Agentic Step 5: Enhance Your Chat App with Agentic Tools
Bring everything together — add tools to the chat app backend so the AI can use a calculator and search Wikipedia during conversations.
What You'll Learn
- Integrating agentic tools into the existing Flask backend
- Adding conversation history for context
- Debugging agent behavior
Step 1: Add Tool Functions to the Backend
Edit backend/app/routes.py. Add the tool functions at the top:
import json
import requests
def calculate(expression: str) -> str:
"""Evaluate a math expression safely."""
try:
allowed = set("0123456789+-*/.() ")
if not all(c in allowed for c in expression):
return "Error: Invalid characters in expression"
result = eval(expression)
return str(result)
except Exception as e:
return f"Error: {str(e)}"
def search_wikipedia(query: str) -> str:
"""Search Wikipedia and return a summary."""
try:
url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + requests.utils.quote(query)
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
return f"Title: {data['title']}\nSummary: {data['extract'][:500]}"
elif response.status_code == 404:
return f"No Wikipedia page found for '{query}'"
else:
return f"Wikipedia error: {response.status_code}"
except Exception as e:
return f"Error: {str(e)}"
Step 2: Define Tools for OpenAI
tools = [
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate a mathematical expression",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Math expression like '2 + 2'"
}
},
"required": ["expression"]
}
}
},
{
"type": "function",
"function": {
"name": "search_wikipedia",
"description": "Search Wikipedia for a topic and get a summary",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The topic to search for"
}
},
"required": ["query"]
}
}
}
]
Step 3: Update the Chat Endpoint
Replace the existing chat() function:
@api.route("/chat", methods=["POST"])
def chat():
data = request.get_json()
user_message = data.get("message", "")
if not user_message:
return jsonify({"error": "Message is required"}), 400
user_msg = Message(content=user_message, sender="user")
db.session.add(user_msg)
db.session.commit()
try:
# Get recent messages for context
recent = Message.query.order_by(Message.timestamp.desc()).limit(10).all()
recent.reverse()
messages = [
{"role": "system", "content": "You are a helpful assistant with a calculator and Wikipedia search. Use these tools when needed."}
]
for msg in recent:
role = "user" if msg.sender == "user" else "assistant"
messages.append({"role": role, "content": msg.content})
# Agent loop
max_turns = 5
for _ in range(max_turns):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
tool_choice="auto",
)
message = response.choices[0].message
if not message.tool_calls:
ai_reply = message.content
break
messages.append(message)
for tool_call in message.tool_calls:
args = json.loads(tool_call.function.arguments)
if tool_call.function.name == "calculate":
result = calculate(args["expression"])
elif tool_call.function.name == "search_wikipedia":
result = search_wikipedia(args["query"])
else:
result = "Unknown tool"
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result,
})
else:
ai_reply = "I couldn't complete that request."
ai_msg = Message(content=ai_reply, sender="ai")
db.session.add(ai_msg)
db.session.commit()
return jsonify({
"user_message": user_msg.to_dict(),
"ai_message": ai_msg.to_dict(),
})
except Exception as e:
return jsonify({"error": str(e)}), 500
Step 4: Install requests
pip install requests
Step 5: Test the Agentic Chat
Start the backend:
cd aiproject/backend
source venv/bin/activate
python app/__init__.py
Test with curl:
# Math — should use calculator
curl -X POST http://localhost:5000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "What is 12345 * 6789?"}'
# Research — should search Wikipedia
curl -X POST http://localhost:5000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "Tell me about the Eiffel Tower"}'
# Simple chat — no tools needed
curl -X POST http://localhost:5000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "Hello!"}'
How It Works Now
User: "What is 12345 * 6789?"
1. Backend saves user message to DB
2. Backend gets recent messages for context
3. Backend calls OpenAI with tools defined
4. OpenAI decides: "I need the calculator tool"
5. Backend executes calculate("12345 * 6789")
6. Backend sends tool result back to OpenAI
7. OpenAI responds with: "12345 × 6789 = 83,810,205"
8. Backend saves AI response to DB
9. Backend returns both messages to mobile app
What Changed
| Before | After |
|---|---|
| Direct reply from AI | AI can use tools |
| No math capability | Calculator tool |
| No research capability | Wikipedia tool |
| One API call | Multiple calls (agent loop) |
| Simple error handling | Max turns to prevent loops |
Your chat app is now agentic. The AI can decide when to calculate, when to search, and when to respond directly.