搜索接地使人工智能代理能够访问实时网络数据,这样他们就不会产生过时事实的幻觉。该模式适用于任何 Python 代理框架:在 LLM 生成答案之前,查询搜索 API 以获得相关结果并将其注入提示上下文中。本教程展示了一种使用 Scavio API 的与框架无关的方法,无论您使用 OpenAI、Anthropic、LangChain 还是裸 Python 循环,该方法都适用。按每次搜索 0.005 美元计算,搁置每轮客服增加的成本不到一分钱。
前置条件
- 已安装 Python 3.9+
- 请求已安装库
- 来自 scavio.dev 的 Scavio API 密钥
- 任何 LLM API 密钥(OpenAI、Anthropic 等)
操作指南
步骤 1: 创建搜索基础功能
构建一个可重用的函数,该函数接受查询并返回格式化的上下文。此功能成为您的代理和实时网络数据之间的桥梁。
import requests, os
API_KEY = os.environ['SCAVIO_API_KEY']
def ground_with_search(query: str, max_results: int = 5) -> str:
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'})
resp.raise_for_status()
results = resp.json().get('organic_results', [])[:max_results]
context = '\n'.join(
f'[{r["position"]}] {r["title"]}\n {r.get("snippet", "")}\n Source: {r["link"]}'
for r in results
)
return f'Search results for: {query}\n\n{context}'步骤 2: 将接地注入任何提示模板
用搜索上下文包装现有的提示。基础数据位于用户问题之前,以便法学硕士可以参考它。
def build_grounded_prompt(user_question: str) -> str:
search_context = ground_with_search(user_question)
return f"""Use the following search results to answer accurately.
Do not make up information not present in the results.
{search_context}
Question: {user_question}
Answer:"""
prompt = build_grounded_prompt('What is the latest Python version in 2026?')
print(prompt[:500])步骤 3: 直接与 OpenAI / Anthropic 一起使用
将接地提示传递给任何 LLM API。此示例显示了 OpenAI 和 Anthropic 模式。
# With OpenAI:
from openai import OpenAI
client = OpenAI()
def ask_grounded_openai(question: str) -> str:
prompt = build_grounded_prompt(question)
response = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': prompt}],
max_tokens=500
)
return response.choices[0].message.content
# With Anthropic:
import anthropic
client_a = anthropic.Anthropic()
def ask_grounded_anthropic(question: str) -> str:
prompt = build_grounded_prompt(question)
msg = client_a.messages.create(
model='claude-sonnet-4-20250514',
max_tokens=500,
messages=[{'role': 'user', 'content': prompt}]
)
return msg.content[0].text步骤 4: 用作 LangChain 工具
如果您使用LangChain,请将搜索功能包装为一个工具,以便代理在需要当前数据时可以自主调用它。
from langchain.tools import tool
@tool
def web_search(query: str) -> str:
"""Search the web for current information. Use this when you need
up-to-date facts, prices, or recent events."""
return ground_with_search(query)
# Register with any LangChain agent:
# agent = create_react_agent(llm, tools=[web_search], ...)步骤 5: 添加缓存以减少重复搜索
在多轮对话中,代理可能会搜索同一事物两次。简单的 TTL 缓存可防止重复的 API 调用。
from functools import lru_cache
import hashlib
_cache = {}
def cached_ground(query: str, ttl_seconds: int = 300) -> str:
import time
key = hashlib.md5(query.encode()).hexdigest()
if key in _cache:
result, timestamp = _cache[key]
if time.time() - timestamp < ttl_seconds:
return result
result = ground_with_search(query)
_cache[key] = (result, time.time())
return result
# First call hits API, second returns cached result
ctx1 = cached_ground('python 3.14 release date')
ctx2 = cached_ground('python 3.14 release date') # cached, no API call
print(f'Cache size: {len(_cache)} entries')Python 示例
import os, requests
API_KEY = os.environ['SCAVIO_API_KEY']
def ground_with_search(query: str, max_results: int = 5) -> str:
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'})
resp.raise_for_status()
results = resp.json().get('organic_results', [])[:max_results]
return '\n'.join(
f'[{r["position"]}] {r["title"]}\n {r.get("snippet", "")}\n Source: {r["link"]}'
for r in results
)
def build_grounded_prompt(question: str) -> str:
ctx = ground_with_search(question)
return f'Use these search results to answer accurately:\n\n{ctx}\n\nQuestion: {question}\nAnswer:'
def main():
question = 'What is the latest Python version in 2026?'
prompt = build_grounded_prompt(question)
print(prompt)
print(f'\nGrounding cost: $0.005 per search')
if __name__ == '__main__':
main()JavaScript 示例
const API_KEY = process.env.SCAVIO_API_KEY;
async function groundWithSearch(query, maxResults = 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' })
});
const data = await resp.json();
return (data.organic_results || []).slice(0, maxResults)
.map(r => `[${r.position}] ${r.title}\n ${r.snippet || ''}\n Source: ${r.link}`)
.join('\n');
}
async function main() {
const question = 'What is the latest Python version in 2026?';
const context = await groundWithSearch(question);
const prompt = `Use these results to answer:\n\n${context}\n\nQ: ${question}\nA:`;
console.log(prompt);
console.log('\nGrounding cost: $0.005 per search');
}
main().catch(console.error);预期输出
Search results for: What is the latest Python version in 2026?
[1] Python Release Python 3.14.0
Python 3.14.0 was released on April 15, 2026 with experimental JIT...
Source: https://www.python.org/downloads/release/python-3140/
[2] What's New In Python 3.14
This article explains the new features in Python 3.14...
Source: https://docs.python.org/3/whatsnew/3.14.html
Grounding cost: $0.005 per search