Sub topic 7
What frameworks add, and what they cost
This chapter assumes you can write basic Python and have called an LLM chat API at least once. It also assumes you have seen the manual versions of structured output, tool calling, an agent loop, and retrieval. The goal is to name what a framework gives you in exchange for what it takes, so you can judge LangChain, LlamaIndex, and PydanticAI in the next chapters.
The layers between your code and the model
A provider SDK is a client library. It builds the HTTP request, sends it, handles authentication, and parses the response into Python objects. A framework sits on top of one or more SDKs and adds its own types, helpers, and conventions.
The dotted line matters. A framework is optional at every point. You can call the SDK directly for one feature and use the framework for another.
What frameworks add
Most framework features answer one of the problems from the earlier chapters. Five show up in nearly every project.
1. A common interface across providers
Each provider SDK has its own request shape, response shape, and error types. A framework wraps them in one chat-model interface. In LangChain, ChatOpenAI and the equivalent classes for other providers all expose invoke, so changing providers mostly means changing the class and its configuration.
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
result = llm.invoke("Explain what an API client library is in one sentence.")
print(result.content)The interface is a lowest common denominator. Features that only one provider offers, such as a specific caching option or a provider-specific reasoning setting, often need extra parameters passed through. Those parameters tie you back to that provider, so portability is real for basic chat and partial for everything else.
2. Built-in handling of recurring chores
These are tasks you would otherwise write yourself:
- Retries with backoff on rate limits and transient errors.
- Streaming tokens and combining the pieces into a final message.
- Async and batch execution.
- Conversation history management.
- Prompt templates with named variables.
None of these is hard. The value is that they are written once, tested by many users, and work the same way in every part of your project.
3. Structured output and validation
In the manual version you ask for JSON, parse it, and validate it with Pydantic, then decide what to do on failure. Frameworks fold this into one call. In LangChain, for example, with_structured_output takes a Pydantic class and returns an instance of it:
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
class Ticket(BaseModel):
category: str
urgency: int
llm = ChatOpenAI(model="gpt-4o-mini")
structured_llm = llm.with_structured_output(Ticket)
ticket = structured_llm.invoke("The site is down for all customers.")
print(ticket)Notice what is no longer visible: the system prompt or schema that tells the model the format, the JSON parsing step, and the validation step. Which mechanism the framework picks (JSON mode, a tool call, or a provider's native schema feature) depends on the provider and the library version. That is convenient until the model returns something odd and you need to know what was actually sent.
4. Tool and agent scaffolding
The raw SDK returns a tool call as data. Your code must run the function, append the result to the message list, and call the model again until it stops asking for tools. Frameworks supply that loop, convert Python functions into tool schemas, and add limits such as a maximum number of steps. You get less code, and you give up some control over the loop. You can no longer easily change when it stops, how errors from a tool are shown to the model, or how history is trimmed.
5. Data ingestion and retrieval
This is where the largest code savings appear. Reading PDFs, HTML, and spreadsheets, splitting documents into chunks, embedding them, writing to a vector store, and querying it are all separate steps by hand. A framework such as LlamaIndex covers the whole pipeline in a few lines, and both LangChain and LlamaIndex ship dozens of ready-made loaders and vector store connectors. Writing one connector yourself is simple. Writing and maintaining twenty is not.
What frameworks cost
Abstraction hides the actual request
Your real debugging question is always "what text did the model receive?" A framework may add its own prompt text, reformat messages, merge system instructions, or retry with a modified prompt. If you cannot see the final request, you cannot explain a bad answer. Chapter on observability covers how to look at it. For now, remember that every layer you add is a layer you must be able to inspect.
Debugging gets harder
A failure inside a framework produces a stack trace through the library's internals. You then need to read code you did not write to find out whether your input, the framework, or the model caused the problem. With a direct SDK call, the stack trace is short and ends at an HTTP error you can read.
API churn
LLM frameworks change quickly because the underlying provider features change quickly. Class names move between packages, old chain classes are deprecated, and tutorials written a year ago may not run. Even the examples in this tutorial carry version notes, such as the PydanticAI names output_type and result.output, which differ in older releases. Pin exact versions and plan time for upgrades.
Dependency weight
A framework pulls in many transitive packages. That affects install time, container size, security review, and the chance of version conflicts with the rest of your environment. Integration packages (one per provider or vector store) reduce this, but you still carry more code than a single SDK.
Concepts you must learn
A framework has its own vocabulary: runnables, chains, retrievers, query engines, nodes, agents, dependencies, and run contexts. Learning it is a real cost. It pays off if you use many of the concepts, and it is wasted if you need one helper function.
Lock-in in a different form
Provider lock-in moves to framework lock-in. Your prompts, tool definitions, retrieval code, and tests end up in the framework's types. Switching later means rewriting more than a client call.
A side-by-side summary
| Concern | Direct SDK | Framework |
|---|---|---|
| Lines of code for a basic call | Few | Few |
| Lines of code for retrieval over many file types | Many | Few |
| Visibility of the exact request | Complete | Depends on tooling |
| Switching providers | Rewrite the call sites | Often change one class |
| Using a provider-only feature | Direct | May need pass-through options |
| Upgrade risk | Follows the provider's API | Follows the provider's API and the framework's |
| Concepts to learn | The provider's API | The provider's API and the framework's |
The SDK column does not get easier with scale. The framework column does not get cheaper with scale either. The right choice depends on how many of the five additions above you actually need.
A practical test for each feature
Before adopting a framework feature, ask these questions in order:
- Can I write this myself in under an hour, and will I need to change it later? If yes to both, write it.
- Does the feature touch many external systems (file formats, vector stores, providers)? If yes, the framework's breadth probably beats your own.
- Can I see and log the exact request the feature sends? If not, treat it as a risk.
- How often has this part of the API changed in the last year? Check the release notes.
- Can I remove it later without rewriting unrelated code? If you wrap framework calls in your own small functions, the answer is yes.
Mixing is normal
Real projects rarely pick one approach for everything. A common split:
- Use the provider SDK for simple chat calls and anything that needs a provider-specific feature.
- Use a framework's loaders and retrievers where the document pipeline is the hard part.
- Use a typed-agent library where validated outputs matter most.
Each choice should come from a specific problem it solves. The next chapters look at LangChain, LlamaIndex, and PydanticAI in turn, each against the problems listed here.
Exercise
Your team has a service that makes one chat call per request and asks for a JSON result with three fields. A teammate proposes adding a large framework "for portability and structured output." Using the costs and tests in this chapter, give two reasons to decline for now and one condition that would change your answer.
Show answer
Reasons to decline: (1) The service uses only a chat call plus a Pydantic validation step, which is a few lines with the SDK, so the framework adds dependency weight and API churn risk without removing much code. (2) The framework hides the exact request behind its structured-output mechanism, which makes debugging bad outputs harder than with a direct call. A condition that would change the answer: the service must support several providers, or must ingest many document formats and vector stores, so the framework's shared interface and ready-made connectors would replace a lot of code you would otherwise write and maintain. Even then, wrap framework calls in your own function so you can remove it later.
Exercise
Name three costs that a framework adds that a direct SDK call does not, and say how pinning versions and wrapping calls in your own function each reduces one of them.
Show answer
Three costs: API churn (names and packages change between releases), debugging through library internals, and framework-specific concepts that spread through your code. Pinning exact versions reduces the churn cost, because upgrades happen when you choose, not when a dependency resolves differently. Wrapping framework calls in your own function reduces the spread of framework types through your code, which makes replacing or removing the framework a change to one file.