Sub topic 11
Seeing what the model was actually sent
This chapter assumes you can call a chat completion API from Python, read JSON, and install packages in a virtual environment. It also assumes you have read the earlier chapters on structured output, tool calling, and what frameworks add.
When a framework call returns a bad answer, the first question is always the same: what text did the model actually receive? A framework builds prompts from templates, memory, retrieved chunks, tool schemas, and output instructions. The final request can look very different from the one line you wrote. This chapter covers how to inspect it, using the same techniques with a bare SDK and with each framework.
Why the final request matters
A language model sees only the request payload. It does not see your Python objects, your chain definition, or your intentions. Every failure you can debug comes down to one of these:
- The messages were not what you expected (a missing system prompt, duplicated history, or a retrieved chunk that is irrelevant).
- The tool schema or output schema was changed on the way out (for example, a docstring became a description, or a field was renamed).
- The request was right but the model's reply was misread (a parsing or validation step failed).
- The request was sent more than once (a hidden retry, or an agent loop that ran extra steps).
With a bare SDK, the payload is the dictionary you built, so you can print it. With a framework, a layer sits between your code and the payload. Your goal is to look at the request at the lowest layer you control, below the abstraction.
The lower the layer, the closer you get to the truth. Framework traces show the framework's own view. HTTP logging shows exactly what left your machine.
Level 1: log the payload in a bare SDK
With a direct SDK call, build the arguments once, log them, then send them.
import json
from openai import OpenAI
client = OpenAI()
request = {
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API client library is in one sentence."},
],
}
print(json.dumps(request, indent=2))
response = client.chat.completions.create(**request)
print(response.choices[0].message.content)
print(response.usage)Two details help here. Building the request as a dictionary makes it easy to log, save to a file, and replay later. The usage field on the response reports prompt and completion token counts, which shows how large the request really was. A prompt that is far bigger than you expect often means history or retrieved text is being added somewhere.
Level 2: turn on SDK and HTTP logging
The OpenAI Python SDK uses the httpx library and reads an OPENAI_LOG environment variable. Setting it to debug makes the SDK log request details, including the body. Keep this to local development, because the logs can contain user data.
import logging
import os
os.environ["OPENAI_LOG"] = "debug" # set before the client is created
logging.basicConfig(level=logging.DEBUG)
from openai import OpenAI
client = OpenAI()
client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say hello."}],
)The httpx and httpcore loggers also emit lines at DEBUG level. Frameworks built on the OpenAI SDK, including LangChain's ChatOpenAI and PydanticAI's OpenAI models, use that same client. The same logging therefore shows the real request even when you call through a framework. This is the most framework-independent technique in the chapter.
Authorization headers are redacted by the SDK's logging. Treat the rest of the output as sensitive anyway.
Level 3: use the framework's own tools
Each framework offers a view of its internal steps. These views show more than the HTTP body does, such as which component produced which text.
LangChain
LangChain has a global debug flag and a callback system. The debug flag prints each step of a chain, with inputs and outputs.
from langchain_core.globals import set_debug
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
set_debug(True)
prompt = ChatPromptTemplate.from_messages(
[
("system", "You answer in one sentence."),
("user", "Explain {topic}."),
]
)
chain = prompt | ChatOpenAI(model="gpt-4o-mini")
print(chain.invoke({"topic": "an API client library"}).content)The output includes the formatted prompt messages, which is the answer to "what was the model sent". To see the rendered prompt without calling the model at all, call the prompt on its own:
messages = prompt.invoke({"topic": "an API client library"}).to_messages()
for message in messages:
print(message.type, ":", message.content)This is a cheap, offline check, and it should be your first move when a template misbehaves. LangChain's hosted tracing product, LangSmith, records the same steps as a tree you can browse, and it can be switched on with environment variables.
LlamaIndex
In LlamaIndex, the most common debugging question is which chunks were retrieved and how they were placed in the prompt. A query response carries its source nodes, and a debug handler can print every LLM call.
import llama_index.core
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
llama_index.core.set_global_handler("simple")
documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)
response = index.as_query_engine().query("What does the guide say about access requests?")
for node in response.source_nodes:
print(round(node.score, 3), node.node.get_content()[:80])The simple handler prints the prompt and response of each LLM call. The source_nodes loop shows which chunks were selected and their similarity scores. If the scores are all low, the problem is retrieval, not generation. Fix chunking or embeddings before changing the prompt.
PydanticAI
PydanticAI returns the full message history of a run. This includes the system prompt, the user prompt, tool calls, tool returns, and any retries caused by failed validation.
from pydantic import BaseModel
from pydantic_ai import Agent
class CityInfo(BaseModel):
city: str
country: str
agent = Agent("openai:gpt-4o-mini", output_type=CityInfo)
result = agent.run_sync("Where were the 2012 Summer Olympics held?")
for message in result.all_messages():
print(message)PydanticAI also integrates with Pydantic Logfire, an observability service, through logfire.configure() and logfire.instrument_pydantic_ai(). Because it is built on OpenTelemetry, you can send the same traces to another compatible backend. Names in this area change between releases, so check the version you installed.
What to look for
Once you can see the request, check these items in order.
| Symptom | What to inspect | Typical cause |
|---|---|---|
| Answers ignore your instructions | System message position and content | Template variable not filled, or instructions overridden by later messages |
| Model never calls a tool | Tool schema in the request body | Missing description, or a schema field dropped during conversion |
| Output fails validation repeatedly | Message history for retry prompts | Schema instructions unclear to the model, or a field type that is too strict |
| Costs higher than expected | `usage` token counts and number of calls | Long history, large retrieved chunks, or repeated agent steps |
| Retrieved answer is off-topic | Source nodes and scores | Poor chunking or an embedding mismatch, not a prompt problem |
| Same call appears twice | Request log count | Client retry on timeout, or a framework retry wrapper |
Inspecting at the network level
When you suspect a framework is changing the request in a way its own logging does not show, route traffic through a local proxy and read the body there. Many SDKs accept a custom base URL, so you can point them at a proxy you run yourself, or at a gateway that records requests. In the OpenAI SDK this is the base_url argument or the OPENAI_BASE_URL environment variable.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8080/v1")This also works with frameworks that accept a base_url or that read the same environment variable. The proxy sees bytes on the wire, so neither the framework nor the SDK can hide anything from it. It is slower to set up than the earlier techniques, so use it as the last check.
Habits that make debugging easier
- Log the request and the response together under one request ID, so you can match them later.
- Save failing requests as JSON files. A saved payload can be replayed through a bare SDK call to find out whether the framework or the model caused the problem.
- Compare the framework call against an equivalent bare SDK call. If the bare call works and the framework call fails, diff the two payloads.
- Keep token counts in your logs. Surprises in cost and latency usually appear there first.
- Pin framework versions while debugging. A change in how a library builds prompts between releases can alter behavior without any change in your code.
Exercises
Exercise
A LangChain chain returns answers that ignore the system instruction. Name two ways to see the exact messages the model received, and say which is cheaper.
Show answer
You can render the prompt template alone with prompt.invoke(...).tomessages(), or turn on setdebug(True) or SDK debug logging (OPENAI_LOG=debug) and run the chain. Rendering the template alone is cheaper, because it makes no model call and costs no tokens.
Exercise
A LlamaIndex query gives an off-topic answer. The prompt looks fine. Which output do you check next, and what does a set of low scores tell you?
Show answer
Check response.source_nodes and the similarity score of each node. Uniformly low scores mean retrieval is the problem, so you should adjust chunking, the embedding model, or the number of results before editing the prompt.
Exercise
Why is HTTP-level logging considered the most reliable view of a request, even when you use a framework?
Show answer
Frameworks and SDKs both build the request before it is sent, so their own logs show their own view. HTTP-level logging or a proxy shows the bytes that actually left your machine, so no layer can hide changes from it.