Validate LLM Function Calls at Runtime for Robust AI Agents
Implement dynamic runtime schema validation for LLM-generated function calls to build more robust and reliable AI agents.
AI agents use tools to interact with the world. These tools are often functions with specific input requirements. Large Language Models (LLMs) generate the calls to these functions, including the function name and its arguments. But LLMs are not perfect. They can generate malformed or invalid function calls. This breaks your agent and leads to unpredictable behavior. You need to validate these calls at runtime.
The Problem with Unvalidated LLM Tool Calls
When an LLM generates a tool call, it provides a function name and a set of arguments. For example, an agent might call a create_task tool with {'title': 'Buy groceries', 'due_date': 'tomorrow'}. The tool expects title to be a string and due_date to be a valid date string or null.
However, an LLM might generate something like {'title': 123, 'priority': 'high'}. Here, title is an integer, which the create_task tool might not accept. The priority argument might not exist in the tool's definition. If you execute this call directly, your application will likely crash or behave unexpectedly. This makes agents unreliable and difficult to trust in production.
Why Static Schemas Are Not Enough
Developers define tool schemas. These schemas tell the LLM what functions are available and what arguments they expect. You might use OpenAPI specifications or JSON Schema definitions for this. This is crucial input for the LLM. It helps the LLM understand how to use your tools.
But defining the schema for the LLM is only half the battle. The LLM's output – the actual function call it generates – still needs to conform to that schema. The LLM might misinterpret the schema, hallucinate arguments, or use incorrect data types. It might omit required fields or include unknown ones.
Static analysis at development time cannot catch these runtime generation errors. You need a check after the LLM has produced its output, but before the tool is executed.
Implementing Dynamic Runtime Validation
The solution is to validate the LLM's generated function call against the tool's defined schema at runtime. This happens after the LLM responds but before your application attempts to execute the tool.
This process typically involves these steps:
- Define a robust schema: Use a standard like JSON Schema for each of your tools. This schema should specify argument names, types, required fields, and any other constraints.
- Extract the LLM's call: Parse the LLM's response to get the tool name and its arguments.
- Validate: Use a schema validation library to compare the extracted arguments against the tool's defined schema.
- Handle validation failures: If validation passes, execute the tool. If it fails, do not execute the tool. Log the error and decide on a recovery strategy.
Practical Example: A Simple Tool and Validation
Consider a search_documents tool. It takes a query (string, required) and an optional filters object (key-value pairs of strings).
Here is its JSON Schema definition:
{
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
},
"filters": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "Optional filters for the search results"
}
},
"required": ["query"]
}
Now, imagine the LLM generates a call like this:
{
"tool_name": "search_documents",
"args": {
"query": 123,
"filters": {
"category": "reports",
"date_range": 2023
}
}
}
This call is invalid. The query is an integer, not a string. The date_range filter is an integer, not a string. A runtime validator will catch these issues.
Here's how you might validate this in Python using the jsonschema library:
import jsonschema
tool_schemas = {
"search_documents": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The search query"},
"filters": {
"type": "object",
"additionalProperties": {"type": "string"},
"description": "Optional filters"
}
},
"required": ["query"]
}
}
llm_generated_call = {
"tool_name": "search_documents",
"args": {
"query": 123, # Invalid type
"filters": {
"category": "reports",
"date_range": 2023 # Invalid type
}
}
}
def validate_tool_call(call):
tool_name = call.get("tool_name")
args = call.get("args")
if not tool_name or tool_name not in tool_schemas:
print(f"Error: Unknown tool name '{tool_name}'")
return False
schema = tool_schemas[tool_name]
try:
jsonschema.validate(instance=args, schema=schema)
print(f"Validation successful for tool '{tool_name}'")
return True
except jsonschema.exceptions.ValidationError as e:
print(f"Validation failed for tool '{tool_name}': {e.message}")
return False
## Run validation
validation_result = validate_tool_call(llm_generated_call)
## Output: Validation failed for tool 'search_documents': 123 is not of type 'string'
This code snippet clearly shows how the jsonschema.validate function catches the type mismatch for query. A more comprehensive error handling would also catch the date_range filter issue.
What to Do When Validation Fails
When a tool call fails validation, you have several options:
- Reject and log: The simplest approach is to stop the current agent turn, log the validation error, and inform the user. This prevents incorrect actions but might halt the agent's progress.
- Retry with feedback: A more sophisticated approach is to provide the LLM with specific feedback about the validation error. You can include the error message in the next prompt, instructing the LLM to correct its call. This allows the agent to self-correct and recover from errors. For example, "The
queryargument forsearch_documentsmust be a string. You provided a number. Please try again with a valid string query." - Default or fallback: For optional arguments, if validation fails due to a missing field, you might be able to inject a default value. If an argument has an invalid value but a sensible default exists, you could substitute it. Be cautious with this approach; it can mask actual LLM errors if overused.
For most production agents, a combination of logging errors and attempting to retry with feedback is the most robust strategy. This improves the agent's resilience and reduces the need for human intervention.
Benefits of Runtime Schema Validation
Integrating dynamic runtime schema validation into your AI agent tooling provides significant benefits:
- Increased robustness: Prevents agent crashes and unexpected behavior caused by malformed tool calls.
- Improved reliability: Agents become more predictable and trustworthy, even when LLMs make mistakes.
- Easier debugging: Errors are caught early in the execution pipeline with clear, actionable messages, simplifying troubleshooting.
- Better user experience: Users encounter fewer frustrating errors and more consistent agent performance.
- Enhanced security: Prevents injection of unexpected data types or structures into your backend systems via tool calls.
By adding this layer of defense, you move closer to building production-ready AI agents that can handle the inherent unpredictability of LLM outputs.
Where to go from here
Integrate schema validation into your tool execution pipeline. Define clear JSON schemas for all your agent's tools. For more on structuring your agent's capabilities, review our guide on /blog/designing-effective-tool-schemas-ai-agents.