搜索接地意味着让您的人工智能代理能够访问实时网络结果,以便它可以回答有关当前事件、价格和最近变化的问题,而不会产生幻觉。您不需要 LangChain、LlamaIndex 或任何框架——调用搜索 API 并将结果注入提示中的简单 Python 函数也可以。本教程仅使用 requests 库和 Scavio API,让初学者在 15 分钟内从零开始成为一名熟练的代理,每次搜索只需 0.005 美元。
前置条件
- 已安装 Python 3.8+
- 安装请求库(pip install requests)
- 来自 scavio.dev 的 Scavio API 密钥(每月 250 个免费积分)
- 任何 LLM API 密钥(OpenAI、Anthropic 等)或本地模型
操作指南
步骤 1: 获取您的 API 密钥并进行测试
在 scavio.dev 上注册并复制您的 API 密钥。使用简单的curl命令或Python脚本对其进行测试以确保其有效。
import requests, os
API_KEY = os.environ.get('SCAVIO_API_KEY', 'your_key_here')
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': 'hello world', 'country_code': 'us'})
if resp.status_code == 200:
results = resp.json().get('organic_results', [])
print(f'API works. Got {len(results)} results.')
else:
print(f'Error: {resp.status_code} - {resp.text}')步骤 2: 编写搜索函数
创建一个接受问题并返回格式化搜索结果的函数。这是接地系统的核心——只有 10 行代码。
def search_web(question: str) -> str:
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': question, 'country_code': 'us'})
if resp.status_code != 200:
return 'Search failed. Answer from your own knowledge.'
results = resp.json().get('organic_results', [])[:5]
if not results:
return 'No results found.'
return '\n'.join(
f'{r["title"]}\n{r.get("snippet", "")}\nSource: {r["link"]}\n'
for r in results
)步骤 3: 建立接地提示
将搜索结果与提示模板中的用户问题结合起来。告诉法学硕士使用搜索结果并引用来源。
def make_prompt(question: str) -> str:
search_results = search_web(question)
return f"""Answer the following question using ONLY the search results below.
If the results do not contain enough info, say so.
Cite your sources with URLs.
Search Results:
{search_results}
Question: {question}
Answer:"""
# Test it:
prompt = make_prompt('What is the cheapest CRM in 2026?')
print(prompt)步骤 4: 连接到您的法学硕士
将接地提示传递给任何法学硕士。此示例使用 OpenAI,但与 Anthropic、本地 Ollama 或任何聊天 API 的工作方式相同。
from openai import OpenAI
client = OpenAI() # uses OPENAI_API_KEY env var
def ask(question: str) -> str:
prompt = make_prompt(question)
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': prompt}],
max_tokens=500
)
return response.choices[0].message.content
# Your first grounded query:
answer = ask('What is the cheapest CRM in 2026?')
print(answer)步骤 5: 添加对话循环
将一次性查询转变为对话代理。每条用户消息都以新鲜的搜索结果为基础。
def chat_loop():
print('Grounded Agent (type "quit" to exit)')
print(f'Search cost: $0.005 per question\n')
while True:
question = input('You: ').strip()
if question.lower() in ('quit', 'exit', 'q'):
break
if not question:
continue
answer = ask(question)
print(f'\nAgent: {answer}\n')
if __name__ == '__main__':
chat_loop()Python 示例
import os, requests
from openai import OpenAI
API_KEY = os.environ['SCAVIO_API_KEY']
client = OpenAI()
def search_web(question: str) -> str:
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': question, 'country_code': 'us'})
results = resp.json().get('organic_results', [])[:5]
return '\n'.join(f'{r["title"]}\n{r.get("snippet", "")}\nSource: {r["link"]}' for r in results)
def ask(question: str) -> str:
ctx = search_web(question)
prompt = f'Use these search results to answer:\n\n{ctx}\n\nQuestion: {question}'
resp = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': prompt}],
max_tokens=500)
return resp.choices[0].message.content
if __name__ == '__main__':
print(ask('Best free CRM 2026'))JavaScript 示例
const API_KEY = process.env.SCAVIO_API_KEY;
async function searchWeb(question) {
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: question, country_code: 'us' })
});
const data = await resp.json();
return (data.organic_results || []).slice(0, 5)
.map(r => `${r.title}\n${r.snippet || ''}\nSource: ${r.link}`).join('\n\n');
}
async function main() {
const question = 'Best free CRM 2026';
const context = await searchWeb(question);
console.log(`Search context (cost: $0.005):\n${context}`);
// Pass context + question to your LLM of choice
}
main().catch(console.error);预期输出
API works. Got 10 results.
Grounded Agent (type "quit" to exit)
Search cost: $0.005 per question
You: What is the cheapest CRM in 2026?
Agent: Based on search results, HubSpot CRM remains the most popular
free option in 2026 with unlimited users. For paid plans, Freshsales
starts at $9/user/month. Zoho CRM offers a free tier for up to 3 users.
Source: https://www.hubspot.com/pricing
Source: https://www.freshworks.com/crm/pricing/