Neuron AI: LLM Summaries
Lowering Token Consumption through Summaries. This repository gives 3 ways to create summaries for the LLM's chat history. The summaries in turn lower token usage for subsequent API calls.
Table of Contents
Installation
- Cloning the Repo. Clone this repo from Github directly.
- Providers. In the summary agents, we give a choice of 2 providers for trying out the repo:
- Ollama (Free). Ollama keeps our LLMs local, though we should have at least one GPU (or be very patient if we don't use a smaller model as given in this repo).
- OpenRouter (Almost Free). OpenRouter provides managed LLMs modelled after the OpenAI API. There is a minimal one-time charge to use free models.
- Embeddings (for RAG). Two free options are to use Ollama, or open a free account in Cohere in order to translate sentences into embeddings.
- Overview of Embeddings. A good overview of embeddings can be found on Hugging Face 🤗.
- Informal Definition.
- Embeddings are translations of words into vectors (arrays of numbers) that the computer can understand.
- These vector translations are closer to or further away from each other in vector space, e.g. 'dog' is closer to 'cat' than it is to 'moon'.
- How close words are to each other in vector space maps to how close their meanings are to humans.
- This is partially how LLMs 'understand' language in deep learning, as well as how recommender systems work.
- Vector Database (for RAG). Download Qdrant (Docker), a vector database, which allows us to store embeddings persistently.
- Insecure by Default. Qdrant's default installation isn't meant for use in production because it's insecure. This page talks about how to harden it, but for the rest of this article we'll just use defaults.
- Run the Vector DB in the repo's main folder. Notice too that it creates a bind mount wherever you run it from:
$ docker run -p 6333:6333 -p 6334:6334 \ --detach \ -v "$(pwd)/qdrant_storage:/qdrant/storage:z" \ qdrant/qdrant- Now that Qdrant is running, insert a collection for Neuron AI:
$ curl -X PUT "http://localhost:6333/collections/neuron-ai" \ -H "Content-Type: application/json" \ -d '{ "vectors": { "size": 1536, "distance": "Cosine" } }'- Managed (Secure) Account. An account can be opened with Quadrant, e.g. if we don't want to set up a secured version on Docker for prod, or we plan on adding many records in the vector DB.
Use
There are 3 buttons on the frontend of this project, each of which accomplishes summarizing chat history in a slightly different way:
How Summaries Work
Summaries involve compressing the LLM's memory from a larger array of elements into a single element that the LLM can understand, for background context.
- Normally, the chat array adds one element per speaker on every button click. The token consumption per API call can therefore become very large.
- The summarized array however replaces the chat array, and is sent back to the frontend with only three elements, in this order: the summary of the chat so far, the user's last interaction, and the LLM's response to that interaction.
- Summarizing Too Often Will Degrade Conversation Quality. To prevent this, we write a conditional statement for the summary.
- Here's one way to do so according to the context window:
# app/Http/Controllers/AgentController.php:
if ($chatAgent->getFreeMemory() < 5000) {
// ...
}
# app/Neuron/Agents/ChatAgent.php:
public function getFreeMemory()
{
if (isset($this->chatHistory)) {
return $this->chatHistory->getFreeMemory();
}
return null;
}
The Summary Itself
A summary is run on its own agent, after the main agent has returned so that we may also include the LLM's last response in the summary:
# app/Http/Controllers/AgentController.php:
$messages[] = new AssistantMessage($content['content']);
$content['summary'] = SummaryAgent::make()
->chat(new UserMessage($this->getSummary($messages)))
->getContent();
Summaries through a Standard Agent
By summarizing through a standard agent, extending inspector-apm/neuron-ai/src/Agent.php, we have no need for an embeddings provider and / or a vector database.
There are two developer-defined classes involved in creating agentic summaries:
- The
ChatAgentClass (app/Neuron/Agents/ChatAgent.php). The main class to carry on a conversation with the end user. - The
SummaryAgentClass (app/Neuron/RAG/SummaryAgentRAG.php). A second class to fetch summaries of the conversation so far, preferably under a developer-defined condition:
# app/Http/Controllers/AgentController.php:
use App\Neuron\Agents\ChatAgent;
use App\Neuron\Agents\SummaryAgent;
// ...
public function callWithAgent(Request $request): array
{
$data = $request->post('data');
if (!$data) return ['data' => []];
// Bring the messages into Neuron's format:
$messages = $this->formatMessages($data);
// The main agent:
$chatAgent = ChatAgent::make();
$response = $chatAgent->chat($messages);
$content['content'] = $response->getContent();
// Dev-defined condition (<10% of default context window):
if ($chatAgent->getFreeMemory() < 5000) {
// Put the most recent message from the LLM into the list:
$messages[] = new AssistantMessage($content['content']);
// Make another call to the LLM's API, and put that under its own key within `$content`:
$content['summary'] = SummaryAgent::make()
->chat(new UserMessage($this->getSummary($messages)))
->getContent();
}
return ['data' => $content];
}
Here, we included the <10% of the default context --- rather than e.g. getFreeMemory() < 1 --- because the main ChatAgent class will clear its context window before this condition is reached, i.e. during the main agent's call.
But we can use any if statement in this condition's place. For example, we could return a summary after a certain number of calls to the agent through defining, storing, and retieving a number_of_calls column on one of our SQL tables.
Summaries through RAG
We can also summarize chats that use Retrieval Augmented Generation (RAG). For this we have to include both an embeddings provider and a vector database.
Here's the call from the controller:
# app/Http/Controllers/AgentController.php:
use App\Neuron\Agents\ChatAgentRAG;
use App\Neuron\Agents\SummaryAgentRAG;
// ...
public function callWithRAG(Request $request): array
{
$data = $request->post('data');
$customSystemPrompt = $request->post('customSystemPrompt');
if (! $data) {
return ['data' => []];
}
$messages = $this->formatMessages($data);
$chatAgentRAG = ChatAgentRAG::make();
$response = $chatAgentRAG->chat($messages);
$content['content'] = $response->getContent();
if ($chatAgentRAG->getFreeMemory() < 5000) {
$messages[] = new AssistantMessage($content['content']);
$content['summary'] = SummaryAgentRAG::make($customSystemPrompt)
->chat(new UserMessage($this->getSummary($messages)))
->getContent();
}
return ['data' => $content];
}
A summary can be created with RAG's preprocessor in 2 ways within App\Neuron\Agents\SummaryAgentRAG::preProcessors():
QueryTransformationPreProcessor::$customPrompt. The source code says this variable is a 'Custom system prompt to override built-in transformations strategies'. We've overriden the system prompt with our custom summarization prompt; no changes to the sourcecode are necessary.PreProcessor::SUMMARY(app/Neuron/RAG/PreProcessor/QueryTransformationPreProcessor.php). Here we've re-created a part of the sourcecode, and added the summary to its own function.- Code re-creation is the most elegant / least-hacky way (as far as I've gathered) to demonstrate this, because of the use of the use of enums, which can't be extended.
A Note on this Implementation of Summaries
- Laravel. This implementation uses Laravel because of its mature features out-of-the-box. However, everything here that relates to summaries is modularized within the folder
Neuron.- The only things that ought to be changed for e.g., vanilla PHP are: the name of main folder (for example from
Neuron/tosrc/), the namespaces of the classes withinNeuron, and thecomposer.jsonfile e.g.:
- The only things that ought to be changed for e.g., vanilla PHP are: the name of main folder (for example from
# Converting to Vanilla PHP:
{
"name": "mgraichy/neuron-ai",
"description": "Summaries for Neuron AI",
"license": "MIT",
"autoload": {
"psr-4": {
"Summaries\\": "src/"
}
},
"require": {
"inspector-apm/neuron-ai": "^1.14"
}
}
- The Implementation's Backend. The BE requires a user in the DB to log in.
- To create one, make sure you have a DB bound to your Laravel instance, and then uncomment the lines in
Route::get('/', ...)inroutes\web.php.
- To create one, make sure you have a DB bound to your Laravel instance, and then uncomment the lines in
- The Implementation's Frontend (in
resources/views/ai/ai-page.blade.php). The FE is very minimal, meant only to nominally show summaries in action. It uses vanilla JS, some vanilla CSS, and tailwindcss.npm run buildshould be run once in order to view the FE properly.
License
This repo is licensed under The MIT License.