Sub topic 14
Migrating and mixing approaches
This chapter assumes you have read the earlier chapters of this tutorial. You should be comfortable with Python classes and virtual environments, have called a chat API, and know the basic shape of structured output, tool calling, and retrieval. It does not repeat how each library works. It covers how to move between a provider SDK and a framework, and how to use both in one codebase.
Why migration is usually partial
Most projects don't switch wholesale from one approach to another. A team starts with the raw SDK and later adopts LlamaIndex for ingestion. Another team starts with LangChain and later finds that one chain is hard to debug, so they rewrite that single chain against the SDK.
Partial migration works because the approaches interoperate at plain-data boundaries:
- Chat messages are lists of role and content pairs.
- Tool schemas are JSON Schema.
- Structured output is a Pydantic model.
- Retrieved context is a list of strings.
If your code passes these plain types between components, you can replace any one component without touching the others. If your code passes framework objects around (a LangChain Runnable, a LlamaIndex Index), every caller is tied to that framework.
Find the seams first
A seam is a place where you can swap one implementation for another without editing the callers. Before changing anything, list your LLM-touching code and mark where each framework object enters and leaves.
A quick inventory command shows how far the framework has spread:
grep -rEn "^(from|import) (langchain|llama_index|pydantic_ai)" src/Files with many matches are deeply coupled. Files with one or two matches are good places to start.
Step 1: put an interface of your own in front
Define the smallest interface your application needs. Write it in your own terms (strings in, strings out), not in the framework's. Then write one adapter per backend.
from typing import Protocol
from langchain_openai import ChatOpenAI
from openai import OpenAI
class TextModel(Protocol):
def complete(self, system: str, user: str) -> str: ...
class OpenAIModel:
def __init__(self, model: str = "gpt-4o-mini") -> None:
self._client = OpenAI()
self._model = model
def complete(self, system: str, user: str) -> str:
response = self._client.chat.completions.create(
model=self._model,
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user},
],
)
return response.choices[0].message.content or ""
class LangChainModel:
def __init__(self, model: str = "gpt-4:
self._llm = ChatOpenAI(model=model)
def complete(self, system: str, user: str) -> str:
result = self._llm.invoke([("system)])
return str(result.content)
def summarize(model: TextModel, text: str) -> str:
return model.complete("Summarize in one sentence.", text)`esn't know which backend it gets. Migrating in either direction means changing which adapter you construct. The cost is one thin layer that you now maintain. Keep it narrow. If the interface grows to mirror the whole SDK, you have built your own framework.
Step 2: record behavior before you change it
A swap can alter results without raising errors. Frameworks add default prompts, retry rules, and parsing steps. The raw SDK has none of these unless you write them. Before swapping, capture what the current implementation does on a fixed set of inputs.
import json
from pathlib import Path
CASES = [
"The site is down for all customers.",
"Please update my billing address.",
]
def record(model, path: str = "golden.json") -> None:
outputs = {case: model.complete("Classify the ticket in one word.", case) for case in CASES}
Path(path).write_text(json.dumps(outputs, indent=2))
def compare(model, path: str = "golden.json") -> list[str]:
golden = json.loads(Path(path).read_text())
mismatches = []
for case, expected in golden.items():
actual = model.complete("Classify the ticket in one word.", case)
if actual.strip().lower() != expected.strip().lower():
mismatches.append(case)
return mismatchesModel output varies between runs, so exact equality is a rough check. For free text, compare with a looser rule, such as a keyword check or a score from a grader. For structured output, compare parsed fields, which are stable.
The most useful comparison is the text actually sent to the model. Log the final messages from both implementations and diff them. Differences in system prompt wording, message order, or extra whitespace explain most behavior changes. The observability chapter covered how to capture this.
Migrating from a framework to the raw SDK
The usual reasons are debugging pain, dependency weight, and API churn. Work from the outside in.
- Replace leaf calls first: a single
llm.invokebecomes oneclient.chat.completions.createcall. - Replace output parsers with a Pydantic model and
model_validate_json. This is the manual structured-output pattern from earlier in the tutorial. - Replace tool wrappers with JSON Schema dicts, and write the dispatch loop yourself.
- Replace the chain composition last. A chain of three steps is often three function calls in sequence.
Keep the Pydantic models. They are the portable part of the work, and both approaches can use them:
from openai import OpenAI
from pydantic import BaseModel
from pydantic_ai import Agent
class Ticket(BaseModel):
category: str
urgency: int
def classify_with_sdk(text: str) -> Ticket:
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": 'Reply with JSON like {"category": "billing", "urgency": 3}. Urgency is an integer from 1 to 5.'},
{"role": "user", "content": text},
],
)
return Ticket.model_validate_json(response.choices[0].message.content)
agent = Agent("openai:gpt-4o-mini", output_type=Ticket)
def classify_with_framework(text: str) -> Ticket:
return agent.run_sync(text).outputBoth functions return the same Ticket. Callers cannot tell which one ran, so you can move between them one call site at a time. What you lose in the raw version is the automatic retry on validation failure. Add a small loop that catches ValidationError and re-asks the model if you need that.
Migrating from the raw SDK to a framework
The usual reasons are that your hand-written code is growing into a framework anyway, or that one task has a mature solution elsewhere. Retrieval is the most common case. Writing loaders, chunkers, and index management yourself is a lot of code, and LlamaIndex handles it well.
Adopt the framework for that one job, and keep the rest of your code unchanged.
Mixing approaches in one pipeline
A mixed design is often the best final state. A common split uses LlamaIndex for retrieval and the plain SDK for generation, so you control the final prompt.
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
from openai import OpenAI
documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)
retriever = index.as_retriever(similarity_top_k=3)
client = OpenAI()
def answer(question: str) -> str:
nodes = retriever.retrieve(question)
context = "\n\n".join(node.get_content() for node in nodes)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Answer using only the context. If it is not there, say so."},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
],
)
return response.choices[0].message.content or ""The framework does ingestion and search. You write the prompt, so you can see exactly what the model receives. The default index settings use OpenAI models for embeddings, so you need OPENAI_API_KEY set.
| Row | Framework handles | SDK or your code handles | Watch for |
|---|---|---|---|
| LlamaIndex + SDK | Loading, chunking, embedding, retrieval | Prompt and generation | Two clients to configure and bill |
| PydanticAI + SDK | Typed agent runs for some tasks | Custom loops for special cases | Duplicate retry logic |
| LangChain integrations + SDK | Vendor-specific loaders and connectors | Core model calls | Pulling in a large package for one connector |
Common errors
- Leaking framework types. Functions that return
DocumentorAIMessageobjects force every caller to import the framework. Convert to strings, dicts, or your own Pydantic models at the boundary. - Changing the prompt by accident. A framework's default template may differ from yours. Diff the sent messages as described above.
- Migrating everything at once. A large rewrite cannot be reviewed or rolled back in pieces. Swap one component per change.
- Losing silent features. Retries, timeouts, streaming, and token counting are sometimes built into the framework. List them before removing it, and decide which to rewrite.
- Mismatched versions during overlap. Two libraries may pin different versions of
pydanticoropenai. Check the resolved versions withpip checkafter each change.
Deciding when to stop
Stop migrating when the goal that motivated it is met. If you moved to cut debugging time, measure whether debugging got easier. If a mixed design works and each part has a clear reason to exist, there is no need to unify it. Leave a short note in the repository saying why each library is there, so a later maintainer can tell which dependencies are deliberate.
Exercise
Your service calls LangChain in twelve files. You want to move to the raw OpenAI SDK. What do you do first, and why not rewrite all twelve files in one change?
Show answer
First define a small interface of your own (for example a TextModel Protocol with a complete method) and put the existing LangChain code behind an adapter. Then record current outputs and sent prompts on fixed test inputs. Then write an SDK adapter and switch call sites one at a time, comparing results. A single large rewrite cannot be reviewed or rolled back in parts, and a behavior change from a different default prompt or lost retry would be hard to trace to its cause.
Exercise
You use the plain SDK and want to add document search. Name one way to mix in LlamaIndex without adopting it for the whole app, and name one risk.
Show answer
Use LlamaIndex only for loading, indexing, and retrieval (index.as_retriever(...).retrieve(question)), and pass the retrieved text into your own SDK call so you control the final prompt. Risks include two clients to configure and bill, and default index settings that require an OpenAI API key for embeddings.