Language models are strong at reasoning, but without tools, they can only talk - not act. For financial applications requiring precise calculations, real-time data access, or system integrations, tool-augmented agents are essential. Combined with structured outputs using Pydantic, we can build reliable financial systems that guarantee data format compliance.
From Talking to Acting: Tool-Augmented Agents
Consider a financial advisor agent. Without tools, it might attempt a rough ROI estimate based on training data. With tools, it can call a precise calculation function and return exact figures. The difference is critical in finance where accuracy matters.
flowchart TB
subgraph WithTools["With Tools"]
direction LR
Q2[Calculate ROI?] --> T[Call: calculate_roi
inv=500000, profit=125000]
T --> E[Execute Python]
E --> R[25.00% exactly]
R --> A2[Professional analysis
with exact figures]
end
subgraph NoTools["Without Tools"]
direction LR
Q1[Calculate ROI?] --> G1[Guess from
training data]
G1 --> A1["~25% maybe?"]
end
classDef pinkClass fill:#E74C3C,stroke:#333,stroke-width:2px,color:#fff
classDef greenClass fill:#27AE60,stroke:#333,stroke-width:2px,color:#fff
class NoTools pinkClass
class WithTools greenClass
Common Tool Types for Finance
Tool Type
Use Case
Example
Math Functions
Precise calculations
ROI, compound interest, risk metrics
APIs & Webhooks
External integrations
Market data, CRM, trading systems
Databases
Data retrieval
Position history, customer records
Web Search
Real-time information
News, regulatory updates
Code Execution
Custom transformations
Data processing, report generation
Function Calling: The Foundation
Early approaches used prompt-based cues like “Calling calculator with X and Y” followed by parsing. This was fragile. Modern function calling provides a formal mechanism where:
Tools are defined with JSON schemas describing name, purpose, and parameters
Models are trained to recognize when tools should be used
Structured calls are returned with function name and arguments
Backend executes the function and returns results to the model
Building a Financial Tool Agent
Let’s build an agent that can perform ROI and tax calculations:
# System prompt for financial advisor persona SYSTEM = """You are a helpful corporate financial advisor. Provide clear, professional financial analysis and recommendations."""
# Tool 1: ROI Calculator defcalculate_roi(investment: float, profit: float, years: int) -> dict: """ Calculate Return on Investment for corporate investments. Returns total and annualized ROI. """ if investment <= 0: raise ValueError("Investment amount must be positive")
total_roi = (profit / investment) * 100 annual_roi = total_roi / years if years > 0else0
defagentic_tool_call(tool_name: str, user_content: str, tool_args: dict = None): """Execute a tool call with agentic response generation."""
# Step 1: Ask model to call the specified tool first = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": SYSTEM}, {"role": "user", "content": user_content} ], tools=TOOLS, tool_choice={"type": "function", "function": {"name": tool_name}}, temperature=0.0 )
msg = first.choices[0].message tool_call = msg.tool_calls[0] if msg.tool_calls elseNone
if tool_call isNone: raise RuntimeError("Model did not issue the expected tool call")
# Step 2: Execute the Python function name = tool_call.function.name model_args = json.loads(tool_call.function.arguments or"{}") call_args = {**model_args, **(tool_args or {})} result = FUNCTIONS[name](**call_args)
# Step 3: Send result back for final analysis messages = [ {"role": "system", "content": SYSTEM}, {"role": "user", "content": user_content}, {"role": "assistant", "content": msg.content or"", "tool_calls": [tool_call.model_dump()]}, {"role": "tool", "tool_call_id": tool_call.id, "name": name, "content": json.dumps(result)} ]
final = client.chat.completions.create( model="gpt-4o-mini", messages=messages, temperature=0.2 )
return final.choices[0].message.content
Example Output
When called with an investment analysis request:
1 2 3 4
result = agentic_tool_call( tool_name="calculate_roi", user_content="Analyze my company's $500,000 investment that earned $125,000 over 3 years." )
The output provides exact figures with professional analysis:
1 2 3 4 5 6 7 8 9 10 11
Your company invested $500,000 and earned a profit of $125,000 over 3 years.
**ROI Analysis:** 1. **Total ROI**: 25.00% - Your investment has grown by a quarter of its original value over the period. 2. **Annualized ROI**: 8.33% - Average return per year, indicating steady growth.
**Recommendation**: A total ROI of 25% over 3 years is a positive outcome. The annualized ROI of 8.33% is competitive compared to traditional savings. Consider reinvesting profits to compound growth.
Structured Outputs with Pydantic
Tools return data, but free-form LLM responses can be inconsistent. Structured outputs ensure machine-readable, validated data that downstream systems can rely on.
@validator('price') deflimit_orders_need_price(cls, v, values): if values.get('order_type') in ['limit', 'stop_limit'] and v isNone: raise ValueError('Limit orders require a price') return v
@validator('stop_price') defstop_orders_need_stop_price(cls, v, values): if values.get('order_type') in ['stop', 'stop_limit'] and v isNone: raise ValueError('Stop orders require a stop price') return v
Tools transform agents from passive responders into active problem-solvers that can perform precise calculations and access real systems
Function calling provides a formal mechanism for LLMs to invoke external functions with proper argument handling
Three-step tool flow: Model requests tool → Backend executes → Model incorporates result into response
Structured outputs with response_format={"type": "json_object"} guarantee valid JSON responses
Pydantic validation catches invalid data before it enters your system, with detailed error reporting
Financial models benefit from strict typing - trade orders, risk assessments, and SWIFT messages all require precise data formats
Combine both patterns for maximum reliability: tools for precise execution, Pydantic for validated outputs
This is the eighth post in my Applied Agentic AI for Finance series. Next: State and Memory for Trading Agents where we’ll explore how agents maintain context across trading sessions.
Comments