Connecting Chat AI to APIs and Real-World Automation
The real power of Chat AI emerges when it can take actions, not just answer questions. Learn how to connect AI to APIs and automate real-world tasks.
From Conversation to Action
Why Function Calling Matters
Traditional chatbots are limited to text responses. With function calling (also called tool use), AI can:
- Query databases
- Call external APIs
- Perform calculations
- Trigger workflows
- Update systems
- Retrieve real-time data
How It Works
- Define Tools: Describe available functions
- Model Decides: AI determines when to use tools
- Execute Function: Your code runs the function
- Return Result: Feed result back to AI
- Generate Response: AI formulates final answer
Function Calling Basics
OpenAI Function Calling
const tools = [
{
type: "function",
function: {
name: "get_current_weather",
description: "Get the current weather in a given location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "City and state, e.g. San Francisco, CA"
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"]
}
},
required: ["location"]
}
}
}
];
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{role: "user", content: "What's the weather in Boston?"}],
tools: tools,
tool_choice: "auto"
});
if (response.choices[0].message.tool_calls) {
const toolCall = response.choices[0].message.tool_calls[0];
const args = JSON.parse(toolCall.function.arguments);
// Execute the function
const weatherData = await getWeather(args.location, args.unit);
// Send result back to model
const finalResponse = await openai.chat.completions.create({
model: "gpt-4",
messages: [
...messages,
response.choices[0].message,
{
role: "tool",
tool_call_id: toolCall.id,
content: JSON.stringify(weatherData)
}
]
});
}
Anthropic Tool Use
import anthropic
client = anthropic.Anthropic()
tools = [
{
"name": "get_stock_price",
"description": "Get the current stock price for a given ticker symbol",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "Stock ticker symbol, e.g. AAPL"
}
},
"required": ["ticker"]
}
}
]
response = client.messages.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's Apple's stock price?"}],
tools=tools,
max_tokens=1024
)
if response.stop_reason == "tool_use":
tool_use = next(block for block in response.content if block.type == "tool_use")
# Execute function
if tool_use.name == "get_stock_price":
result = get_stock_price(tool_use.input["ticker"])
# Continue conversation with result
follow_up = client.messages.create(
model="claude-3-sonnet-20240229",
messages=[
{"role": "user", "content": "What's Apple's stock price?"},
{"role": "assistant", "content": response.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": str(result)
}
]
}
]
)
Common Integration Patterns
1. Database Queries
Allow AI to retrieve information:
const tools = [{
name: "search_customers",
description: "Search customer database by name or email",
parameters: {
type: "object",
properties: {
query: { type: "string" },
limit: { type: "number", default: 10 }
},
required: ["query"]
}
}];
async function searchCustomers(query: string, limit: number) {
const results = await db.customers.find({
$or: [
{ name: { $regex: query, $options: 'i' } },
{ email: { $regex: query, $options: 'i' } }
]
}).limit(limit);
return results;
}
2. Third-Party APIs
Connect to external services:
async def get_flight_info(flight_number: str):
"""Get real-time flight status"""
url = f"https://api.flightaware.com/flights/{flight_number}"
headers = {"Authorization": f"Bearer {API_KEY}"}
response = await httpx.get(url, headers=headers)
return response.json()
tools = [{
"name": "get_flight_info",
"description": "Get real-time flight status and details",
"parameters": {
"type": "object",
"properties": {
"flight_number": {"type": "string"}
},
"required": ["flight_number"]
}
}]
3. Calculations and Processing
Offload complex computations:
function calculateMortgagePayment(
principal: number,
annualRate: number,
years: number
): number {
const monthlyRate = annualRate / 100 / 12;
const numPayments = years * 12;
return (principal * monthlyRate * Math.pow(1 + monthlyRate, numPayments)) /
(Math.pow(1 + monthlyRate, numPayments) - 1);
}
const tools = [{
name: "calculate_mortgage",
description: "Calculate monthly mortgage payment",
parameters: {
type: "object",
properties: {
principal: { type: "number", description: "Loan amount" },
annual_rate: { type: "number", description: "Annual interest rate" },
years: { type: "number", description: "Loan term in years" }
},
required: ["principal", "annual_rate", "years"]
}
}];
4. Workflow Automation
Trigger multi-step processes:
async function createSupportTicket(data: {
customer_email: string;
issue_type: string;
priority: string;
description: string;
}) {
// Create ticket in system
const ticket = await tickets.create(data);
// Send confirmation email
await sendEmail({
to: data.customer_email,
subject: `Support Ticket #${ticket.id} Created`,
body: `Your ticket has been created...`
});
// Notify support team
await slack.postMessage({
channel: "#support",
text: `New ${data.priority} ticket: ${ticket.id}`
});
return { ticket_id: ticket.id, status: "created" };
}
Advanced Patterns
Multi-Tool Orchestration
AI can chain multiple function calls:
User: "Book me a flight to Paris and reserve a hotel"
AI Process:
- Call
search_flights(destination="Paris") - Present options
- After user selection:
book_flight(flight_id) - Call
search_hotels(location="Paris") - After user selection:
book_hotel(hotel_id) - Confirm both bookings
Conditional Logic
AI determines which tools to use based on context:
const tools = [
{ name: "check_inventory", ... },
{ name: "place_order", ... },
{ name: "notify_backorder", ... }
];
// AI automatically:
// 1. Checks inventory
// 2. If available: places order
// 3. If not: notifies about backorder
Error Handling
Implement robust error management:
async def execute_tool(tool_name: str, arguments: dict):
try:
if tool_name == "send_email":
return await send_email(**arguments)
elif tool_name == "create_order":
return await create_order(**arguments)
except AuthenticationError:
return {"error": "Authentication failed. Please reconnect."}
except RateLimitError:
return {"error": "Too many requests. Please try again later."}
except Exception as e:
logger.error(f"Tool execution failed: {e}")
return {"error": "An unexpected error occurred."}
Security Considerations
1. Authentication and Authorization
Verify user permissions before executing tools:
async function executeFunction(
userId: string,
functionName: string,
args: any
) {
// Check permissions
const hasPermission = await checkPermission(userId, functionName);
if (!hasPermission) {
throw new Error("Unauthorized");
}
// Execute with user context
return await functions[functionName](userId, args);
}
2. Input Validation
Validate all function arguments:
from pydantic import BaseModel, validator
class TransferFundsInput(BaseModel):
from_account: str
to_account: str
amount: float
@validator('amount')
def amount_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Amount must be positive')
if v > 10000:
raise ValueError('Amount exceeds transfer limit')
return v
3. Rate Limiting
Prevent abuse:
const rateLimiter = new RateLimiter({
tokensPerInterval: 10,
interval: "minute"
});
async function safeExecuteFunction(userId: string, func: Function) {
if (!await rateLimiter.tryRemoveTokens(userId, 1)) {
throw new Error("Rate limit exceeded");
}
return await func();
}
4. Audit Logging
Track all function executions:
await auditLog.record({
userId,
action: functionName,
arguments: sanitizedArgs,
result: result.status,
timestamp: new Date(),
ip: request.ip
});
Testing Function Calling
Unit Tests
Test individual functions:
def test_calculate_shipping():
result = calculate_shipping(
weight=5.0,
destination="US",
shipping_class="standard"
)
assert result["cost"] == 12.50
assert result["estimated_days"] == 5
Integration Tests
Test AI + function execution:
test("AI can calculate and explain shipping cost", async () => {
const response = await chatWithFunctions(
"How much to ship 5 pounds to California?",
[calculateShippingTool]
);
expect(response.tool_calls).toHaveLength(1);
expect(response.tool_calls[0].name).toBe("calculate_shipping");
expect(response.message).toContain("$12.50");
});
Best Practices
- Clear Descriptions: Make tool descriptions specific and comprehensive
- Type Safety: Use TypeScript/Pydantic for argument validation
- Error Messages: Provide actionable error information
- Timeouts: Set reasonable timeout limits
- Idempotency: Make functions safe to retry
- Logging: Track all executions for debugging
- Graceful Degradation: Handle API failures gracefully
- User Confirmation: Confirm before destructive actions
Conclusion
Function calling transforms Chat AI from informational to transactional, unlocking countless automation possibilities. Start with simple integrations, prioritize security, and gradually build more sophisticated workflows as you learn what works for your use case.
