Blog / Generative AI
What does it cost to give your AI context? Less than you think
A proof of concept that generates embeddings serverlessly, at $0.03 per million tokens, and an architecture that lets you start out paying only for what you use.
This article brings together my research, reflections, and experiments on neural networks, specifically LLMs (large language models), and how they’re applied in practice. These reflections are about ways to implement these models on a tight budget, and they also led me to build a proof of concept called Serverless LLM. So I had two goals in mind for this article: first, to explain what LLMs are and the main strategies for using them in production, and second, to detail how and why I built this proof of concept. You’ll see throughout the text that these goals are closely linked, since Serverless LLM is my way of showing you, concretely, how to build simple, efficient solutions with these models.
A good place to start would be explaining why I’ve become so interested in this topic and decided to spend my free weekend hours building this proof of concept. The explanation is simple, or at least the reason is. There’s a huge gap between using an LLM in a personal setting, on your own computer for example, and using it in production. In production, there are many dimensions to evaluate, from the solution’s complexity to its scalability and quality. With that in mind, I started studying the main problems these models could solve today and the possible ways to implement them. Serverless LLM is meant to get people thinking and to offer a starting point for finding more efficient ways to run these models, with a focus on cost, so that people and companies on tight budgets can work with them too.
For those of you wondering “what is an LLM?”: large language models (LLMs) are a category of machine learning models specialized, as the name suggests, in natural language processing. In other words, they’re very large neural network models that, given an initial text, can predict what the next words should be, producing coherent text that fits the input.
When we ask these models a question, they simply make a probabilistic assessment, generating text one piece after another, each time picking what’s most likely to make sense given what came before (hence the name generative). Their results are shaped both by their training on huge amounts of data, which lets them learn the patterns and features of human language, and by the vast computing resources available today.
When we talk about practical applications of language models, one of the most sought-after goals is the ability to get relevant, objective information on very specific subjects. For example, let’s say I want to build a solution that helps patients and doctors investigate and better understand the side effects of medicines and how they compare. Here, state-of-the-art models like ChatGPT, Claude, or Gemini (the world of language models evolves so fast that, by the time you read this, new competitors will probably have shown up!) won’t be able to help us on their own. Because they were trained on generic datasets that aren’t always up to date, if we ask them this question, they’re unlikely to give satisfactory answers.
RAG to the rescue!
This challenge is so common that people have already come up with a way to tackle it, and they called it RAG, or retrieval-augmented generation. Before explaining this solution, I’ll first cover the fundamental concept, the heart of it all, the thing that makes the magic happen: embeddings, a “byproduct” of these models. Here, I’ll let Claude 3 do the explaining. After all, who better to explain them than an expert at generating them?
“During the training of generative language models such as GPT, the model learns to represent words, sentences, and paragraphs as numerical vectors called embeddings. These capture information about the meaning and context of words, allowing the model to understand and generate language more efficiently. Embeddings can therefore be considered a valuable ‘byproduct’ of generative models, since they contain dense knowledge and can be used in a wide range of natural language processing tasks, even without needing the full generative model.”
— Claude 3
That is, neural network models naturally create numerical representations of the patterns they learn; that’s at the core of how they work. And tapping into this deeper mechanism of the model, not just its output, is also very valuable. Put another way, it’s like turning a text into a list of 1,000 numbers, or embeddings, that holds a whole set of semantic relationships and patterns the model discovered in the text. At first glance, looking at the numbers, we can’t make sense of these patterns, but they’re there.
Back to RAG and its stages. It can be split into two main blocks: (1) building the knowledge base and (2) retrieving/querying that information.
In the first block, before anything else, we need access to a dataset with information about the domain we want to explore. In our medicines example, the source of that data could be the medicines section of the Brazilian Ministry of Health’s Virtual Library (BVMS). Once we’ve extracted it, the next step is to convert all of it into a language model’s vector space, that is, into embeddings. And finally, we store all this converted information in a vector database.
In the second block, we take the user’s question, convert it into embeddings at runtime, and send it to the vector database to run a similarity search. As I said, this is where the magic happens, and it’s why these vectors matter so much. This simple similarity search hides all the complexity of the semantic analysis the model performed when it turned the texts into vectors. In other words, when a user asks our system, “Which is better for children with a fever: ibuprofen or dipyrone (metamizole)?” the system searches the database for the vectors most similar to the question’s. And that automatically takes into account all the semantic patterns the model discovered 🤯.
Hold on, the second block isn’t over yet: there’s still the final step. If we showed the user the result of this search, it would be a list of the articles most semantically similar to their question. But we want the result to be a clear, accurate answer to the question, and that’s the language model’s job, just as we’re used to seeing in the ChatGPT console, for example. So the final step takes the top results of the vector search, retrieves the texts that correspond to those vectors, and sends them to the model along with the question we want answered:
You are an expert in medicines. Answer this question using only the articles below.
Question: {User's question}
Articles: {Content of the X articles most similar to the question}
Practical challenges
There’s a problem that people working with these kinds of models inevitably run into: it’s all very expensive! It doesn’t matter which path you take, whether you use OpenAI’s APIs, for example, or provision and run open‑source models on your own infrastructure or with cloud computing providers. Few companies have the budget to pay that bill.
Every data engineer has to face the challenge of finding creative, efficient, and cheap ways to build their solutions, and this case is no different. In fact, here it’s imperative! It’s in this context that two factors influenced me and motivated me to tackle this problem. First, smaller open‑source models with increasingly surprising performance are emerging, and second, frameworks are also emerging that make it possible to put these models into production with incredible performance.
One of these frameworks stands out: TEI (Text Embeddings Inference). As the name suggests, it’s used to deploy embedding models. Developed by the team at Hugging Face, the company known for creating the Transformers library and maintaining an extensive repository of pre-trained models, this framework is easy to use, extremely fast (or, as they themselves put it, “Blazing fast”), and can be used to build RAG’s core component.
Now the picture starts to get clearer. You can use lighter models and squeeze the most performance out of them with these frameworks. That’s good, but it can get better. There’s still one small catch: the way TEI was designed, it needs infrastructure provisioned 100% of the time, or at least most of the time. And in some cases, precisely those with leaner budgets and initiatives that are just getting started, it’s better to pay only when you use the resource. This is where serverless comes in: a service model in which the cloud computing provider manages the infrastructure and offers usage-based pricing.
So why not run TEI on serverless services, like AWS Lambda? Going serverless simplifies your solution and makes it more efficient, since the provider removes the need to manage servers, and you pay only for the requests processed and the resources consumed. A great idea, but to my dismay, I found out that this framework isn’t compatible with this kind of service model.
And now, my modest contribution: Serverless LLM
After going through its code, I realized that TEI packages everything it needs to run into a single Docker image. That realization was really exciting and led me to test a hypothesis: since AWS Lambda also supports this kind of image, could I modify the original version so that TEI could run on it? And the answer was yes! To skip ahead, with the changes in place, the framework ran on Lambda without any problems.
With a compatible image in hand, I moved on to deploying the service on AWS, in these steps:
- Building the Docker image from the modified source code.
- Storing the image in AWS’s container registry, ECR.
- Creating the Lambda function from a container image and associating the image stored in ECR with the new function.
A few points about this deployment are worth highlighting. First, to improve response times for requests to these models, I changed the framework’s behavior so that its image would ship with the chosen model already baked in. This cuts execution time considerably, since the model doesn’t have to be downloaded on every startup (serverless services have ephemeral infrastructure). And second, I made sure to reuse the model loaded in the Lambda function’s memory, since AWS doesn’t provision/deprovision its infrastructure on every request. By using the singleton pattern, we ensure that, once loaded into memory, the model is always reused as long as that instance stays up.
For the test, I used the small version of Multilingual E5 Text Embeddings. This model was developed by Microsoft’s research team and delivers great results across many languages, ranking high on the category leaderboard. It also has an MIT license, which allows free commercial and non-commercial use.
You may have noticed that I chose a small model for Serverless LLM to run. On one hand, this is in line with the trend I mentioned earlier: much smaller models than usual are emerging, with great performance (with a few caveats on the “great,” since it’s always important to consider the context of use). On the other hand, I named the project Serverless LLM, of all things, with the first L standing for Large. Maybe I overdid it with the name, but I’ll ask for a little poetic license here, since a name like Serverless Small-To-Medium LM would be odd, to say the least, and, besides, embedding models are naturally smaller than chat models.
Results
With the process and choices explained, on to the tests. I sent a 600-token text to the model and measured the time it took to return the result. I took two measurements: the time with a cold start (including infrastructure provisioning and service startup) and the time without one. With the results in hand, I calculated (1) what the cost per million tokens processed would be, not counting the AWS free tier (assuming 90% of runs without a cold start and 10% with one), and (2) how many million tokens per month you can process for free under that free tier.
- Cost per million tokens, in dollars
- 0.03
- Million tokens free per month
- 17.8
- Response time without a cold start
- 300ms
- Response time with a cold start
- 4s
Based on these results, we can draw a few conclusions about using serverless in this context:
- The model’s response time suggests that this kind of architecture can be used in production applications.
- Thanks to the serverless pattern, where you pay only for what you use, you can arrive at a per-token pricing model. And even as a proof of concept, it already reached a highly competitive price.
- Thanks to the quota AWS gives Lambda users every month, you can process a large volume of tokens without paying anything.
- With your own implementation, you have more control over its availability. I, for one, have been hit by OpenAI API throttling many times. And that was just while I was learning about RAG and processing the datasets. Imagine the risk in production settings.
As for the TEI framework and the adaptations I made, a few reflections are in order too:
- The execution times for processing 600 tokens per request on commodity hardware, with no GPU, are surprising. The framework really does live up to its promise. And from what I learned along the way, three things are largely responsible for this: a Docker image optimized for CPU, the Safetensors format for the models, and a Rust library called candle (both Safetensors and candle were also developed by the Hugging Face team). Together, they make loading the model and processing tokens very fast.
- We’re talking about a simple adaptation of the framework, with quick, less-than-optimal changes so it could run on AWS Lambda. If the changes had followed the framework’s own patterns (e.g., a Lambda handler in Rust that talks directly to the candle library), I imagine performance would be even better.
- There’s no support for quantized models on CPU. That’s another area with the potential to push performance even further.
Where do Serverless LLM and RAG meet?
As I said earlier, embeddings are the heart of RAG. So a solid implementation of this capability is key to its success. By generating embeddings with a serverless architecture, you get scalability, resilience, and low cost. That way, we put the pillars in place for running this kind of application in production, overcoming the cost barrier and also ensuring independence from big companies’ services and their potential availability issues.
And to tie up loose ends, I’ll also share a suggested architecture for the whole RAG implementation, using as many AWS serverless services as possible, since AWS is the provider I know best. I hope this gives you a more tangible picture of the whole: how each piece fits with the others, and some possible ways to put it into practice. Actually, I don’t think the picture will be all that complete. Since I haven’t looked into the chat model stage yet, I’ll leave it for a future article.
The philosophy behind this suggested architecture is to be 100% serverless. Here, we use AWS API Gateway to expose the API to the user, and we use Lambdas to (1) orchestrate all the RAG steps, (2) generate the embeddings (this is where Serverless LLM comes in), and (3) load the data into the vector database. For the database, we also stick with a serverless architecture, but in this case the service isn’t offered by AWS. Pinecone offers a serverless version of its database and is one of the standout players today. For the chat model, since I haven’t looked into it yet, my suggestion for now is to integrate with APIs from companies like OpenAI and Google, which keeps the principle of paying only for what you use.
This strategy is great for anyone just starting out, precisely because it lets you build a complete solution without much money. That said, it’s important to stress that every solution has its pros and cons, and this one is no exception. Think of how a “field hospital” is built: in a short time and on a smaller budget, you get every service a hospital needs up and running, with all of its capabilities. This architecture works the same way. Now, this “field-hospital RAG” needs to be revisited as your initiative grows from a simple adventure into something big, just as a field hospital can’t be turned into something permanent. For example, for many well-established products, it makes more sense to keep dedicated infrastructure. So use the right tools for the right context and the right problems.
Conclusion
What a journey! In this piece, I’ve laid out important concepts around large language models and ways to apply them to real problems, and I even ventured into proofs of concept with surprising results. All to show that this topic doesn’t have to be limited to big tech companies. You can do a lot with a little.
Now, for those of you who got excited about Serverless LLM and are thinking of using it in real-world settings, here’s a warning: I don’t recommend using it in production as it stands; it was only a proof of concept. But I’ll leave you with an invitation and a reflection. The reflection, as I said earlier, is that yes, you can build a solution around LLMs while spending very little. And the invitation goes both to the Hugging Face team, to build this capability into TEI, and to the open‑source community, to propose adaptations and improvements to Serverless LLM. As for the chat model, since it’s a relevant and challenging topic, it will be the subject of future research and a new article.
Originally published in Portuguese on Medium, Mar 17, 2024.