The AI Function Calling System enables AI providers to call external functions and tools, allowing for more sophisticated interactions and real-world actions.
Overview
The function calling system provides:
- Function Registry: Central registry for callable functions
- Schema Validation: JSON schema validation for function parameters
- Function Execution: Safe execution of function calls with error handling
- Result Streaming: Streaming of function results back to AI
- Call Parsing: Automatic parsing of function calls from AI responses
- Middleware Integration: Seamless integration with AI provider middleware
Architecture
AI Response
↓
FunctionCallParser
↓
FunctionCallExecutor
↓
FunctionRegistry
↓
External Function
↓
FunctionResult
↓
Formatted Response
Components
FunctionRegistry
Central registry for managing callable functions:
from novacoder.ai.function_calling import FunctionRegistry, FunctionDefinition, FunctionParameter
registry = FunctionRegistry()
def add_numbers(x: int, y: int) -> int:
return x + y
func_def = FunctionDefinition(
name="add_numbers",
description="Add two numbers together",
parameters=[
FunctionParameter("x", "number", "First number"),
FunctionParameter("y", "number", "Second number")
],
handler=add_numbers
)
registry.register(func_def)
FunctionDefinition
Definition of a callable function:
@dataclass
class FunctionDefinition:
name: str
description: str
parameters: list[FunctionParameter]
handler: Callable[..., Any]
metadata: dict[str, Any]
FunctionParameter
Parameter definition for function schema:
@dataclass
class FunctionParameter:
name: str
type: str # "string", "number", "boolean", "object", "array"
description: str
required: bool = True
default: Any = None
enum: list[Any] | None = None
FunctionCallExecutor
Executor for function calls with validation:
from novacoder.ai.function_calling import FunctionCallExecutor
executor = FunctionCallExecutor(registry)
result = await executor.execute(function_call)
FunctionCallParser
Parser for extracting function calls from AI responses:
from novacoder.ai.function_calling import FunctionCallParser
parser = FunctionCallParser()
calls = parser.parse_function_calls(ai_response)
FunctionCallingMiddleware
Middleware for handling function calling in AI interactions:
from novacoder.ai.function_calling import FunctionCallingMiddleware
middleware = FunctionCallingMiddleware()
formatted_response, results = await middleware.process_response(ai_response)
Usage Examples
Basic Function Registration
from novacoder.ai.function_calling import FunctionCallingMiddleware, FunctionDefinition, FunctionParameter
middleware = FunctionCallingMiddleware()
def get_weather(location: str) -> str:
# Simulate weather API call
return f"The weather in {location} is sunny"
func_def = FunctionDefinition(
name="get_weather",
description="Get current weather for a location",
parameters=[
FunctionParameter("location", "string", "City name")
],
handler=get_weather
)
middleware.registry.register(func_def)
Processing AI Responses
import asyncio
async def process_with_function_calling():
middleware = FunctionCallingMiddleware()
# Register functions
middleware.registry.register(get_weather_func)
# AI response that includes function call
ai_response = 'I need to call get_weather(location="New York")'
# Process response
formatted_response, results = await middleware.process_response(ai_response)
print(f"Formatted response: {formatted_response}")
print(f"Results: {results}")
Function Schema Generation
# Get JSON schema for a function
schema = middleware.registry.get_schema("get_weather")
print(schema)
# {
# "name": "get_weather",
# "description": "Get current weather for a location",
# "parameters": {
# "type": "object",
# "properties": {
# "location": {
# "type": "string",
# "description": "City name"
# }
# },
# "required": ["location"]
# }
# }
# Get all function schemas
all_schemas = middleware.registry.get_all_schemas()
Function Execution
from novacoder.ai.function_calling import FunctionCall
async def execute_function():
call = FunctionCall(
name="get_weather",
arguments={"location": "Boston"}
)
result = await middleware.executor.execute(call)
if result.success:
print(f"Result: {result.result}")
print(f"Execution time: {result.execution_time}s")
else:
print(f"Error: {result.error}")
Function History
# Get call history for a function
history = middleware.registry.get_call_history("get_weather", limit=10)
# Get all call history
all_history = middleware.registry.get_call_history(limit=100)
Tools Schema for AI Providers
# Get tools schema for AI providers (OpenAI, Anthropic, etc.)
tools_schema = middleware.get_tools_schema()
print(tools_schema)
Function Types
Simple Functions
def simple_function(text: str) -> str:
return text.upper()
func_def = FunctionDefinition(
name="uppercase",
description="Convert text to uppercase",
parameters=[
FunctionParameter("text", "string", "Text to convert")
],
handler=simple_function
)
Async Functions
async def async_function(url: str) -> str:
import httpx
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.text
func_def = FunctionDefinition(
name="fetch_url",
description="Fetch content from URL",
parameters=[
FunctionParameter("url", "string", "URL to fetch")
],
handler=async_function
)
Functions with Enums
func_def = FunctionDefinition(
name="set_status",
description="Set status",
parameters=[
FunctionParameter(
"status",
"string",
"Status value",
enum=["active", "inactive", "pending"]
)
],
handler=set_status
)
Functions with Optional Parameters
func_def = FunctionDefinition(
name="search",
description="Search database",
parameters=[
FunctionParameter("query", "string", "Search query", required=True),
FunctionParameter("limit", "number", "Result limit", required=False, default=10)
],
handler=search_function
)
Error Handling
The function calling system includes comprehensive error handling:
# Function validation
errors = middleware.executor._validator.validate_call(function_call, function_def)
if errors:
print(f"Validation errors: {errors}")
# Execution errors
result = await middleware.executor.execute(function_call)
if not result.success:
print(f"Execution error: {result.error}")
Integration with AI Providers
OpenAI Function Calling
from novacoder.ai.providers.openai import OpenAIProvider
provider = OpenAIProvider()
middleware = FunctionCallingMiddleware()
# Register functions
middleware.registry.register(my_function)
# Get tools schema
tools = middleware.get_tools_schema()
# Use in OpenAI API call
response = await provider.chat(
messages,
tools=tools,
tool_choice="auto"
)
Anthropic Function Calling
from novacoder.ai.providers.anthropic import AnthropicProvider
provider = AnthropicProvider()
middleware = FunctionCallingMiddleware()
# Similar integration for Anthropic
tools = middleware.get_tools_schema()
response = await provider.chat(messages, tools=tools)
Best Practices
- Function Naming: Use clear, descriptive function names
- Parameter Validation: Always validate function parameters
- Error Handling: Handle errors gracefully in function handlers
- Documentation: Provide clear descriptions for functions and parameters
- Type Safety: Use proper type hints for function parameters
- Async Functions: Use async functions for I/O operations
- Security: Validate and sanitize all inputs to functions
- Testing: Test functions independently before registering
Security Considerations
- Input Validation: Always validate function inputs
- Sandboxing: Consider running functions in a sandboxed environment
- Permission Checks: Implement permission checks for sensitive operations
- Rate Limiting: Add rate limiting for expensive operations
- Logging: Log all function calls for audit purposes
Performance Considerations
- Async Execution: Use async functions for I/O-bound operations
- Caching: Cache results of expensive function calls
- Timeouts: Implement timeouts for long-running functions
- Resource Limits: Set resource limits for function execution
Configuration
Configure function calling behavior:
# Enable/disable function calling
middleware.enable()
middleware.disable()
# Check if enabled
if middleware.is_enabled():
# Process with function calling
pass
Related Documentation
- AI Runtime
- AI Streaming
- AI Context Window
- AI Error Handling