Expose a Local FastAPI Service as Tools for a Voice AI Agent
System DesignModel answerLast updated
Design and harden two HTTP tool endpoints that let a hosted conversational agent store a user's reported problem and recite earlier ones, with a local server made reachable.
Wiring a Voice Agent to a Local Service
You have a small Python project built on FastAPI running on your laptop. A third-party hosted platform runs conversational AI agents that talk with end users, possibly over a phone call. Your goal is to let the agent do two things mid-conversation:
- Record a problem the user describes (an "issue").
- Recite the user's earlier issues when they ask about them.
Plan and build a working round trip from the hosted agent to your local service and back for both operations. Then explain how you would make it robust.
Assumptions
- The platform lets you register custom tools that the agent's language model can invoke during a conversation. Each tool has a name, a plain-language description, an argument schema, and an HTTPS URL. The platform calls that URL with the arguments the model extracted, and whatever you return is passed back to the model, which then speaks to the user.
- The conversation may be spoken, so anything read aloud must be short and easy to say.
- If the codebase has no issue storage, an in-memory store or SQLite is fine.
- The exact request and response formats of the platform are unknown. Confine any dependence on them to a single place in your code.
What to cover
- How the hosted platform reaches a server running on your machine.
- Tool names, descriptions, argument schemas, and the agent instructions that tell the model when to call each tool.
- The FastAPI endpoints, validation, and storage.
- How the user is identified so nobody hears another person's issues.
- How read-back output is shaped for speech, including the empty case.
- Failure handling: request authentication, duplicate saves from retries, slow or failing endpoints, and what the agent says when a tool fails.
- How you would test locally before connecting the platform.
You may also list the clarifying questions you would ask first.
Hints
Hint 1
Separate the platform-specific envelope (how arguments, call metadata and the response are wrapped) from your business logic, so only one small adapter changes if the format differs from your guess.
Hint 2
Never let the model supply the user's identity as a tool argument. Take it from trusted call metadata (such as a caller number or session ID) that the platform sends, and scope every query by it.
Hint 3
Platforms may retry on timeouts, so make the save operation idempotent using a call/tool-call ID or a content hash, and keep read-back responses short, ordered newest first and capped at a small number.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying questions first
- What does the codebase already include (models, storage, routes, tests)?
- What exactly does the platform POST to a tool URL: only the model's arguments, or also call metadata (call ID, caller number)? What response shape does it expect?
- How is the user identified?
- Is an issue just free text, or does it have category and priority?
- Does the platform retry on timeout or error, and what is its timeout?
Architecture
User (voice) -> Agent platform (LLM) -> HTTPS tool call -> tunnel -> local FastAPI -> store
<- short text result <-
Reachability. A laptop is not publicly addressable, so run a tunnel (ngrok, Cloudflare Tunnel) that exposes localhost:8000 at a public HTTPS URL, and register that URL with the platform. Trade-off: tunnel URLs often change on restart, so keep the base URL in config. For production, deploy to a real host.
Tool definitions
Two tools, with descriptions written for the model:
save_issue(description: string, category?: enum): "Call once the user has finished describing a problem they want recorded. Do not call for general questions."list_past_issues(limit?: int = 3): "Call when the user asks about problems they reported earlier."
In the agent instructions: confirm the issue in one sentence before saving, call each tool at most once per request, and say a fixed fallback line if a tool errors. Keep schemas small; the fewer free fields, the fewer extraction mistakes.
Endpoints
from fastapi import FastAPI, Header, HTTPException, Depends
from pydantic import BaseModel, Field
import sqlite3, hashlib, os, time
app = FastAPI()
SECRET = os.environ["TOOL_SECRET"]
def auth(x_tool_secret: str = Header(...)):
if x_tool_secret != SECRET:
raise HTTPException(401)
class Envelope(BaseModel): # the ONLY platform-specific piece
call_id: str
caller_id: str
args: dict
class SaveArgs(BaseModel):
description: str = Field(min_length=3, max_length=500)
@app.post("/tools/save_issue", dependencies=[Depends(auth)])
def save_issue(env: Envelope):
a = SaveArgs(**env.args)
key = f"{env.call_id}:{hashlib.sha1(a.description.encode()).hexdigest()}"
with db() as c:
c.execute("""INSERT OR IGNORE INTO issues
(idem_key, user_id, text, created_at)
VALUES (?,?,?,?)""",
(key, env.caller_id, a.description, time.time()))
return {"result": "Saved. I have recorded that issue."}
@app.post("/tools/list_past_issues", dependencies=[Depends(auth)])
def list_issues(env: Envelope):
limit = min(int(env.args.get("limit", 3)), 5)
rows = db().execute(
"SELECT text FROM issues WHERE user_id=? ORDER BY created_at DESC LIMIT ?",
(env.caller_id, limit)).fetchall()
if not rows:
return {"result": "You have no issues on file."}
spoken = "; ".join(f"{i+1}: {r[0][:80]}" for i, r in enumerate(rows))
return {"result": f"Your latest {len(rows)} issues are. {spoken}."}
The table has a UNIQUE constraint on idem_key and an index on (user_id, created_at).
Key design decisions
User identity. Derive user_id from trusted metadata (caller number or authenticated session) supplied by the platform, never from a model-provided argument. A model can be talked into asking for someone else's data; the server must make that impossible by scoping every query by the trusted ID. If the identity is a phone number, remember that it can be spoofed, so treat it as weak and consider a verification step for sensitive data.
Authentication. Require a shared secret header (or HMAC signature over the body, which also protects integrity and allows timestamp checks against replay). Without it, anyone who finds the tunnel URL can write data.
Idempotency. Platforms and networks retry. Use the platform's tool-call ID if available; otherwise combine call ID and content hash as above. INSERT OR IGNORE against a unique key makes a retried save harmless. Trade-off: a content hash would also suppress a user deliberately reporting the same issue twice in one call; accept that or include a turn index.
Speech-friendly output. Cap at 3 to 5 items, newest first, truncate each to about 80 characters, avoid markdown, IDs, timestamps in ISO format, and nested structures. Handle empty explicitly. Return a result string the model can read nearly verbatim.
Latency and failure. Voice users notice silence after roughly 1 to 2 seconds. Keep handlers synchronous and fast (SQLite on an index is sub-millisecond), set server timeouts, and return a clear, short error body with a 5xx rather than a stack trace. In the agent prompt, define a graceful line such as "I couldn't save that just now, could you try again in a moment?" so the model does not claim success. Never return a "Saved" message unless the commit succeeded.
Validation. Pydantic limits on length, enum for category, and a clamp on limit. Parameterized SQL only.
Testing
- Unit-test handlers with FastAPI's
TestClient: save, list, empty list, duplicate save, wrong secret, another user's ID. curlthe tunnel URL with a sample envelope.- Use the platform's test console to confirm the model calls the right tool and the spoken result sounds natural.
- Log call ID, tool, latency and status for debugging.
Common mistakes
- Trusting a model-supplied user ID.
- No auth on a publicly tunneled endpoint.
- Non-idempotent saves that create duplicates on retry.
- Returning long JSON or paragraphs that are painful to hear.
- Scattering platform format assumptions across handlers.
- Saying "done" after a failed call.
- Forgetting the tunnel URL changes between restarts.
Possible follow-ups
Moving to Postgres and a hosted deployment, summarizing many issues, asynchronous saves with a queue for slow work, deleting data on request, and rate limiting per caller.