OpenAI Function Calling with Live Trends API (Python)
Build OpenAI function calling with a live trends API in Python: full tool-calling loop, tool_call_id round-trip, async tools, tool_search and safety.

OpenAI function calling with a live trends API in Python works like this: you describe a tool in JSON, the model decides when to call it, your Python code runs the call against a real endpoint, and you pass the result back so the model can answer with current data. This tutorial does exactly that against the TrendsAGI real-time trend intelligence API, so the tool returns live trend velocity and AI insights instead of a stubbed weather lookup.
Below you get a complete tool-calling loop (including tool_call_id round-tripping), a live API version of the tool, async tool calling, tool_search guidance, and an end-to-end agent that finds a rising trend and proposes a campaign change for human approval. All code reads the API key from an environment variable.
What OpenAI function calling actually does
The “function” tool lets a model decide when to call named tools you expose in your application. The model does not run business logic itself; it returns a structured function call, your code executes the function, and the output is passed back to the model so it can keep reasoning with real system-generated data. That is the whole pattern, and it is why it is useful: answers can include real-time system-generated data (Microsoft Learn).
Two mechanics matter for your loop. OpenAI uses finish_reason: "tool_calls" to signal the model is requesting tool calls, and a function tool result is tied to its call by tool_call_id (Ofox.ai). Miss that ID and the model cannot connect output to request.
Step 1: install and set up
pip install openai trendsagiexport OPENAI_API_KEY="sk-..."
export TRENDSAGI_API_KEY="your-trendsagi-key"TrendsAGI API keys are created in the account profile. The SDK is trendsagi v0.12.0 or later.
Step 2: define the tool schema in Python
OpenAI's guidance is to write clear, detailed function names and parameter descriptions that state each parameter's format and what the output represents (OpenAI Developers). Here is a trend-lookup tool built on TrendsAGI's tools object:
import json
import os
from openai import OpenAI
from trendsagi import TrendsAGIClient, TrendsAGITools
client = OpenAI()
trends_client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
tools = TrendsAGITools(trends_client) # read-only by default
TOOL_SCHEMAS = [
{
"type": "function",
"function": {
"name": "list_trends",
"description": (
"List currently tracked trends, sorted by measured velocity. "
"Returns objects with id (integer), name (string), volume "
"(snapshot post count) and category (string)."
),
"parameters": {
"type": "object",
"properties": {
"category": {
"type": "string",
"description": "Exact category name, e.g. 'Technology'.",
}
},
"required": ["category"],
},
},
},
{
"type": "function",
"function": {
"name": "get_trend_analytics",
"description": (
"Return analytics for one trend over a period. The trend_id "
"must come from list_trends."
),
"parameters": {
"type": "object",
"properties": {
"trend_id": {"type": "integer"},
"period": {
"type": "string",
"enum": ["24h", "7d", "30d"],
},
},
"required": ["trend_id"],
},
},
},
]
SYSTEM_PROMPT = (
"Use list_trends when the user asks what is rising. Call "
"get_trend_analytics only after you have a trend_id. Never guess a "
"trend_id. Quote measured snapshot velocity, not forecasts."
)Step 3: execute the returned function_call and pass output back
Your code runs the function, then appends a message whose tool_call_id matches the call:
def run_tool(name, arguments):
result = tools.call(name, arguments)
if "error" in result:
return json.dumps({"error": result["error"], "detail": result.get("detail")})
return json.dumps(result["result"])
def ask(question):
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": question},
]
while True:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=TOOL_SCHEMAS,
)
choice = response.choices[0]
messages.append(choice.message)
if choice.finish_reason != "tool_calls":
return choice.message.content
for call in choice.message.tool_calls:
args = json.loads(call.function.arguments)
output = run_tool(call.function.name, args)
messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": output,
}
)
print(ask("What is rising in Technology right now?"))Note that tools.call returns {"result": <data>} on success and {"error": ..., "detail": ...} on failure rather than raising. Translating an error into a JSON string keeps the loop alive and gives the model something to reason about.
Step 4: wire the tool to the live API, not a stub
You can bypass the wrapper and call the SDK directly if you want tighter control over what the model sees:
def live_trend_snapshot(category):
trends = trends_client.get_trends(
category=category, sort_by="velocity", limit=5
)
return trends
trends = trends_client.get_trends(category="Technology", sort_by="velocity", limit=5)
top_id = trends[0]["id"]
analytics = trends_client.get_trend_analytics(top_id, period="7d")
insights = trends_client.get_ai_insights(top_id)This is the same data the model gets through the tool. Keep the raw response small and stable: return a trimmed dictionary of IDs, names, velocity and category so the model has enough to select a trend without drowning in fields. If you need the underlying REST endpoint for another language, it is GET https://api.trendsagi.com/api/trends with the header X-API-Key.
Step 5: safety, sendboxing and rate limits
- Read-only by default.
TrendsAGITools(client)exposes read tools only. Write tools appear only withTrendsAGITools(client, allow_writes=True). - Opt in deliberately. Do not enable writes in the same agent that drafts public copy. Keep the read agent separate.
- Watch usage. The
get_api_usagetool (and GET/api/user/api-usage) tells you how many requests you have spent. Each MCP tool call counts as one API request. - Preview ad changes. TrendsAGI ad-platform connectors preview changes before any explicit execution, so your agent should always surface that preview for a human.
- Verify webhooks. Deliveries carry
X-Webhook-Signature, a lowercase hex HMAC-SHA256 of the raw body. Verify against unmodified bytes with a constant-time comparison.
Async tool calling and tool_search
Adding async: true to a tool definition makes the call items in response.output include async: true and lets the lookup run in the background (OpenAI Developers). For async function tools the call item is function_call and the output item is function_call_output. That suits slow trend lookups where you want the model to keep working before the data lands:
async_tool = {
"type": "function",
"function": {
"name": "get_trend_analytics",
"description": "Return analytics for a trend over a period.",
"async": True,
"parameters": {
"type": "object",
"properties": {"trend_id": {"type": "integer"}},
"required": ["trend_id"],
},
},
}Support for async behavior depends on the endpoint and model you use; check OpenAI's documentation for your setup rather than assuming it applies.
The tool_search tool lets the model search for relevant tools, add them to the model context, and then use them (OpenAI Developers). Reach for it once you have dozens of tools — for example separate trend, analytics, recommendation, crisis and watchlist tools — so you don't paste every schema into every request. With a handful of tools, plain function definitions are simpler.
Multi-turn loop with the function tool
The loop above is already multi-turn: each iteration appends the assistant's tool-call message and one tool message per call, then re-calls the model. To let a human reply mid-conversation, append their message and call ask again with the full history rather than starting fresh.
End-to-end example: find a trend, read the insight, propose a change
recommendations = trends_client.get_recommendations(limit=10, priority="high")
if recommendations:
rec = recommendations[0]
print("Proposed action:", rec)
print("Awaiting human approval before any execution.")
else:
print("No high-priority recommendation right now.")client.call_tool = None # placeholder note: use tools.call in the loop aboveThe realistic flow is: ask for a category, let the model call list_trends, pass back the top ID, let it call get_trend_analytics, then get_trend_ai_insights, then list_recommendations. The final message is a proposed action, not an execution. If a write is needed, use the approved path via POST /api/intelligence/recommendations/{id}/action after a human confirms, and pair it with an ad connector preview.
Building an agent loop with the SDK
The tool schemas above map directly to TrendsAGI's agent tools, so you can hand the same tools to OpenAI, Claude or LangChain without rewriting them:
openai_tools = tools.openai()
responses_tools = tools.openai_responses()
claude_tools = tools.anthropic()
langchain_tools = tools.langchain()For hosted agents, the MCP server is the shortest route: pip install "trendsagi[mcp]", then run trendsagi mcp with TRENDSAGI_API_KEY set. Claude Code users can run claude mcp add trendsagi --env TRENDSAGI_API_KEY=... -- trendsagi mcp. The hosted server at https://api.trendsagi.com/mcp uses an API key as a Bearer token and exposes read-only tools.
Frequently asked questions
How do I define an OpenAI function tool in Python so the model can call it?
Build a list of dictionaries with type set to "function", then name, description, and a JSON-schema parameters object, and pass it as tools to the chat completion call. State each parameter's format and what the output represents.
How do I execute the returned function_call and pass its output back to the model?
Check finish_reason == "tool_calls", read call.function.name and call.function.arguments, run your function, then append a message with role: "tool", the matching tool_call_id (from call.id) and the JSON result. Repeat until the model stops requesting tools.
How do I connect the tool to a real-time data source instead of a stub?
Replace the stub body with a call to your data source, such as tools.call("list_trends", {...}) against the TrendsAGI API, and return a small trimmed dictionary. Keep the function signature and output shape identical so the schema stays accurate.
What is the difference between the function tool, async tool calling, and tool_search?
The function tool lets the model request one of your named tools. Async tool calling (async: true) lets a lookup run in the background and returns function_call and function_call_output items. Tool_search lets the model search for relevant tools and add them to context before using them.
How do I structure a multi-turn tool-calling loop in Python?
Use a while True loop: call the model, append the assistant message, append one tool message per call, and break when the finish reason is no longer tool_calls. Keep the full message list so the model retains history across turns.
How should I write function names and parameter descriptions for reliable tool selection?
Use precise, verb-led names and describe formats explicitly, and use the system prompt to say when and when not to use each function (OpenAI Developers). Mention units, enum values and that IDs must come from a previous call.
How we researched this
Prepared by TrendsAGI Research. Facts checked on 23 October 2026 against the sources listed below.
Capability descriptions and code use TrendsAGI's documented REST API, Python SDK and MCP server. External facts come from the sources below.
| Claim | Applies to | Source |
|---|---|---|
| The function tool lets a model decide when to call named tools you expose, and the model returns a structured function call rather than running business logic directly. | All plans | learn.microsoft.com |
| After the model returns a function call, your code runs the function and you pass the function output back to the model so it continues reasoning. | All plans | learn.microsoft.com |
| Answers produced through this pattern can include real-time system-generated data. | All plans | learn.microsoft.com |
| Adding async: true to a tool definition makes the corresponding call items in response.output include async: true and lets the lookup run in the background. | All plans | developers.openai.com |
| For async function tools, the call item is function_call and the output item is function_call_output. | All plans | developers.openai.com |
| The tool_search tool lets the model search for relevant tools, add them to the model context, and then use them. | All plans | developers.openai.com |
| Best practice is to write clear, detailed function names and parameter descriptions that explicitly describe each parameter's format and what the output represents. | All plans | developers.openai.com |
| The system prompt should describe when and when not to use each function. | All plans | developers.openai.com |
| In OpenAI's tool-calling result mapping, an OpenAI function tool result is tied to the call by tool_call_id. | All plans | ofox.ai |
| OpenAI uses finish_reason: "tool_calls" to signal that the model is requesting tool calls. | All plans | ofox.ai |
We re-research and rewrite this page at least every four months; the updated date only changes when the facts are re-checked.
Sources
- Use the function tool - Training (Microsoft Learn) — learn.microsoft.com
- Async tool calling | OpenAI API (OpenAI Developers) — developers.openai.com
- Function Calling: руководство по OpenAI и Claude API (2026) (Ofox.ai) — ofox.ai