没有搜索访问权限的人工智能代理会产生过时信息的幻觉。添加搜索工具只需不到 10 分钟,即可让您的代理实时访问网络。这个适合初学者的教程逐步介绍了获取 API 密钥、进行首次搜索调用以及将搜索集成到基本代理循环中。 Scavio 每月提供 250 次免费搜索,因此您无需花费任何费用即可构建和测试。
前置条件
- 安装了 Python 3.9+ 或 Node.js 18+
- 来自 scavio.dev 的免费 Scavio API 密钥
- 10分钟时间
操作指南
步骤 1: 获取您的 API 密钥并进行首次搜索
在 scavio.dev 上注册以获得免费 API 密钥(包括每月 250 次搜索)。然后进行第一次搜索呼叫。
Python
import requests, os
# Set your API key as an environment variable:
# export SCAVIO_API_KEY=your-key-here
API_KEY = os.environ['SCAVIO_API_KEY']
# Your first search
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={
'x-api-key': API_KEY,
'Content-Type': 'application/json'
},
json={
'query': 'what is an AI agent',
'country_code': 'us',
'num_results': 5
})
results = resp.json().get('organic_results', [])
print(f'Search returned {len(results)} results:\n')
for r in results:
print(f' {r["title"]}')
print(f' {r["link"]}')
print(f' {r.get("snippet", "")[:100]}...')
print()步骤 2: 将其包装在可重用的搜索功能中
创建一个可以在整个项目中使用的干净搜索功能。这是您的代理将调用的函数。
Python
def search(query: str, count: int = 5) -> list:
"""Search the web and return structured results."""
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': query, 'country_code': 'us', 'num_results': count})
if resp.status_code != 200:
print(f'Search error: {resp.status_code}')
return []
results = resp.json().get('organic_results', [])
return [{
'title': r['title'],
'url': r['link'],
'snippet': r.get('snippet', '')
} for r in results]
# Test it
results = search('best python libraries 2026')
for r in results:
print(f'{r["title"]}: {r["url"]}')
print(f'\nCost: $0.005 per search, {250} free/month')步骤 3: 通过搜索构建简单的代理循环
创建一个基本代理来决定何时进行搜索并使用结果来回答问题。这是任何搜索增强代理的基础。
Python
def simple_agent(question: str) -> str:
"""A basic agent that searches before answering."""
print(f'Question: {question}')
# Step 1: Search for relevant information
results = search(question, count=3)
if not results:
return 'I could not find any search results for that question.'
# Step 2: Build context from search results
context = '\n'.join(
f'- {r["title"]}: {r["snippet"][:150]}'
for r in results
)
# Step 3: Format the answer (in a real agent, send to LLM)
answer = f'Based on {len(results)} search results:\n\n{context}'
answer += f'\n\nSources:\n'
for r in results:
answer += f' - {r["url"]}\n'
return answer
# Ask the agent a question
answer = simple_agent('What are the best Python web frameworks in 2026?')
print(answer)
print(f'\nTotal cost: $0.005 (1 search query)')Python 示例
Python
import requests, os
API_KEY = os.environ['SCAVIO_API_KEY']
def search(query, count=5):
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': query, 'country_code': 'us', 'num_results': count})
return [{'title': r['title'], 'url': r['link'], 'snippet': r.get('snippet', '')}
for r in resp.json().get('organic_results', [])]
results = search('what is an AI agent')
for r in results:
print(f'{r["title"]}: {r["url"]}')
print(f'\nFree tier: 250 searches/month')JavaScript 示例
JavaScript
const API_KEY = process.env.SCAVIO_API_KEY;
async function search(query, count = 5) {
const resp = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST',
headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ query, country_code: 'us', num_results: count })
});
const data = await resp.json();
return (data.organic_results || []).map(r => ({
title: r.title, url: r.link, snippet: r.snippet || ''
}));
}
search('what is an AI agent').then(results => {
results.forEach(r => console.log(`${r.title}: ${r.url}`));
console.log(`\nFree tier: 250 searches/month`);
});预期输出
JSON
Search returned 5 results:
What Is an AI Agent? - IBM
https://www.ibm.com/topics/ai-agents
An AI agent is a software program that can interact with its environment...
AI Agents Explained - Microsoft
https://learn.microsoft.com/en-us/ai/agents
AI agents are autonomous systems that perceive, decide, and act...
Based on 3 search results:
- What Is an AI Agent? - IBM: An AI agent is a software program...
- AI Agents Explained - Microsoft: AI agents are autonomous systems...
Total cost: $0.005 (1 search query)
Free tier: 250 searches/month