Knowledge Base · Learning paths
Emerging Architectures for LLM Applications
This article outlines an emerging reference architecture for LLM applications, with a focus on in-context learning design patterns. It covers core components such as data pipelines, vector databases, orchestration, LLM caching, and logging, offering developers a practical stack reference.
Translated from Chinese by AI. Spotted an issue? Use the feedback button.
Original URL: https://a16z.com/2023/06/20/emerging-architectures-for-llm-applications/
Translator: WaytoAGI (Way to AGI). If there are any imperfections, please correct them in the paragraph comments; many thanks.
Published: June 20, 2023
Large language models (LLMs) are powerful new infrastructure for building software. But because they are so new—and behave so differently from ordinary compute resources—it is not always obvious how to use them.
In this article, we share a reference architecture for the emerging LLM application stack. It shows the most common systems, tools, and design patterns we have seen AI startups and established technology companies use. This stack is still very early and may change significantly as the underlying technology advances, but we hope it can serve as a useful reference for developers working with LLMs now.
This work is based on conversations with AI startup founders and engineers. We especially relied on input from: Ted Benson, Harrison Chase, Ben Firshman, Ali Ghodsi, Raza Habib, Andrej Karpathy, Greg Kogan, Jerry Liu, Moin Nadeem, Diego Oppenheimer, Shreya Rajpal, Ion Stoica, Dennis Xu, Matei Zaharia, and Jared Zoneraich. Thank you for your help!
The Stack
Here is our current view of the LLM application stack:
Below is a linked list of each item for quick reference:
The titles are, in order:
"Data pipelines"
"Embedding model"
"Vector database"
"Playground" — sandbox / testing environment
"Orchestration"
"APIs/plugins" — API endpoints / plugins
"LLM cache" — large language model cache
"Logging / LLMops" — logging / large language model operations
"Validation"
"App hosting"
"LLM APIs (proprietary)" — proprietary large language model API endpoints
"LLM APIs (open)" — open large language model API endpoints
"Cloud providers"
"Opinionated clouds" — cloud services with a specific strategy or point of view
There are many ways to build applications with large language models (LLMs), including training a model from scratch, fine-tuning an open-source model, or using a hosted API. The stack we show here is based on in-context learning, the design pattern we see most developers start with (and one that is only possible with foundation models).
The next section briefly explains this pattern; experienced LLM developers can skip it.
Design Pattern: In-Context Learning
The core idea of in-context learning is to use an off-the-shelf LLM (i.e., without any fine-tuning) and then control its behavior through clever prompting and by conditioning it on private "context" data.
For example, suppose you're building a chatbot to answer questions about a set of legal documents. In a naive approach, you could paste all the documents into a ChatGPT or GPT-4 prompt and then ask questions about them at the end. This might work for very small datasets, but it doesn't scale. The largest GPT-4 model can only handle about 50 pages of input text, and performance (measured by inference time and accuracy) degrades severely as you approach this limit, known as the context window.
In-context learning solves this with a clever trick: instead of sending all the documents with every LLM prompt, it sends only a handful of the most relevant documents. And the most relevant documents are determined with the help of... you guessed it... the LLM.
At a very high level, the workflow can be divided into three stages:
-
Data preprocessing/embedding: This stage involves storing the private data to be retrieved later (in our example, the legal documents). Typically, documents are split into chunks, passed through an embedding model, and then stored in a specialized database called a vector database.
-
Prompt construction/retrieval: When a user submits a query (a legal question in this example), the application constructs a series of prompts to submit to the language model. A compiled prompt typically combines a developer-hardcoded prompt template; effective output examples known as few-shot examples; any necessary information retrieved from external APIs; and a set of relevant documents retrieved from the vector database.
-
Prompt execution/inference: Once the prompts are compiled, they are submitted to a pre-trained LLM for inference, including proprietary model APIs and open-source or self-trained models. Some developers also add operational systems such as logging, caching, and validation at this stage.
This looks like a lot of work, but it's usually simpler than the alternative: training or fine-tuning the LLM itself. You don't need a dedicated team of machine learning engineers for in-context learning. You also don't need to host your own infrastructure or buy expensive dedicated instances from OpenAI. This pattern effectively reduces an AI problem to a data engineering problem that most startups and large companies already know how to solve. For relatively small datasets, it also tends to outperform fine-tuning—because a specific piece of information needs to appear in the training set at least about 10 times for an LLM to memorize it through fine-tuning—and it can incorporate new data in near real-time.
One of the biggest questions about in-context learning is: what happens if we simply change the underlying model to increase the context window? This is indeed possible and is an active area of research (see, for example, the Hyena paper or this recent article). But it comes with many trade-offs—mainly, the cost and time of inference scale quadratically with prompt length. Today, even linear scaling (the best theoretical result) is too costly for many applications. At current API rates, a single GPT-4 query of more than 10,000 pages would cost hundreds of dollars. So we don't expect massive changes to the stack based on expanded context windows, but we'll comment more on this in the body of the post.
If you want a deeper dive into in-context learning, the AI Canon has many great resources (especially the "Practical Guide to Building with LLMs" section). In the rest of this post, we'll walk you through the reference stack following the workflow above.
Data Preprocessing / Embeddings
The contextual data for LLM applications includes text documents, PDFs, and even structured formats such as CSV or SQL tables. Data loading and transformation solutions for this data vary widely among the developers we interviewed. Most use traditional ETL tools such as Databricks or Airflow. Some also use document loaders built into orchestration frameworks, such as LangChain (powered by Unstructured) and LlamaIndex (powered by Llama Hub). However, we believe this part of the stack is relatively underdeveloped and that there is an opportunity to build data replication solutions specifically for LLM applications.
For embeddings, most developers use the OpenAI API, specifically the text-embedding-ada-002 model. It is easy to use (especially if you are already using other OpenAI APIs), delivers fairly good results, and is becoming cheaper. Some larger enterprises are also exploring Cohere, whose product work is more focused on embeddings and which performs better in certain scenarios. For developers who prefer open source, Hugging Face's Sentence Transformers library is the standard. You can also create different types of embeddings for different use cases; this is a niche practice today but a promising area of research.
From a systems perspective, the most important part of the preprocessing pipeline is the vector database. It is responsible for efficiently storing, comparing, and retrieving up to billions of embeddings (i.e., vectors). The most common choice we see in the market is Pinecone. It is the default because it is fully cloud-hosted, making it easy to get started, and it has many features that large enterprises need in production (e.g., good performance at scale, SSO, and uptime SLAs).
However, there are many vector databases available. In particular:
-
Open-source systems such as Weaviate, Vespa, and Qdrant: They generally have excellent single-node performance and can be customized for specific applications, making them popular with experienced AI teams who like to build custom platforms.
-
Local vector management libraries such as Chroma and Faiss: They offer a rich developer experience and are easy to get started with for small applications and development experiments. They are not necessarily replacements for full databases at scale.
-
OLTP extensions such as pgvector: This is a good vector-support solution for developers who see a database-shaped hole in every problem and try to plug Postgres into it, or for enterprises that buy most of their data infrastructure from a single cloud provider. In the long run, it is unclear whether tightly coupling vector and scalar workloads makes sense.
Looking ahead, most open-source vector database companies are developing cloud services. Our research indicates that achieving strong performance in the cloud across a design space spanning a wide range of possible use cases is a very difficult problem. Therefore, the set of options may not change substantially in the short term, but it may change over the long term. The key question is whether vector databases will consolidate around one or two popular systems, as their OLTP and OLAP counterparts have.
Another open question is how embeddings and vector databases will evolve as the context windows available in most models grow. It is tempting to say that embeddings will become less relevant because contextual data can be placed directly into the prompt. However, expert feedback on this topic suggests the opposite—embedding pipelines may become more important over time. Large context windows are a powerful tool, but they also require significant computational cost. Therefore, using them effectively becomes imperative. We may start to see different types of embedding models become popular—trained directly for model relevance—as well as vector databases designed to enable and exploit this.
Prompt Construction/Retrieval
Strategies for prompting LLMs and incorporating contextual data are becoming increasingly complex—and increasingly important as a source of product differentiation. Most developers start new projects by trying simple prompts that include direct instructions (zero-shot prompting) or perhaps some example outputs (few-shot prompting). These prompts often produce good results, but they fall short of the level of accuracy required for production deployment.
The next level of prompting techniques aims to ground model responses in some source of truth and provide external context that the model was not trained on. The Prompt Engineering Guide lists no fewer than 12 (!) more advanced prompting strategies, including chain-of-thought, self-consistency, generated knowledge, tree of thoughts, directional stimulus, and many others. These strategies can also be used together to support different LLM use cases such as document question answering and chatbots.
This is where orchestration frameworks such as LangChain and LlamaIndex shine. They abstract away many of the details of prompt chains; interfaces with external APIs (including determining when an API call is needed); retrieval of contextual data from vector databases; and maintaining memory across multiple LLM calls. They also provide templates for many of the common applications mentioned above. Their output is a prompt or a series of prompts to be submitted to a language model. These frameworks are widely used by hobbyists and startups looking to launch applications, with LangChain as the leader.
LangChain is still a relatively new project (currently version 0.0.201), but we are already beginning to see applications built with it move into production. Some developers, especially early adopters of LLMs, prefer to switch to native Python in production to eliminate the extra dependency. However, we expect that this DIY approach will be used less over time in most use cases, similar to what happened with the traditional web application stack.
Sharp-eyed readers will notice a seemingly odd entry in the orchestration box: ChatGPT. Under normal circumstances, ChatGPT is an application, not a developer tool. But it can also be accessed as an API. And if you look closely, it performs some of the same functions as other orchestration frameworks, such as abstracting away the need for custom prompts, maintaining state, and retrieving contextual data through plugins, APIs, or other sources. Although ChatGPT is not a direct competitor to the other tools listed here, it can be viewed as an alternative solution, and it may ultimately become a viable, simple alternative for ad-hoc builds.
Prompt Execution / Inference
Today, OpenAI has become the leader in the language model space. Nearly every developer we encounter starts new LLM applications using the OpenAI API, typically with the gpt-4 or gpt-4-32k models. This provides the best-case scenario for application performance and is easy to use, since it operates across a wide range of input domains and usually does not require fine-tuning or self-hosting.
When a project goes into production and begins to scale, a broader set of options comes into play. Some common questions we hear include:
-
Switching to gpt-3.5-turbo: It is about 50x cheaper than GPT-4 and significantly faster. Many applications do not need GPT-4-level accuracy, but they do need low-latency inference and cost-effective support for free users.
-
Experimenting with other proprietary vendors (especially Anthropic's Claude models): Claude offers fast inference, GPT-3.5-level accuracy, more customization options for large customers, and context windows of up to 100k (although we find that accuracy degrades as input length increases).
-
Routing some requests to open-source models: This can be especially effective in high-traffic B2C use cases (such as search or chat), where query complexity varies widely and free users need to be served cheaply.
- This usually makes the most sense in combination with fine-tuning open-source base models. We will not go deep into that tool stack in this article, but a growing number of engineering teams are using platforms such as Databricks, Anyscale, Mosaic, Modal, and RunPod.
- Open-source models can be used with a variety of inference options, including simple API interfaces from Hugging Face and Replicate; raw compute resources from major cloud providers; and the more opinionated cloud services listed above.
At present, open-source models lag behind proprietary offerings, but the gap is starting to close. Meta's LLaMa models set a new standard for open-source accuracy and sparked a wave of variants. Because LLaMa was licensed only for research use, many new providers have stepped in to train alternative base models (for example, Together, Mosaic, Falcon, and Mistral). Meta is also discussing a truly open-source release of LLaMa 2.
When (rather than if) open-source LLMs reach accuracy comparable to GPT-3.5, we expect to see a Stable Diffusion moment for text—including a great deal of experimentation with, sharing of, and production use of fine-tuned models. Hosting companies like Replicate are already adding tools that make these models easier for software developers to use. Developers are increasingly convinced that smaller, fine-tuned models can achieve state-of-the-art accuracy in narrow use cases.
Most of the developers we interviewed have not yet gone deep into LLM operations tooling. Caching is relatively common—usually based on Redis—because it can shorten application response times and reduce costs. Tools such as Weights & Biases and MLflow (ported over from traditional machine learning) or PromptLayer and Helicone (designed specifically for LLMs) are also fairly widely used. They can log, trace, and evaluate LLM outputs, usually to improve prompt construction, adjust pipelines, or select models. There are also many new tools under development to validate LLM outputs (such as Guardrails) or detect prompt injection attacks (such as Rebuff). Most of these operations tools encourage the use of their own Python clients for LLM calls, so it will be interesting to see how these solutions coexist over time.
Finally, the static parts of an LLM application (that is, everything other than the model) also need to be hosted somewhere. So far, the most common solutions we have seen are standard options such as Vercel or major cloud providers. However, two new categories are emerging. Startups such as Steamship provide end-to-end hosting for LLM applications, including orchestration (LangChain), multi-tenant data context, asynchronous tasks, vector storage, and secret management. Companies such as Anyscale and Modal allow developers to host models and Python code in one place.
What about agents?
The most important missing component in this reference architecture is the AI agent framework. AutoGPT, described as "an experimental open-source attempt to make GPT-4 fully autonomous," was the fastest-growing Github project in history this spring, and virtually every AI project or startup today incorporates some form of agent.
Most developers we spoke with are very excited about the potential of agents. The in-context learning patterns we describe in this post are effective at solving hallucination and data freshness issues to better support content generation tasks. Agents, on the other hand, offer a whole new set of capabilities for AI applications: solving complex problems, taking actions on the outside world, and learning from experience after deployment. They achieve this through a combination of advanced reasoning/planning, tool use, and memory/recursion/self-reflection.
As a result, agents have the potential to become a core part of LLM application architecture (or even take over the entire stack, if you believe in recursive self-improvement). Existing frameworks like LangChain already incorporate some agent concepts. There's just one problem: agents don't really work yet. Most agent frameworks today are at the proof-of-concept stage—capable of incredible demos, but not yet able to complete tasks reliably and reproducibly. We're watching closely to see how they evolve in the near future.
Looking ahead
Pretrained AI models represent the most significant change in software architecture since the internet. They enable individual developers to build incredible AI applications in a matter of days—applications that surpass supervised machine learning projects built by large teams over several months.
The tools and patterns we list here are likely a starting point for integrating LLMs, not the endpoint. We will update this information when major changes occur (for example, a shift toward model training) and publish new reference architectures where it makes sense. If you have any feedback or suggestions, please contact us.