This article demonstrates a real-world implementation of Tavily search integration in an AI agent system. The code examples are taken from actual production code in the open-source Wei AI Agent project.
cover image. made by https://www.linkedin.com/in/abdibrokhim/
Integrating @tavilyai with Function Calling in AI Agentic Apps 🧵
Taking a closer look at this open-source project: https://github.com/Anora-Labs/eliza-agent-orchestration.
official website: https://www.tavily.com/
🚀 Building AI agents that can search the web in real-time? Here’s how I integrated @TavilyAI with function calling to give my AI agents instant access to current information.
The result? Agents that can answer questions about today’s news, current events, and live data! 🧵👇
official website: https://www.tavily.com/
🤔 The Problem: Most AI models are trained on data with a cutoff date. They can’t tell you about breaking news, current stock prices, or what happened yesterday.
Solution: Function calling + Tavily’s real-time search API = AI agents with up-to-the-minute knowledge! ⚡
official website: https://www.tavily.com/
🛠️ Setting up Tavily is surprisingly simple. First, install and configure:
npm i @tavily/core
Add your Tavily API key to .env
TAVILY_API_KEY=your_key_here_goes_here
That’s it for dependencies! No complex SDKs or heavy libraries needed. 📦
💡 The magic happens with function definitions. Here’s how I defined Tavily search functions for my AI agents:
{
  name: "searchWeb",
  description: "Search the internet for real-time information",
  parameters: {
    type: "object",
    properties: {
      query: { type: "string" },
      topic: { enum: ["general", "news"] },
      max_results: { type: "number" }
    }
  }
}
🔧 The Tavily service class is clean and modular:
export class TavilyService {
  async search(options: TavilySearchOptions) {
    const response = await fetch('https://api.tavily.com/search', {
      method: 'POST',
      headers: {
        'Authorization': Bearer ${this.apiKey},
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(searchPayload)
    });
    return response.json();
  }
}
🎯 Function calling integration is where it gets interesting. When the AI decides it needs current information, it automatically calls the search function:
case "searchWeb":
  const searchResponse = await tavilyService.search({
    query: args.query,
    topic: args.topic || 'general',
    max_results: args.max_results || 5
  });
  return JSON.stringify(searchResponse);
📈 The AI agent conversation flow:
User asks: “What’s happening with Bitcoin today?”
AI recognizes it needs current data
AI calls
searchWeb(“Bitcoin price news today”)Tavily returns real-time results
AI synthesizes the information into a natural response
All automatic! 🤯
🗞️ Specialized functions for different use cases:
// General web search
await tavilyService.searchGeneral(query, maxResults)
// Current news
await tavilyService.searchNews(query, maxResults, 'day')
// Quick answers
await tavilyService.getQuickAnswer(query)
Each optimized for different types of information retrieval! 📊
⚡ Pro tip: Format the results for better AI consumption:
formatSearchResults(searchResponse: TavilySearchResponse): string {
  let formatted = Search Query: "${query}"\n\n;
  if (answer) formatted += Answer: ${answer}\n\n;
results.forEach((result, index) => {
    formatted += ${index + 1}. ${result.title}\n;
    formatted += Content: ${result.content}\n\n;
  });
return formatted;
}
🎛️ Error handling is crucial for production:
try {
  const searchResponse = await tavilyService.search(options);
  return JSON.stringify({ success: true, ...searchResponse });
} catch (error) {
  return JSON.stringify({
    error: "Failed to search the web",
    message: error.message
  });
}
Always graceful degradation! 🛡️
📊 Real-world example from my Wei AI agent:
User: “What are the latest developments in AI safety?”
AI Agent:
Calls
searchNews(“AI safety developments”, 5, “week”)Gets 5 recent articles from Tavily
Synthesizes findings into comprehensive answer
Cites sources with URLs
try Wei at https://wei.yaps.gg
🎮 Advanced features I’m using:
Domain filtering: Include/exclude specific sites
Time range controls: Last day, week, month
Content depth: Basic vs advanced search
Answer extraction: Get direct answers, not just links
Multiple topics: General web vs news-specific
official website: https://www.tavily.com/
🚀 Performance benefits:
⚡ Sub-second response times
🎯 Highly relevant results (scored by relevance)
📱 Works great with streaming responses
💰 Cost-effective vs other search APIs
🌍 Global coverage with localization
official website: https://www.tavily.com/
🎯 Key takeaways:
Function calling makes AI agents incredibly extensible
Tavily’s API is developer-friendly and fast
Real-time search transforms user experience
Simple integration, powerful results
Essential for any serious AI application
Try it yourself! 🚀
Technical Implementation Details
Complete Function Definition:
const searchFunctions = [
  {
    name: "searchWeb",
    description: "Search the internet for real-time information and current events",
    parameters: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description: "The search query to find information on the web"
        },
        topic: {
          type: "string",
          enum: ["general", "news"],
          description: "The type of search - 'general' for broad searches, 'news' for current events"
        },
        max_results: {
          type: "number",
          description: "Maximum number of search results to return (1-20, default: 5)"
        },
        time_range: {
          type: "string",
          enum: ["day", "week", "month", "year"],
          description: "Time range for news searches"
        },
        include_answer: {
          type: "boolean",
          description: "Whether to include an AI-generated answer summary"
        }
      },
      required: ["query"]
    }
  }
];
Error Handling Best Practices:
async function handleSearchFunction(args: any) {
  try {
    // Validate inputs
    if (!args.query || typeof args.query !== 'string') {
      throw new Error('Query parameter is required and must be a string');
    }
// Call Tavily with validated parameters
const searchResponse = await tavilyService.search({
  query: args.query,
  topic: args.topic || 'general',
  max_results: Math.min(Math.max(args.max_results || 5, 1), 20),
  time_range: args.time_range,
  include_answer: args.include_answer !== false,
});
// Track usage for analytics
await trackSearchOperation(userId, 'web', args.query, searchResponse.results.length);
return {
  success: true,
  ...searchResponse,
  formatted_results: tavilyService.formatSearchResults(searchResponse)
};
} catch (error) {
    console.error('Search function error:', error);
    return {
      error: "Failed to search the web",
      success: false,
      message: error instanceof Error ? error.message : "Unknown search error"
    };
  }
}
Usage Analytics Integration:
// Track search operations for insights
await keywordsAIService.trackSearchOperation(
  userId,
  'web', // search type
  args.query,
  searchResponse.results.length
);
Give a star: https://github.com/Anora-Labs/eliza-agent-orchestration.
my linkedin in case: https://www.linkedin.com/in/abdibrokhim/
              
    
Top comments (0)