LangChain Tool Wrong Argument Value with Ollama: Fixes
A LangChain tool wrong argument value with Ollama, like 'username=bob' instead of 'bob', is almost always the small model's weak tool-call output plus a loose schema, not a LangChain bug. Inspect tool_calls, tighten the schema, validate.
- LangChain forwards whatever JSON the model emits as tool_calls, so print ai_msg.tool_calls first to see who is at fault.
- Replace bare str arguments with a Pydantic args_schema, Field descriptions with examples, and a validator that rejects bad input with a clear error.
- Give the model a create_users(usernames: list[str]) batch tool so a list is valid input instead of a stringified array.
- Set temperature=0, raise num_ctx to 8192, keep few tools and pin the model tag.
- When the action is deterministic, extract with structured output and call the Python function yourself.
Why does a LangChain tool get a wrong argument value with Ollama?
Mostly the model. LangChain takes the tool_calls the model returns, validates them against the tool schema, and passes the args to your function. It does not rewrite a value like 'bob' into 'username=bob'.
An 8B model such as llama3.1:8b is the main source of malformed arguments, because it imitates the surrounding text of the prompt or the parameter name. The tool definition and prompt are the second cause: a bare `username: str` with no description gives the model nothing to anchor on.
Your setup is the third suspect. Ollama's default context window (2048 or 4096 tokens depending on version) can truncate tool definitions in a long prompt, and old text-based ReAct agents pass 'Action Input' as a raw string, which is where prefixes like `username=bob` often come from.
How do I see what the model actually sent?
Bind the tool and print the raw tool calls. If the bad value is already here, LangChain is innocent and the fix belongs in the model, schema or prompt.
from langchain_ollama import ChatOllama
from langchain_core.tools import tool
@tool
def create_user(username: str) -> str:
"""Create a user account."""
return f"created {username}"
llm = ChatOllama(model="llama3.1:8b", temperature=0)
llm_t = llm.bind_tools([create_user])
ai_msg = llm_t.invoke("Create accounts for bob and alice")
for tc in ai_msg.tool_calls:
print(tc["name"], tc["args"], tc["id"])
print(ai_msg.invalid_tool_calls) # unparseable JSON ends up here
# Optional: trace every step
from langchain_core.globals import set_debug
set_debug(True)Before and after: the same create_user tool
The before version is a bare string with no description. The after version has a typed schema, a described field with an example, a validator that normalises harmless noise and rejects the rest, and a batch tool.
The before-validator must also cope with JSON that is not a list. `json.loads('5')` returns an int and `json.loads('"bob"')` returns a str. If these reach the second validator unchanged, iterating over them raises `TypeError`, which Pydantic does not convert into a `ValidationError`. `handle_validation_error=True` therefore does not catch it and the tool call crashes.
The corrected code wraps any non-list result as `[v]`. The `check` validator then raises `ValueError` for non-string items. Pydantic turns `ValueError` into a `ValidationError`, so the model receives a readable error and can retry.
Use the modern `langchain_ollama.ChatOllama` with bind_tools or a tool-calling agent (`create_react_agent` from langgraph.prebuilt, or `create_agent` in recent LangChain). Avoid the legacy string-based ReAct agent.
import json, re
from typing import List
from pydantic import BaseModel, Field, field_validator
from langchain_core.tools import StructuredTool
USER_RE = re.compile(r"^[a-z0-9_]{3,32}$")
def clean(v: str) -> str:
v = v.strip().strip("'\"")
v = re.sub(r"^username\s*=\s*", "", v, flags=re.I)
v = v.strip("'\"").lower()
if not USER_RE.match(v):
raise ValueError(
f"Invalid username {v!r}. Use 3-32 chars of a-z, 0-9, _ only, "
"e.g. 'bob'. Call again with a corrected value.")
return v
class CreateUsersInput(BaseModel):
usernames: List[str] = Field(
description="Usernames to create. Each is username only, lowercase, "
"no spaces, no prefix like 'username='. Example: ['bob','alice']")
@field_validator("usernames", mode="before")
@classmethod
def parse_list(cls, v):
if isinstance(v, str): # stringified array or single name
try:
v = json.loads(v) # may return int, str, dict, list...
except json.JSONDecodeError:
pass # plain text such as 'bob': keep as is
if not isinstance(v, list): # '5' -> 5, '"bob"' -> 'bob', 'bob'
v = [v] # wrap so check() always iterates a list
return v
@field_validator("usernames")
@classmethod
def check(cls, v):
for x in v:
if not isinstance(x, str):
raise ValueError(
f"Each username must be a string, got {x!r}. "
"Example: ['bob','alice']")
return [clean(x) for x in v]
def create_users(usernames: List[str]) -> str:
"""Create one or more user accounts in a single call. Pass ALL requested
usernames together in the list. Do not call this tool repeatedly."""
return "created: " + ", ".join(usernames) # make this idempotent
create_users_tool = StructuredTool.from_function(
func=create_users, name="create_users",
args_schema=CreateUsersInput, handle_validation_error=True)Which fix addresses which symptom?
Match the symptom you see in tool_calls to the cheapest effective fix.
| Symptom | Likely cause | Fix |
|---|---|---|
| Value is 'username=bob' | Model echoes the parameter name; legacy ReAct string input; bare str schema | Field description with example, validator, tool-calling agent instead of ReAct |
| Value is '["bob","alice"]' as one string | Schema only allows str, model wants to batch | Use List[str] batch tool plus a before-validator that parses JSON |
| Tool crashes with TypeError on input like '5' | Before-validator returned a non-list and the check validator iterated over it | Wrap non-lists as [v] and raise ValueError for non-string items |
| Only one of several users created | Model emitted one call, or parallel calls handled inconsistently | Batch tool, or a description saying 'call once per user' and a loop on the agent side |
| Tool never called, or wrong tool | Too many tools, truncated context, no tool support in model | Fewer tools, num_ctx=8192, pick a model with the tools tag |
| Different args every run | Sampling randomness | temperature=0, pinned tag, short system prompt, few-shot example |
| invalid_tool_calls populated | Model emitted broken JSON | Stronger model or structured output route |
How do I make LangChain tool calling more reliable with a small model?
Work through these in order; each is cheap.
Reduce randomness first, then shrink what the model has to get right, then make failure recoverable.
- Set `temperature=0` and pin the exact tag (`llama3.1:8b`, not `llama3.1`) so a silent model update does not change behaviour.
- Raise the context: `ChatOllama(model=..., temperature=0, num_ctx=8192)`. Truncated tool definitions are a classic cause of invented arguments.
- Expose as few tools as possible. Small models degrade as the tool count grows; 3 to 5 is a sensible ceiling.
- Keep the system prompt short and explicit, and add one or two few-shot examples, e.g. a human message 'add bob and alice' followed by an AI tool call `create_users(usernames=['bob','alice'])` and its ToolMessage.
- Make the validator return a clear error string and let the agent feed it back as a ToolMessage so the model self-corrects.
- Cap retries (2 or 3). In langgraph set a recursion_limit, or in a manual loop use a counter, so a stubborn model cannot loop forever.
When should I take the LLM out of the loop?
If the action is always 'create these users', the model does not need to choose a tool. Use it only to extract the names, then call plain Python. Extraction with a schema is far more deterministic than tool selection.
`with_structured_output` on ChatOllama uses the schema to constrain output (via Ollama's format parameter in recent versions), so the result is a validated object. The snippet below is self-contained: it has its own imports and repeats the `clean` helper from the earlier example.
import re
from typing import List
from pydantic import BaseModel
from langchain_ollama import ChatOllama
USER_RE = re.compile(r"^[a-z0-9_]{3,32}$")
def clean(v: str) -> str:
# same helper as in the before/after example
v = v.strip().strip("'\"")
v = re.sub(r"^username\s*=\s*", "", v, flags=re.I)
v = v.strip("'\"").lower()
if not USER_RE.match(v):
raise ValueError(f"Invalid username {v!r}")
return v
class Users(BaseModel):
usernames: List[str]
extractor = ChatOllama(model="llama3.1:8b", temperature=0, num_ctx=8192)\
.with_structured_output(Users)
req = extractor.invoke("Please set up accounts for Bob and Alice")
names = [clean(n) for n in req.usernames] # raises ValueError on bad input
print(names) # ['bob', 'alice']
# then: create_users(names) in ordinary code, after confirmationWhich model should I use instead of llama3.1:8b?
llama3.1:8b handles a single, simple call acceptably but is weaker at multi-call and strict formatting. Pick a model that the Ollama library lists with the 'tools' tag, since models without native tool support will not return tool_calls at all.
Rule of thumb: if you cannot constrain the task (open-ended agent, many tools), use a bigger or hosted model. If you can (fixed action, known fields), use structured extraction plus plain Python and keep the small model.
| Model | Tool-calling fit | Notes |
|---|---|---|
| llama3.1:8b | Single simple calls | Prefixes, stringified lists and skipped calls are common |
| qwen2.5 / qwen3 (7B to 14B) | Generally better schema adherence at similar size | Check the tools tag and your Ollama version |
| mistral-nemo | Reasonable for few tools | Keep prompts short |
| llama3.1:70b | Much more consistent | Needs substantial VRAM or RAM |
| Hosted model | Most reliable for multi-step agents | Cost and data-privacy trade-off |
Common questions
Why does my tool receive a string like '["bob","alice"]' instead of two calls?
The schema says str, so the model packs both names into one valid string. Declare usernames as List[str] so a real list is valid, and add a before-validator that parses a JSON string for the cases where it still stringifies.
Does langchain_ollama fix the problem compared with the old Ollama class?
It helps, because ChatOllama uses Ollama's native tool-calling API and returns structured tool_calls rather than parsing text. It cannot fix a model that emits wrong values, so you still need schema and validation.
Should the validator silently fix bad arguments?
Only for harmless, well-defined noise such as quotes or a literal 'username=' prefix. For anything ambiguous, raise an error with a clear message so the model retries, since guessing can create wrong accounts.
Why does the model ignore my tool descriptions?
Often the context was truncated by a small num_ctx, or there are too many tools competing for attention. Raise num_ctx to 8192, shorten descriptions to one clear sentence plus an example, and remove unused tools.
Can I force the model to call a specific tool?
Yes, bind_tools accepts a tool_choice argument for providers that support it, but support varies in ChatOllama and by version, so test it. A more dependable option for a fixed action is structured extraction followed by a plain Python call.