OpenAI Function Calling with Live Trends API (Python)
Python tutorial: wire OpenAI function calling to a live trends API. Register TrendsAGITools, run the call-execute-return loop, handle quotas and stream real

OpenAI function calling with real-time data in Python
OpenAI function calling (also called tool calling) lets models interface with external systems and access data outside their training data by defining tools via JSON schema. The model emits a tool call, the application executes it, and returns the output for a final response. Official documentation on developers.openai.com describes a multi-step flow with the Responses API (preferred for newer models) and Python SDK examples that include streaming of function arguments in real time. Chat Completions remains supported.
Most tutorials stop at a mocked weather function. This guide replaces the mock with a live trends API so an agent can list rising topics, read measured velocity and volume, pull AI insights, and surface recommendations—all without inventing schemas. The TrendsAGI Python client (available on PyPI as trendsagi and documented on GitHub under TrendsAGI Official Python Client) ships ready-made OpenAI tools that plug directly into the official call–execute–return loop.
What function calling actually does
You declare tools with a name, description and JSON schema for parameters. The model decides when a tool is needed and returns a structured tool call instead of (or before) a final answer. Your code runs the tool, feeds the result back, and the model continues. Built-in tools, custom tools, async tool calling and tool search for large schemas are all documented on developers.openai.com.
For real-time data the critical requirement is that the tool returns current measurements rather than static or hallucinated values. TrendsAGI measures velocity as a snapshot rate of posts per hour, reports growth, and supplies AI-generated summaries, key themes, sentiment, audience notes and marketing angles. Recommendation confidence reflects evidence completeness, not a probability of success.
Install and authenticate
Install the client:
pip install trendsagi
Create an API key in your TrendsAGI account profile. Authenticate with the header X-API-Key or Authorization: Bearer. The base URL is https://api.trendsagi.com. Always load the key from an environment variable:
import os
from trendsagi import TrendsAGIClient
client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
Register TrendsAGI tools for OpenAI
TrendsAGITools wraps the client and returns tool definitions that OpenAI can consume. Tools are read-only by default; write tools are opt-in.
from trendsagi import TrendsAGITools
tools = TrendsAGITools(client) # read-only
# tools = TrendsAGITools(client, allow_writes=True) # adds write tools
openai_tools = tools.openai() # Chat Completions format
responses_tools = tools.openai_responses() # Responses API format
Available tool names include list_trends, list_trend_categories, search_trend_insights, get_trend, get_trend_ai_insights, get_trend_analytics, list_recommendations, list_crisis_events, list_watchlist and get_api_usage. With allow_writes=True the set also includes add_to_watchlist and update_recommendation.
Execute any tool call with:
result = tools.call("list_trends", {"category": "Technology", "sort_by": "velocity", "limit": 5})
# success: {"result": {"trends": [...], "total": N}}
# failure: {"error": "...", "detail": "..."}
Read the data from result["result"] when present.
Chat Completions loop
A minimal Chat Completions example that lets the model list high-velocity technology trends:
from openai import OpenAI
import os
from trendsagi import TrendsAGIClient, TrendsAGITools
openai_client = OpenAI()
client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
tools = TrendsAGITools(client)
messages = [
{"role": "user", "content": "What are the fastest-rising technology trends right now?"}
]
response = openai_client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools.openai(),
tool_choice="auto",
)
msg = response.choices[0].message
if msg.tool_calls:
messages.append(msg)
for tc in msg.tool_calls:
out = tools.call(tc.function.name, eval(tc.function.arguments) if tc.function.arguments else {})
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": str(out),
})
final = openai_client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools.openai(),
)
print(final.choices[0].message.content)
else:
print(msg.content)
Responses API loop
The Responses API is the preferred path for newer models. The same tools work via tools.openai_responses():
response = openai_client.responses.create(
model="gpt-4o",
input="List the top velocity technology trends and summarise the first one.",
tools=tools.openai_responses(),
)
# Inspect response.output for tool calls, execute with tools.call,
# then submit the results in a follow-up responses.create call.
Streaming of function-call arguments is supported by the official Python SDK; you receive partial argument deltas while the model is still generating the tool call, which is useful when the subsequent TrendsAGI call may take a moment.
MCP server alternative
If you prefer the Model Context Protocol, install the optional extra and run the server:
pip install "trendsagi[mcp]"
# TRENDSAGI_API_KEY must be set
trendsagi mcp
# or with write tools:
trendsagi mcp --allow-writes
Claude Code registration example:
claude mcp add trendsagi --env TRENDSAGI_API_KEY=... -- trendsagi mcp
JSON config for Claude Desktop, Cursor or VS Code:
{
"mcpServers": {
"trendsagi": {
"command": "trendsagi-mcp",
"env": {"TRENDSAGI_API_KEY": "..."}
}
}
}
Safety and rate limits
Tools are read-only unless you explicitly pass allow_writes=True. Ad-platform connectors preview changes before any explicit execution. Always call get_api_usage before heavy work so the agent can see remaining quota and avoid unexpected failures:
usage = tools.call("get_api_usage", {})
print(usage)
When a call fails, tools.call returns an object with "error" and "detail" keys instead of raising; surface those fields to the model so it can recover or inform the user.
End-to-end agent example
The following agent finds a rising trend in a category, checks its analytics, reads the AI insight and proposes a campaign change for human approval. Write tools remain disabled; the recommendation is only suggested in the final text.
import os
from openai import OpenAI
from trendsagi import TrendsAGIClient, TrendsAGITools
openai_client = OpenAI()
client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
tools = TrendsAGITools(client) # read-only
messages = [{
"role": "user",
"content": (
"Find the highest-velocity Technology trend, pull its 7-day analytics "
"and AI insights, then propose one concrete campaign change a marketer "
"could make. Do not execute any write actions."
)
}]
# First turn – model decides which tools to call
resp = openai_client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools.openai(),
tool_choice="auto",
)
msg = resp.choices[0].message
messages.append(msg)
# Execute every tool call the model requested
for tc in msg.tool_calls or []:
args = eval(tc.function.arguments) if tc.function.arguments else {}
out = tools.call(tc.function.name, args)
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": str(out),
})
# Final turn – model synthesises the answer
final = openai_client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools.openai(),
)
print(final.choices[0].message.content)
Typical flow the model follows: list_trends with category="Technology" and sort_by="velocity", then get_trend_analytics with period="7d", then get_trend_ai_insights, finally a natural-language proposal that a human can approve or reject.
When a live trends feed is the right tool
Prefer a measured trends API when the agent needs current volume, velocity or growth numbers rather than general knowledge or web-search snippets. Use built-in web search for broad factual lookup, custom tools for internal systems, and the TrendsAGI tools (or MCP server) when the decision depends on what is rising right now on social platforms. The same OpenAI loop works for all of them; only the tool registry changes.
Frequently asked questions
How do I define an OpenAI function/tool schema in Python for a live trends endpoint?
You do not have to write the schema by hand. TrendsAGITools.openai() and TrendsAGITools.openai_responses() already return the complete list of tool definitions that OpenAI expects. Pass the returned list to the tools parameter of chat.completions.create or responses.create.
What is the complete call–execute–return loop with the current Responses API versus Chat Completions?
Both follow the same pattern: send messages plus tools, receive a tool call, execute it with tools.call, append the result, and call the model again. Chat Completions uses messages with role "tool"; the Responses API uses its own output and input structures documented on developers.openai.com. The Responses API is preferred for newer models.
How can I stream function-call arguments while fetching real-time data?
OpenAI’s Python SDK supports streaming of function-call argument deltas. You can start preparing the TrendsAGI call as soon as the tool name and partial arguments arrive, then finish the call once the full arguments are available.
How do I register TrendsAGI’s ready-made agent tools so the model can list trends or pull AI insights?
Instantiate TrendsAGITools with your client, then pass tools.openai() (Chat Completions) or tools.openai_responses() (Responses API) to the model. The model can then call list_trends, get_trend_ai_insights and the other documented tool names.
What error handling, rate-limit, and quota behaviour should I expect from a live trends API?
tools.call returns {"error": "...", "detail": "..."} on failure instead of raising. Call get_api_usage to inspect remaining quota before large batches. Rate limits and daily quotas are enforced by the API; surface the error object to the model so it can decide whether to retry or inform the user.
When should I prefer a real-time trends feed over a static mock or web-search tool?
Use a live trends feed when the answer depends on current velocity, volume, growth or AI-generated insight about a rising topic. Mocks are fine for unit tests; web search is better for general knowledge. Measured social signals are required when the agent must act on what is gaining attention right now.
Sources
- Function calling | OpenAI API — developers.openai.com
- TrendsAGI Official Python Client (GitHub / TrendsAGI) — github.com
- trendsagi (PyPI) — pypi.org