On this page · 14 sections

Here is a line of code that appears in a great many LLM applications:

llm = ChatOllama(model="qwen2.5:3b", temperature=0, seed=42, num_ctx=8192)

It reads like a complete description of the model call. Temperature 0, fixed seed, an 8k context. Add .with_structured_output(DeliveryException) and you have typed objects coming out of a model. Add .bind_tools([...]) and you have tool calling. Swap ChatOllama for another provider’s class and, in principle, the rest of the code doesn’t change.

That is what LangChain gives you: one interface over many models, with structured output, tools, streaming, and callbacks built in. The question this article asks is the one every abstraction raises: what does it do underneath, and which of those things would you want to know about?

To answer it, the demo puts a small logging proxy between LangChain and Ollama and records every byte of every request and response. Then it makes the same calls by hand, with a plain HTTP client, and compares the two. One example runs throughout: a fleet-operations assistant that answers questions about delayed packages and turns delivery-exception messages into typed records.

The short version: most of what LangChain sends is exactly what you’d send yourself. But a few things you’d reasonably expect to work are silently dropped or ignored, one structured-output method returns None instead of raising an error, there is no timeout, and the call that looks synchronous streams on the wire.

Try to Understand It This Way

Think of a travel agent. You say “a flight to Delhi on Friday, aisle seat, vegetarian meal”. The agent turns that into the airline’s booking form, which you never see. Most of the time the form says exactly what you asked. The agent also handles things you didn’t think about: rebooking, paperwork, the right format for each airline.

But suppose the airline’s form has no field for the meal. A good agent tells you. A busy one just leaves it off, and you find out on the plane. And if you later say “and make it a window seat”, does the agent change one field or start a new form with only the window seat on it?

LangChain is the agent. Ollama’s /api/chat is the airline’s form. Each ChatOllama setting has to become a field on that form, and when there’s no field for it, or a later instruction replaces an earlier one, the only way to know is to look at the form. That’s what the proxy is for.

The Setup

The demo, 05-langchain-what-it-hides, uses the current packages, pinned:

  • langchain-core 1.7.4: the base abstractions: messages, runnables, output parsers, callbacks.
  • langchain-ollama 1.1.0: the Ollama integration, ChatOllama. It needs langchain-core and the official ollama Python client (0.6.3), but not langchain itself.
  • langchain 1.4.8: the agent layer, which depends on LangGraph 1.2.19. The documentation says “LangChain’s agents are built on top of LangGraph.”

The proxy forwards each request unchanged to Ollama 0.40.16 and records the request body and every line of the streamed response. For the failure cases, a stub that answers like Ollama replaces it, so each failure can be produced on demand.

Versions and setup
  • Python: 3.12.13, on an Apple M4 Pro.
  • Packages: langchain 1.4.8, langchain-core 1.7.4, langchain-ollama 1.1.0, ollama 0.6.3, langgraph 1.2.19, langsmith 0.14.17, httpx 0.28.1, pydantic 2.14.2. Every package in the lock was released on or before 2026-11-02.
  • Ollama: 0.40.16, with qwen2.5:3b, llama3.2:3b, and llama3.2:1b.
  • The hand-written baseline: one httpx POST to /api/chat with a body written out in the script.
  • Model requests: temperature 0, seed 42, num_ctx 8192, except where a case is about the defaults.

What a Call Sends

For a plain invoke(), LangChain’s request differs from the hand-written one in three fields: "stream": true, "options": {}, and "tools": []. Settings you didn’t set aren’t sent at all: no keep_alive, no num_ctx, no temperature. That’s a sensible design, because Ollama applies its own defaults, but it means LangChain’s documentation isn’t describing what you get. ChatOllama’s docstring describes the context window as “(Default: 2048)”, while the server in “Ollama for Development: Running Local Models Reproducibly (opens in a new tab)” allocated 4,096 on the same kind of machine, and more on machines with more GPU memory.

With temperature=0, seed=42, num_ctx=8192 on the constructor, all three arrive in options, as expected. So far, no surprises. Now the ones that are.

invoke() streams

Every LangChain call to Ollama is a streamed request, including invoke(), which collects the chunks and returns one message. The source says so directly: "stream": kwargs.pop("stream", True). For most applications that’s invisible. It matters when something between your code and the model behaves differently for streamed responses: a proxy that buffers, a timeout that measures something else, or, as below, error handling.

A call-time options replaces the constructor’s

Suppose the constructor sets temperature, seed, and context, and one call needs a shorter reply:

llm = ChatOllama(model="qwen2.5:3b", temperature=0, seed=42, num_ctx=8192)
llm.invoke(messages, options={"num_predict": 64})

On the wire, options was {"num_predict": 64}. Temperature, seed, and context were gone, so that call ran at Ollama’s default temperature, with no seed, in the default context. Nothing warned. The code is explicit about it: if a call passes options, the dictionary built from the constructor’s fields isn’t used at all.

Arguments that do nothing

ChatOllama(model=..., max_tokens=64, timeout=5, max_retries=2) is accepted without a warning, and none of the three has any effect. ChatOllama has no field with those names, and LangChain’s model classes ignore arguments they don’t know. They are real settings on other LangChain chat models, which is exactly why someone switching providers would expect them to work. (The Ollama names are num_predict for the reply length, and client_kwargs={"timeout": ...} for a timeout.)

Passing temperature=0 to invoke() instead fails before any request, with TypeError: Client.chat() got an unexpected keyword argument 'temperature'. At least that one is loud.

Tools lose part of their schema

With bind_tools() and two functions, the tool definitions on the wire matched the hand-written ones except for one thing: a parameter’s default was missing. With with_structured_output(method="function_calling"), the delay_hours field, typed int | None, arrived with its description and nothing else: its type was gone.

This isn’t LangChain’s choice. LangChain generated the full schema. The ollama Python client that langchain-ollama uses validates each tool into a model whose properties have only four fields, type, items, description, and enum, so anything else, including anyOf, default, and minimum, never reaches the server. The layer below the abstraction made the decision, which is a good reason to look at the wire rather than at either library’s code alone.

tool_choice isn’t sent either, and here the docstring is honest: “This parameter is currently ignored as it is not supported by Ollama.”

When a tool result goes back to the model, the tool call’s ID and the ToolMessage’s tool_call_id aren’t sent. Neither is tool_name, the field Ollama’s API documents for saying which tool a result came from. Ollama 0.40.16 returns an ID with each tool call (call_ngttwpv8 in one run); LangChain replaces it with a UUID of its own, and the ollama client has no field to send IDs back. With one tool call per turn, the model can still match the result to the call by position. With several in one turn, it has only the order to go on.

Structured Output, Measured

with_structured_output() has three methods for ChatOllama, and the default is json_schema (the source changed it to that in version 0.3.0):

  • json_schema: the Pydantic model’s JSON schema goes in Ollama’s format field, which constrains the model’s output to it, as in “Structured Outputs: Making LLMs Produce Reliable Data (opens in a new tab)”.
  • json_mode: "format": "json". Output is valid JSON, but the schema is only in whatever prompt you write.
  • function_calling: a tool named after the model; the model is expected to call it.

The demo extracts fifteen delivery-exception messages into a DeliveryException record (package_id, city, reason from seven values, and delay_hours as an optional integer). Some messages are deliberately awkward: “two days” or “half a day” instead of hours, a second package ID as a distractor, a city that isn’t the first one named. Each method runs on three small models, and each field is graded against the expected value.

Fields correct, out of 60 (15 messages × 4 fields), with the hand-written request that sends the same schema in format for comparison:

Model json_schema (default) function_calling json_mode hand-written, schema in format
qwen2.5:3b 57 57 57 57
llama3.2:3b 56 57 53 (1 parse error) 56
llama3.2:1b 47 20 42 (3 parse errors) 47

For the two 3B models, the method barely mattered: every reply parsed, and the misses were extraction mistakes, such as a distractor package ID. LangChain’s default and the hand-written request gave identical results, as they should: the wire showed the same request.

The 1B model is where the methods separate, and function_calling is where it went wrong:

  • 6 of 15 returned None, with no error. The model wrote the tool’s definition, or a call to it, as ordinary text in its reply, instead of making a tool call. There was no tool call to parse, so the parser returned None.
  • 3 raised ValidationError. Two calls left out the required package_id; one sent 1.5 for an integer field.
  • 6 parsed, for 20 correct fields in all.

With json_schema, the same model’s replies all parsed, because the server constrained them to the schema. Eight of its 13 missed fields were delay_hours: left empty seven times, even for messages that said “5 hours” or “12h”, and 2 instead of 48 for “two days”. The field is optional in the schema, so an empty value is valid: a schema can make a reply well-formed, not complete.

When the reply is wrong

The stub can produce exactly the wrong reply each test needs. What each method does with it:

The model’s reply json_schema / json_mode function_calling
Prose instead of the structure raises OutputParserException returns None, no error
A value outside the enum, or a missing field raises OutputParserException raises pydantic.ValidationError (if it came as a tool call)
Valid JSON inside a Markdown code fence parsed: the fence is stripped returns None
A call to a tool that doesn’t exist raises OutputParserException

The None is the dangerous one. If the model answers in text instead of calling the tool, function_calling returns None, and code that does result.package_id fails later, somewhere else, with an error about NoneType. The behaviour comes from langchain-core’s tool-call parser, which returns None when it finds no tool call. In every case, the stub received exactly one request: there’s no automatic retry for a reply that doesn’t parse. With include_raw=True, nothing is raised; you get the raw message, parsed (possibly None), and parsing_error to check yourself.

Errors, Timeouts, and Retries

The stub also produced infrastructure failures. Here’s what a default ChatOllama did:

  • No timeout. The ollama client is created with timeout=None. A reply that took 7 seconds was waited for in full; plain httpx, by contrast, gave up at its 5-second default. A hung server means a hung call, unless you pass client_kwargs={"timeout": ...}.
  • No retries. One request per call, and max_retries is ignored, as above.
  • .with_retry() retries everything. It made 3 attempts with exponential backoff and jitter, 3 to 5 seconds in all, and by default it retries on every exception: including a 404 for a model that doesn’t exist, and a malformed response body that will be malformed the next time too. Its retry_if_exception_type parameter narrows that, and it’s worth setting.
  • Exceptions from three libraries. A refused connection raised httpx.ConnectError (the ollama client converts it to its own ConnectionError only for requests that aren’t streamed, and LangChain always streams). An HTTP error, or an error line inside the stream, raised ollama.ResponseError. A malformed body raised json.JSONDecodeError. Error handling that catches one of these misses the others.

None of this is wrong, exactly. But “LangChain handles retries” and “LangChain handles errors” are both things people assume, and for ChatOllama, by default, neither is true.

Streaming and Token Counts

.stream() yielded one chunk per line on the wire, plus a final empty chunk that langchain-core adds. The joined text was identical to what came over the wire. Ollama’s prompt_eval_count and eval_count become usage_metadata (input_tokens, output_tokens, total_tokens), on the chunk built from Ollama’s final line, which isn’t the last chunk, so add the chunks together to get the totals. One field doesn’t survive: Ollama 0.40.16 also reports prompt_eval_cached_count, the prompt tokens it reused from cache, and the ollama client doesn’t know that field, so LangChain never sees it.

What It Costs

With the model taken out, against the stub that answers instantly, here is the median time per call over 500 calls:

Call Median per call
plain httpx POST 0.29 ms
the ollama Python client 0.31 ms
LangChain invoke() 0.57 ms
LangChain .stream() 0.52 ms
hand-written structured request, parsed with Pydantic 0.30 ms
LangChain with_structured_output() 0.95 ms

LangChain adds about a quarter of a millisecond per call, and about two-thirds of a millisecond with structured output. The model calls in “Ollama for Development: Running Local Models Reproducibly (opens in a new tab)” took one to two seconds each, so per call, the abstraction costs well under a tenth of a percent: negligible.

The cost is elsewhere. Importing langchain_ollama took about 320 ms, against 38 ms for httpx and 103 ms for the ollama client; the largest single part was langsmith, about 100 ms, imported even with tracing off. That matters for a command-line tool or a serverless function that starts often, not for a long-running server. And the installed footprint grows: httpx alone is 7 packages and 3.9 MB, the ollama client 12 packages and 13.1 MB, langchain-ollama 35 packages and 38.9 MB, and langchain itself 39 packages and 45.3 MB. More packages means more to pin, audit, and upgrade.

How the overhead was measured
  • Stub: a local server that answers /api/chat like Ollama with a fixed reply, instantly, streamed when the request asks for streaming. It removes the model, so what’s left is the client libraries and loopback HTTP.
  • Timing: 50 warm-up calls, then 500 calls per variant, time.perf_counter, median reported. Two runs agreed within 3%.
  • Imports: each import timed in a fresh Python process, 10 times, median reported; the per-package breakdown is from python -X importtime.
  • Footprint: the packages each install pulls in, and the size of the files they list, on Python 3.12.13.
  • Machine: Apple M4 Pro, on mains power, with no model loaded.

What leaves the machine

LangSmith, LangChain’s tracing service, is a required dependency of langchain-core, but tracing is off unless LANGSMITH_TRACING (or one of its older names) is set to "true". The demo checked this at the socket level: importing langchain, langchain_core, langchain_ollama, and langgraph opened no connection, and the calls opened one, to the local server. With tracing turned on and pointed at a local recorder instead of the real service, a single call uploaded the system prompt, the question, and the model’s reply. That’s the point of tracing, and it’s also what to know before you set the variable in an environment that handles customer data.

What Breaks

  • Per-call options. Replaces every sampling setting from the constructor.
  • Provider-portable arguments. max_tokens, timeout, and max_retries are silently ignored by ChatOllama.
  • Tool schemas. Defaults, anyOf types, and constraints are dropped before the request leaves the client.
  • function_calling structured output. Returns None when the model answers in text.
  • No timeout. A slow or hung server holds the call indefinitely.
  • .with_retry() defaults. Retries errors that can’t succeed.
  • Exception types. Three libraries, three families of exceptions.

Engineering Decisions

1. Look at the wire once, for every new integration

A logging proxy is about a hundred lines of standard-library Python, and it answers questions that documentation can’t: what was sent, what was dropped, what came back. The demo’s wire.py is one. Run your real calls through it once, and again after upgrades.

2. Pin the behaviours you depend on in tests

The demo’s tests run against the stub and fail if a release changes what’s on the wire: that options replaces, that tool_choice isn’t sent, that function_calling returns None. If your application depends on a library’s behaviour, a test is the place to say so.

3. Pass settings on the constructor, or pass all of them per call

If one call needs different options, pass the complete set. Better, create a second model object with its own settings.

4. Prefer json_schema, and check for None

With Ollama, json_schema sends your schema as an output constraint, raises a clear error when the reply doesn’t parse, and is the default. If you use function_calling, check the result for None every time, or use include_raw=True and check parsing_error.

5. Set a timeout, and choose what to retry

client_kwargs={"timeout": ...} on the model, and .with_retry(retry_if_exception_type=(...)) with only the exceptions a retry can fix.

When to Use LangChain (and When Not To)

LangChain earns its place when you use what it’s built for: many providers behind one interface, LangGraph agents (its agent layer is built on LangGraph), and a large set of integrations for retrievers, loaders, and tools. If an application really does switch between providers, or uses several, the common interface saves real work, and the streaming, token counts, and callbacks are consistent across them.

For one provider and a few calls, the measurements point the other way. The hand-written call in this demo is a single HTTP request whose every field you can see. LangChain’s version sent almost the same request, but with settings dropped in ways only the wire revealed, and with error behaviour you’d need to learn anyway. If you use it, I’d treat it like any dependency that sits between you and a production system: read what it sends, pin its version, and test the behaviours you rely on.

What to Take Away

  • Most of what LangChain sends is what you’d send. The differences are few, and some of them matter.
  • Per-call options replace, not merge, and unknown constructor arguments are ignored without a word.
  • The ollama client strips tool schemas down to type, items, description, and enum.
  • function_calling returns None when the model doesn’t call the tool; json_schema raises.
  • No timeout and no retries by default, and .with_retry() retries everything.
  • Look at the wire. A small logging proxy found what the documentation didn’t say.

Think About These Use Cases

  • Switching providers: Your code uses ChatOpenAI(max_retries=3, timeout=30) and you move to a local model with ChatOllama. Which of your reliability assumptions still hold, and how would you find out before production?

  • A tool with a default: One of your tools has a parameter limit: int = 10. After the schema reaches the model without its default, what will the model send, and does your tool handle it?

  • Parallel tool calls: The model calls get_package_status for three packages in one turn. With no IDs on the tool results, how would you make sure each result is matched to the right call?

  • An upgrade: A new langchain-ollama release changes the default structured-output method. Which of your tests would catch it, and which wouldn’t?

  • Tracing in production: You want LangSmith traces for debugging, but requests contain customer addresses. What would you change before setting the environment variable?

If you want to talk one of these through, take it to GPT along with this article. Ask GPT ↗️

What’s Next?

This article ends the first set of AI Tooling articles: OpenUI, LangGraph, Langfuse, MCP, Ollama, and LangChain, each measured with the same small fleet assistant. The pattern across them is the same one: read what the tool actually does, measure it with your own data, and pin the behaviours you depend on.

← All articles