Sub topic 2
Writing the agent loop yourself
This chapter assumes basic Python, JSON, HTTP APIs, and one previous LLM API call. The examples use OpenAI-style chat completions.
Writing the agent loop yourself
A tool call is data returned by the model. Your program must execute the named function, append its result, and call the model again. This cycle is an agent loop.
import json
from openai import OpenAI
client = OpenAI()
messages = [{"role": "user", "content": "What is the weather in Paris?"}]
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Return weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
}]
def get_weather(city):
return {"city": city, "temperature_c": 18, "condition": "sunny"}
while True:
response = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, tools=tools
)
message = response.choices[0].message
messages.append(message.model_dump(exclude_none=True))
if not message.tool_calls:
print(message.content)
break
for call in message.tool_calls:
args = json.loads(call.function.arguments)
result = get_weather(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result)
})Set limits for iterations, tool permissions, timeouts, and errors. Otherwise, a faulty model response can create an endless or unsafe loop.
Retrieval-augmented generation by hand
In retrieval-augmented generation (RAG), a retriever selects relevant document chunks before the model answers. A hand-built pipeline usually:
- Loads and splits documents.
- Creates embeddings, which are numeric representations of meaning.
- Stores them in a vector database.
- Embeds the user question and retrieves nearby chunks.
- Places those chunks in the model prompt.
You control chunk size, filters, citations, and failure handling. You also own the indexing and evaluation code.
What frameworks add, and what they cost
Frameworks package repeated work such as retries, message conversion, tool dispatch, memory, tracing, vector stores, and provider adapters.
| Approach | Main strength | Main cost |
|---|---|---|
| Raw SDK | Control and clear requests | More glue code |
| Framework | Faster composition | Hidden state and dependencies |
A framework can reduce implementation time, but debugging may require understanding both its abstractions and the provider API.
LangChain: components and integrations
LangChain focuses on composable components: chat models, prompts, parsers, tools, retrievers, and chains. Its broad integrations help when a project combines providers and services. The trade-off is a larger abstraction surface and more dependency-driven API changes.
LlamaIndex: data-centric retrieval
LlamaIndex focuses on documents and retrieval. It can load files, split them, build indexes, and expose a query engine with little code. Choose it when data ingestion and question answering are central. Inspect its defaults when you need precise chunking, metadata, citations, or retrieval behavior.
> callout note > Start with the SDK when one model and a few tools are enough. Add a framework when the repeated infrastructure is greater than the abstraction cost.
Exercise
What must your program do after receiving a tool call?
Show answer
Validate the arguments, run the permitted function, append the tool result, and call the model again.