Building Agent Workflows
Unlock the full potential of your autonomous agents by connecting them to the TrendsAGI Context Layer.
Agent Initialization
Welcome to TrendsAGI. This guide shows how marketers, operators, and technical teams can connect one-click integrations or use advanced custom setup with the same signal layer.
Two Setup Paths
Use one-click setup when you want the fastest path in the UI. Use advanced custom setup when you want provider writes and worker execution to stay in your own infrastructure.
1. Agent Authentication
Your API key identifies your agent and manages its rate limits.
- Navigate to your Profile Page.
- Select the "API Keys" tab.
- Generate a key to act as your agent's token.
Security Best Practice
Treat this key like your agent's password. Store it in environment variables (e.g., TRENDSAGI_API_KEY), not in your source code.
2. Initialize the Client
The Python client is the standard interface for Python-based agents (LangChain, AutoGPT, etc).
pip install trendsagi3. The Agent's First Breath
Initialize the client and poll for active signals to "wake up" your agent's awareness.
from trendsagi import TrendsAGIClient, APIError
import os
# Initialize the sensory layer
client = TrendsAGIClient(api_key=os.getenv("TRENDSAGI_API_KEY"))
try:
# Agent checks for high-velocity signals in the 'Technology' sector
signals = client.get_trends(limit=5, category="Technology", sort_by="velocity")
print(f"Agent Awareness Initialized. Detected {len(signals.trends)} active signals.")
for signal in signals.trends:
print(f" - Signal Detected: {signal.name} (Velocity: {signal.volume})")
except APIError as e:
print(f"Sensory Input Failed ({e.status_code}): {e.error_detail}")Ads Platform Integrations
One-click ad integrations for paid social and search execution. Connect Google, Meta, TikTok, LinkedIn, Microsoft, Snapchat, Pinterest, and Amazon Ads in one click, then optionally enable advanced custom setup. TrendsAGI maps positive trend categories to additive keyword and targeting updates with safety guardrails.
Use Case 1: Programmatic Audience Targeting
Your workflow can dynamically update campaign settings from category-driven positive trend keywords.
- Discover: Select a category or trend from the Ads mapping flow.
- Analyze: TrendsAGI resolves the latest positive trend and extracts audience keywords.
- Execute: Preview or apply guardrailed targeting updates to mapped campaign entities.
Two Integration Paths
One-click setup: Managed account connection and token handling in TrendsAGI.
Advanced custom setup: Keep provider credentials and execution workers fully in your own infrastructure.
Use Case 2: Context-Aware Copy Generation
Prevent generic ad copy. Inject our "Sentiment Summary" and "Key Themes" into your LLM's system prompt to force it to write copy that aligns with the current public mood.
# Example: Preparing a prompt for an Ad Generator Agent
trend_id = 123
insights = client.get_ai_insights(trend_id=trend_id)
# Constructing the System Prompt Context
# Note: These are retrieved from the cache. New insights must be triggered via the dashboard.
system_context = {
"topic": insights.trend_name,
"current_public_mood": insights.sentiment_summary,
"marketing_hook": insights.suggested_marketing_angle,
"taboo_subjects": insights.negative_themes # Guardrails
}
prompt = f"""
You are an expert copywriter.
Topic: {system_context['topic']}
Mood: {system_context['current_public_mood']}
Hook: {system_context['marketing_hook']}
Task: Write 3 Facebook Ad headlines that align with this mood.
"""
# agent.llm.predict(prompt)
Content Ops Agents
Deploy Content Ops Agents that autonomously manage your editorial calendar. By feeding your agents data on "People Also Ask" queries and rising topics, you ensure every piece of content captures existing demand.
Use Case 1: The 'Newsjacker' Agent
Create an agent that monitors your niche for breakout velocity. When a topic crosses a specific growth threshold, the agent automatically drafts a blog post outline.
- Poll
get_trendssorted bygrowth. - If
growth > 200%, trigger the content workflow. - Use
ai_insights.suggested_content_angleas the H1 title. - Use
ai_insights.key_themesto generate H2 headers.
Use Case 2: Hallucination Reduction
LLMs often make up facts when writing about new topics. Use our API to inject a "Fact Sheet" into the context window so the agent has grounded truth to work from.
# Fetch grounded, cached context before generation
trends_response = client.get_trends(search="sustainable fashion", limit=1)
trend = trends_response.trends[0]
insights = client.get_ai_insights(trend_id=trend.id)
print(f"--- Fact Sheet for Agent ---")
print(f"Context: {insights.trend_name}")
print(f"Verified Themes: {', '.join(insights.key_themes)}")
print(f"Audience Sentiment: {insights.sentiment_category}")
# The agent uses 'Verified Themes' as a checklist for content sections.
Retail Intelligence Agents
Power Retail Intelligence Agents that adjust your storefront based on what the world is talking about. These agents can automatically re-rank products or tag items as "Trending" without human intervention.
Use Case: Dynamic Merchandising Agent
Run a background agent that maps external trends to your internal SKUs. If "Retro Gaming" trends on social, your agent moves your retro console inventory to the homepage.
Implementation Logic
The agent acts as a semantic bridge: Trend Name (API) ↔ Vector Embedding Match ↔ Product Category (DB).
# Background Job: Update 'Trending Now' Collection
CATEGORIES = ["Fashion", "Electronics", "Home"]
for cat in CATEGORIES:
# 1. Agent observes the market
trends = client.get_trends(category=cat, limit=3)
# 2. Agent decides which products match
for trend in trends.trends:
print(f"Market Signal: {trend.name}")
# vector_search_products(query=trend.name) -> returns matching SKUs
# 3. Agent updates the database
# db.update_collection(name="trending_now", items=matching_skus)
Low-Code Orchestration
Orchestrate Low-Code Agent Workflows. Use N8N as the logic layer to trigger actions in Trello, Slack, or WordPress whenever TrendsAGI detects a signal.
Workflow: Automated Briefing Agent
- Trigger: N8N HTTP Request node polls
GET /api/trendsevery hour. - Logic: "IF" node checks if
trend.growth > 100%. - Enrichment: HTTP Request to
GET /api/trends/:id/ai-insightsfor the summary. - Action: N8N uses an OpenAI node to summarize the insight into a slack message.
- Output: Message sent to
#marketing-alertschannel: "New Trend Detected: [Name]. Sentiment: [Positive]. Suggested Angle: [Angle]".
No Code Required
This allows non-technical teams to deploy powerful AI agents that monitor the market 24/7.
Enterprise AI (Vertex)
Build Enterprise-Grade Agents on Google Cloud Vertex AI. Create custom "Tools" for your LangChain or AutoGPT agents, giving them the ability to query the real world.
Use Case: The 'Market Analyst' Agent
Define a custom tool function. When a user asks the agent "What is happening in Tech right now?", the agent knows to call this tool rather than hallucinating an answer.
from langchain.agents import tool
from trendsagi import TrendsAGIClient
# Initialize the Context Layer
trends_client = TrendsAGIClient(api_key="YOUR_KEY")
@tool
def check_market_signals(sector: str) -> str:
"""
Useful for when you need to know what is currently trending or
popular in a specific market sector. Returns real-time data.
"""
try:
response = trends_client.get_trends(category=sector, limit=5)
return str([t.name for t in response.trends])
except Exception:
return "Data unavailable."
# The LLM now has a "sense" of the market.
# agent_chain = initialize_agent(tools=[check_market_signals], ...)
Manage Knowledge
Your agents need memory. Instead of stuffing every prompt with generic context, use the Context Intelligence Suite to create structured knowledge bases. Upload product reference guides, PDF specs, or style guides, and let our API handle the retrieval.
Use Case: The 'Support Bot' Agent
Create a dedicated knowledge base for your customer support agent. Upload your latest policy documents so the agent always answers with the most up-to-date information.
# 1. Create a dedicated knowledge base
project = client.create_context_project(name="Support Bot Knowledge")
# 2. Upload the official policy document (PDF/Text/Image)
client.upload_context_file(
project_id=project.id,
file_path="./refund_policy_2025.pdf",
item_type="reference_doc"
)
# 3. Agent Runtime: Retrieve context relevant to user query
user_query = "Can I get a refund after 30 days?"
relevant_items = client.query_context(
project_id=project.id,
search=user_query
)
# 4. Inject into LLM
context_block = "
".join([item.content for item in relevant_items])
# response = agent.predict(f"Context: {context_block}
Question: {user_query}")Webhooks Reactor
The Webhooks Reactor is a universal integration layer. If a platform can receive a POST request, it can be integrated with TrendsAGI. This allows you to trigger workflows, serverless functions, or chat notifications instantly when a trend is detected.
Universal Compatibility
We send a standardized JSON payload to your configured URL. This makes our service compatible with virtually any modern stack or SaaS tool.
Supported Platforms (Extensive List)
Since we use standard Webhooks, you can integrate with:
- Serverless: AWS Lambda, Google Cloud Functions, Azure Functions, Vercel, Netlify, Cloudflare Workers
- Automation: n8n, IFTTT, Tray.io, and custom webhook orchestrators
- Communication: Slack, Discord, Microsoft Teams, Telegram, WhatsApp Business API, Twilio, SendGrid
- DevOps: GitHub, GitLab, Bitbucket, PagerDuty, Datadog, New Relic, Splunk, Jira, Linear
- E-commerce: Shopify, WooCommerce, Magento, BigCommerce, Stripe, PayPal, Square
- CRM/Sales: Salesforce, HubSpot, Zoho, Pipedrive, Zendesk, Intercom
- Data/Productivity: Google Sheets, Airtable, Notion, Trello, Asana, Monday.com, ClickUp
- CMS: WordPress, Webflow, Contentful, Strapi, Ghost, Drupal
- Infrastructure: Heroku, DigitalOcean, Render, Railway, Fly.io, Supabase, Firebase
Example: Cloud Function Reactor
Trigger a Google Cloud Function to run a complex sentiment analysis job whenever a new trend hits a velocity threshold.
exports.trendsReactor = async (req, res) => {
// 1. Verify Signature (Security)
const signature = req.headers['x-webhook-signature'];
if (!verifySignature(req.body, signature)) {
return res.status(401).send('Unauthorized');
}
// 2. Parse Payload
const { trend_name, velocity, sentiment } = req.body;
// 3. Execute Business Logic
console.log(`Reacting to trend: ${trend_name} (Velocity: ${velocity})`);
await triggerMarketingCampaign(trend_name);
res.status(200).send('Reactor Executed');
};Real-Time Event Triggers
The Nervous System for Agents. For high-frequency bots, polling REST APIs is too slow. Our WebSocket API pushes data to your agent the moment it is detected, allowing for sub-second reaction times.
Plan Limits
Real-time event streams are available on all plans, with throughput and concurrent stream limits scaling by tier (Scale includes priority throughput).
Stream 1: Industry Events (/ws/industry-live)
Your agent receives a push payload immediately when a Regulatory Update is released or an Economic Indicator is published.
import asyncio
import websockets
import json
URI = f"wss://api.trendsagi.com/ws/industry-live?token={API_KEY}"
async def run_agent_listener():
async with websockets.connect(URI) as websocket:
print("--> Agent Connected to Nervous System")
while True:
message = await websocket.recv()
data = json.loads(message)
# Immediate Reaction
if data['type'] == 'new_market_event' and data['payload']['impact'] == 'High':
await trigger_response_protocol(data['payload'])
# asyncio.run(run_agent_listener())Stream 2: Trend Velocity (/ws/trends-live)
Wake up your creative agents the moment a topic goes viral. Filter by specific keywords to create specialized "Watchdog" agents.
wss://api.trendsagi.com/ws/trends-live?token=KEY&trends=AI,TechnologyModel Training Data
Long-Term Memory & Model Training. Offload our daily data dumps into your data lake to build historical datasets. This data is crucial for fine-tuning your own models (LoRA/QLoRA) to understand market dynamics specific to your industry.
Data Pipeline Integration
- Configure your S3/GCS bucket in the Export Dashboard.
- We push
.parquetor.csvfiles daily. - Ingest these files into your vector database (e.g., Pinecone, Milvus) to expand your agent's long-term memory.
Full API Reference
This guide focused on Agent Architecture and use cases. For the raw technical specifications, endpoint schemas, and parameter definitions, consult the API Reference.
Technical Specs
The API Reference contains the Swagger/OpenAPI specifications needed for generating client libraries or integrating with strict-schema tools.
Social & Search Integrations
Deploy Social + Search Ops Agents that detect emerging narratives and convert them into ranked, actionable content and response plans. The new integration tab in API docs centralizes playbooks for X, Reddit, YouTube, and Google search workflows.
Use Case 1: Social Narrative Watchtower
get_trendswith category filters every 15-30 minutes.get_ai_insightsto extract sentiment and key themes.get_crisis_events(status=\"active\").Use Case 2: Search Opportunity Ranking
Build a queue of SEO opportunities by combining
recommendationsandsearch_insights, then cross-check against your search analytics data in your own runtime.