← Back to Blog
Tavily 集成到 LangGraph 工作流示例
概述
本文档展示了如何在现有的 LangGraph 金融代理工作流中使用 Tavily 网络搜索功能,而无需添加额外的节点。Tavily 搜索已经智能地集成到现有节点中,并支持主题特定的搜索。
支持的搜索主题
Tavily API 支持两种主要的搜索主题:
general
- 广泛主题,包括金融市场、股票、收益、经济数据、AI、金融科技、区块链、ESG投资、可持续发展和一般商业内容news
- 时事新闻、突发新闻、政策变化、监管更新、最新公告和时间敏感信息
注意: 虽然 Tavily 文档提到其他主题,但 API 目前只接受 "general"
和 "news"
作为有效的主题值。
集成方式
1. Context Analysis Node (上下文分析节点)
自动触发条件:
- 查询包含实时关键词:
latest
,current
,today
,recent
,price
,market
等 - 意图类别需要实时数据:
market_analysis
,portfolio_analysis
,risk_control
,pricing_automation
示例查询:
// 这些查询会自动触发 Tavily 搜索
"分析当前市场状况"
"最新的苹果股价分析"
"今天的标普500指数表现"
"最近的美联储利率决定"
搜索结果集成:
// 在 context.marketContext 中会包含:
{
currentDate: "2024-12-19",
marketConditions: "volatile",
interestRateEnvironment: "rising",
economicIndicators: { ... },
realTimeData: {
searchQuery: "分析当前市场状况 market analysis trends 2024",
directAnswer: "当前市场呈现波动性上升趋势...",
sources: [
{
title: "Market Analysis Today",
url: "https://bloomberg.com/...",
snippet: "Markets showed increased volatility..."
}
],
timestamp: "2024-12-19T10:30:00Z"
},
dataSource: "tavily_search",
lastUpdated: "2024-12-19T10:30:00Z"
}
2. Agent Execution Node (代理执行节点)
Market Agent 增强:
- 自动获取实时市场数据
- 搜索当前股市指数、经济指标
- 集成权威金融新闻源
Research Agent 增强:
- 基于执行计划描述进行深度研究
- 搜索相关金融分析报告
- 获取最新行业趋势
使用示例
示例 1:市场分析查询
// 用户查询
const userQuery = "分析当前科技股市场趋势和苹果公司最新财报影响";
// 工作流执行过程:
// 1. Intent Analysis: 识别为 market_analysis
// 2. Context Analysis: 检测到 "当前"、"最新" 关键词,触发 Tavily 搜索
// 搜索查询: "科技股市场趋势苹果公司财报 market analysis trends 2024"
// 3. Routing Decision: 选择复杂分析流程
// 4. Execution Plan: 包含 market_agent 和 research_agent
// 5. Agent Execution:
// - market_agent 获取实时市场数据
// - research_agent 搜索苹果财报分析
// 6. Report Generation: 整合所有数据生成报告
示例 2:投资组合风险评估
// 用户查询
const userQuery = "评估我的投资组合在当前市场环境下的风险";
// 工作流执行过程:
// 1. Intent Analysis: 识别为 portfolio_analysis + risk_control
// 2. Context Analysis: 检测到 "当前市场环境",触发搜索
// 搜索查询: "投资组合风险当前市场环境 portfolio market conditions investment 2024"
// 3. Agent Execution:
// - portfolio_agent: 分析组合配置
// - risk_agent: 计算风险指标
// - market_agent: 获取当前市场风险因子
配置和启用
1. 环境变量设置
# .env.local
TAVILY_API_KEY="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"
COMPOSIO_API_KEY="your-composio-api-key"
2. 工具配置
// 在你的工具配置中启用 Tavily
import { ToolConfig } from '@/lib/tools/composio-config';
const toolConfig: ToolConfig = {
enabled: true,
apps: ['tavily'], // 添加 tavily 到应用列表
maxToolRoundtrips: 3,
useSmartToolSelection: true
};
3. 工作流使用
// 使用现有的工作流,无需修改
import { financialOrchestrationGraph } from '@/lib/agents/financial-orchestration-workflow';
// 执行工作流
const result = await financialOrchestrationGraph.invoke({
messages: [],
userQuery: "分析最新市场趋势",
userId: "user-123"
});
// 检查是否使用了网络搜索
if (result.context?.marketContext?.dataSource === 'tavily_search') {
console.log('使用了实时市场数据');
console.log('搜索结果:', result.context.marketContext.realTimeData);
}
搜索触发逻辑
Context Analysis Node 触发条件
// 实时关键词
const realTimeKeywords = [
'latest', 'current', 'today', 'recent', 'now', 'update',
'price', 'market', 'news', 'earnings', 'fed', 'rate',
'inflation', 'gdp', 'unemployment', 'stock', 'index'
];
// 需要实时数据的意图类别
const realTimeCategories = [
'market_analysis',
'portfolio_analysis',
'risk_control',
'pricing_automation'
];
Agent Execution Node 触发条件
// Market Agent: 总是尝试获取实时市场数据
// Research Agent: 基于执行步骤描述进行搜索
搜索域名配置
金融数据源
const financialDomains = [
"bloomberg.com", // 彭博财经
"reuters.com", // 路透社
"marketwatch.com", // 市场观察
"yahoo.com", // 雅虎财经
"cnbc.com", // CNBC
"wsj.com", // 华尔街日报
"ft.com", // 金融时报
"sec.gov", // 美国证监会
"federalreserve.gov" // 美联储
];
监控和调试
1. 日志监控
// 在节点执行过程中查看日志
console.log('📊 Context Analysis Node - Starting');
console.log('🔍 Fetching real-time market data using Tavily');
console.log('✅ Tavily search completed: Found 5 results');
2. LangGraph Studio 可视化
# 启动 LangGraph Studio
npx @langchain/langgraph-cli dev
# 访问 Studio UI
# https://smith.langchain.com/studio?baseUrl=http://localhost:2024
3. 状态检查
// 检查工作流状态中的搜索结果
const state = await graph.getState();
console.log('Web search performed:', state.webSearchPerformed);
console.log('Search results:', state.webSearchResults);
性能优化
1. 缓存策略
// 实现搜索结果缓存(5分钟)
const searchCache = new Map();
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
function getCachedResult(query: string) {
const cached = searchCache.get(query);
if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
return cached.result;
}
return null;
}
2. 并行搜索
// 在 Agent Execution 中并行执行多个搜索
const [marketData, researchData] = await Promise.all([
fetchMarketData(),
fetchResearchData(description)
]);
错误处理
1. 优雅降级
try {
const marketData = await fetchRealTimeMarketData(userQuery, intent);
// 使用实时数据
} catch (error) {
console.log(`Failed to fetch real-time data: ${error}`);
// 使用基础数据继续执行
}
2. 超时处理
// 设置搜索超时
const searchWithTimeout = Promise.race([
searchTool.callback(params),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Search timeout')), 10000)
)
]);
最佳实践
- 智能触发:只在需要实时数据时触发搜索
- 域名过滤:使用可信的金融数据源
- 错误处理:始终提供降级方案
- 缓存策略:避免重复搜索相同内容
- 日志记录:记录搜索活动以便调试
通过这种集成方式,你的 LangGraph 金融代理系统现在具备了强大的实时网络搜索能力,能够自动获取最新的市场数据和金融信息,而无需修改现有的工作流结构。
支持的主题
Tavily 支持以下主题进行特定领域的搜索:
finance
- 金融市场、股票、收益、经济数据news
- 当前事件、政策变化、监管更新technology
- AI、金融科技、区块链、数字创新science
- 研究、分析、定量方法health
- ESG投资、可持续性、环境因素politics
- 政府政策、选举、监管变化general
- 广泛主题、客户服务、一般业务sports
- 体育业务、娱乐行业entertainment
- 媒体、娱乐行业分析
主题选择策略
系统智能选择主题基于:
-
意图类别映射:
market_analysis
→finance
portfolio_analysis
→finance
kyc_research
→general
compliance_check
→finance
-
查询关键词分析:
- AI/金融科技关键词 →
technology
- Fed/政策关键词 →
news
- ESG/可持续性 →
health
- 政府/政治 →
politics
- AI/金融科技关键词 →
集成点
1. Context Analysis Node
Context Analysis Node 自动检测何时需要实时数据并执行主题特定的搜索:
// Automatic topic selection based on intent
const topic = this.getSearchTopic(intent);
const searchResult = await searchTool.callback({
query: searchQuery,
topic: topic, // Dynamically selected
searchDepth: "basic",
includeImages: false,
includeAnswer: true,
maxResults: 5,
includeDomains: [
"bloomberg.com",
"reuters.com",
"marketwatch.com"
]
});
触发条件:包含关键词如:
latest
,current
,today
,recent
price
,market
,earnings
news
,update
,announcement
2. Agent Execution Node
不同代理使用不同的主题进行专业搜索:
Market Agent (Finance Topic)
const searchResult = await searchTool.callback({
query: "stock market today S&P 500 Dow Jones financial markets",
topic: "finance",
searchDepth: "basic",
includeImages: false,
includeAnswer: true,
maxResults: 5,
includeDomains: [
"bloomberg.com",
"reuters.com",
"marketwatch.com",
"yahoo.com",
"cnbc.com"
]
});
Research Agent (Multiple Topics)
// Technology research
const techResult = await searchTool.callback({
query: "artificial intelligence fintech applications 2024",
topic: "technology",
searchDepth: "advanced",
includeImages: false,
includeAnswer: true,
maxResults: 8
});
// Financial research
const financeResult = await searchTool.callback({
query: searchQuery,
topic: "finance",
searchDepth: "advanced",
includeImages: false,
includeAnswer: true,
maxResults: 8,
includeDomains: [
"bloomberg.com",
"reuters.com",
"ft.com",
"wsj.com",
"sec.gov"
]
});
工作流示例
示例 1:市场分析查询
用户查询:"What's the latest on Tesla's stock performance today?"
工作流:
- 意图分析:分类为
market_analysis
- 上下文分析:
- 检测到 "latest" 和 "today" 关键词
- 选择
finance
主题 - 触发实时搜索
- 搜索执行:
{ query: "Tesla stock performance latest news earnings", topic: "finance", searchDepth: "basic", includeDomains: ["bloomberg.com", "reuters.com", "marketwatch.com"] }
- 结果集成:实时数据与基础分析合并
示例 2:技术研究
用户查询:"How is AI being used in fintech applications?"
工作流:
- 意图分析:分类为
research_agent
- 上下文分析:
- 检测到 "AI" 和 "fintech" 关键词
- 选择
technology
主题
- 搜索执行:
{ query: "artificial intelligence fintech applications 2024", topic: "technology", searchDepth: "advanced", maxResults: 8 }
示例 3:ESG投资研究
用户查询:"What are the latest ESG investing trends?"
工作流:
- 意图分析:分类为
research_agent
- 上下文分析:
- 检测到 "ESG" 和 "investing" 关键词
- 选择
health
主题(为可持续性聚焦)
- 搜索执行:
{ query: "ESG investing trends sustainable finance 2024", topic: "health", searchDepth: "advanced", includeDomains: ["sustainalytics.com", "msci.com"] }
示例 4:监管新闻
用户查询:"What's the latest Federal Reserve policy update?"
工作流:
- 意图分析:分类为
market_analysis
- 上下文分析:
- 检测到 "Federal Reserve" 和 "policy" 关键词
- 选择
news
主题
- 搜索执行:
{ query: "Federal Reserve policy update interest rates 2024", topic: "news", searchDepth: "basic", includeDomains: ["federalreserve.gov", "reuters.com", "bloomberg.com"] }
主题使用模式
金融市场 (finance
)
- 最佳用途:股票价格、收益、市场分析、财务数据
- 域名:bloomberg.com, reuters.com, marketwatch.com, yahoo.com
- 搜索深度:通常为
basic
用于实时数据
当前事件 (news
)
- 最佳用途:政策变化、监管更新、突发新闻
- 域名:reuters.com, ft.com, wsj.com, federalreserve.gov
- 搜索深度:
basic
用于最近新闻,advanced
用于分析
技术 (technology
)
- 最佳用途:AI、金融科技、区块链、数字创新
- 域名:techcrunch.com, wired.com, arstechnica.com
- 搜索深度:通常为
advanced
用于全面研究
可持续性 (health
)
- 最佳用途:ESG投资、环境因素、可持续性
- 域名:sustainalytics.com, msci.com, 环境站点
- 搜索深度:
advanced
用于详细分析
高级用法
自定义主题选择
您可以覆盖自动主题选择:
import { performIntelligentSearch } from '../lib/tools/tavily-example';
const result = await performIntelligentSearch(
"blockchain adoption in banking",
"market_analysis", // Intent category
{
searchDepth: "advanced",
maxResults: 10,
includeDomains: ["coindesk.com", "bloomberg.com"]
}
);
// Result includes selected topic and reasoning
console.log(result.selectedTopic); // "technology"
console.log(result.searchMetadata.topicReasoning);
主题特定工作流
import { TOPIC_USAGE_PATTERNS } from '../lib/tools/tavily-example';
// Use predefined patterns
const pattern = TOPIC_USAGE_PATTERNS.techResearch;
const result = await searchTool.callback({
query: "AI in financial services",
topic: pattern.topic, // "technology"
searchDepth: pattern.searchDepth, // "advanced"
includeDomains: pattern.domains,
maxResults: 8
});
性能考虑
-
主题选择影响:
finance
主题返回更多财务聚焦结果technology
主题更适合创新研究news
主题优先考虑最近发展
-
主题搜索深度:
- Finance:
basic
for prices,advanced
for analysis - Technology: Usually
advanced
for comprehensive coverage - News:
basic
for breaking news,advanced
for context
- Finance:
-
域名过滤:
- Combine topic selection with domain filtering for best results
- Financial topics work well with financial domain restrictions
- Technology topics benefit from tech-focused domains
错误处理
系统优雅处理主题相关错误:
try {
const result = await searchTool.callback({
query: "market analysis",
topic: "finance",
// ... other parameters
});
if (result.success) {
// Use search results
} else {
// Fallback to base analysis
}
} catch (error) {
// Log error and continue with fallback
console.log(`Search failed: ${error.message}`);
}
测试主题功能
运行增强测试套件:
npm run test:tavily
测试包括主题特定搜索:
- Finance topic with market data
- Technology topic with AI/fintech queries
- News topic with policy updates
- Health topic with ESG research
- General topic with business queries
最佳实践
- 让系统自动选择主题 基于意图和关键词
- 使用 finance topic 用于市场数据和财务分析
- 使用 technology topic 用于创新和金融科技研究
- 使用 news topic 用于政策和监管更新
- 使用 health topic 用于ESG和可持续性研究
- Combine topics with domain filtering 用于最佳结果
- Monitor search quality 并根据需要调整主题选择
主题参数显著提高了搜索相关性和帮助金融代理系统向用户提供更多准确、特定领域的信息。