ScavioScavio
产品定价文档
登录开始使用
  1. 首页
  2. 教程
  3. 如何为任何 Python 代理添加搜索基础
教程

如何为任何 Python 代理添加搜索基础

任何 Python AI 代理都可以在 20 行之内使用实时搜索数据。可与 OpenAI、Anthropic、LangChain 或自定义代理配合使用。分步教程。

获取免费API密钥API文档

搜索接地使人工智能代理能够访问实时网络数据,这样他们就不会产生过时事实的幻觉。该模式适用于任何 Python 代理框架:在 LLM 生成答案之前,查询搜索 API 以获得相关结果并将其注入提示上下文中。本教程展示了一种使用 Scavio API 的与框架无关的方法,无论您使用 OpenAI、Anthropic、LangChain 还是裸 Python 循环,该方法都适用。按每次搜索 0.005 美元计算,搁置每轮客服增加的成本不到一分钱。

前置条件

  • 已安装 Python 3.9+
  • 请求已安装库
  • 来自 scavio.dev 的 Scavio API 密钥
  • 任何 LLM API 密钥(OpenAI、Anthropic 等)

操作指南

步骤 1: 创建搜索基础功能

构建一个可重用的函数,该函数接受查询并返回格式化的上下文。此功能成为您的代理和实时网络数据之间的桥梁。

Python
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: 将接地注入任何提示模板

用搜索上下文包装现有的提示。基础数据位于用户问题之前,以便法学硕士可以参考它。

Python
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 模式。

Python
# 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,请将搜索功能包装为一个工具,以便代理在需要当前数据时可以自主调用它。

Python
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 调用。

Python
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 示例

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 示例

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);

预期输出

JSON
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

相关教程

  • 如何构建具有内存和实时搜索的 LangGraph 代理
  • 如何设置初级代理搜索基础
  • 如何通过 SERP 增强来提高 RAG 准确性

常见问题

大多数开发者在15到30分钟内完成本教程。您需要一个Scavio API密钥(免费套餐即可)和可用的Python或JavaScript环境。

已安装 Python 3.9+. 请求已安装库. 来自 scavio.dev 的 Scavio API 密钥. 任何 LLM API 密钥(OpenAI、Anthropic 等). Scavio API密钥注册即送50个免费积分。

可以。免费套餐注册即送50个积分,完全足够完成本教程并构建一个可运行的原型解决方案。

Scavio提供原生LangChain包(langchain-scavio)、MCP服务器以及适用于任何HTTP客户端的REST API。本教程使用 the raw REST API, 但您可以根据需要适配您选择的框架。

相关资源

Best Of

Google I/O 2026 AI模式变化后最佳搜索API

Read more
Glossary

搜索 API 供应商格局(2026)

Read more
Best Of

2026 年最佳 SERP API 提供商按价格排名

Read more
Glossary

免费搜索API层级对比

Read more
Comparison

Search APIs (Scavio, Tavily, SerpAPI) vs Headless Browser (Playwright, Puppeteer, Browserbase)

Read more
Comparison

Google Places API vs SERP Local Pack API

Read more

开始构建

任何 Python AI 代理都可以在 20 行之内使用实时搜索数据。可与 OpenAI、Anthropic、LangChain 或自定义代理配合使用。分步教程。

获取免费API密钥阅读文档
ScavioScavio

面向AI智能体的实时搜索API。搜索所有平台,不仅仅是Google。

产品

  • 功能
  • 定价
  • 控制台
  • 联盟计划

开发者

  • 文档
  • API参考
  • 快速开始
  • MCP集成
  • Python SDK

替代方案

  • Tavily替代方案
  • SerpAPI替代方案
  • Firecrawl替代方案
  • Exa替代方案

工具

  • JSON格式化
  • cURL转代码
  • Token计数器
  • 全部工具

© 2026 Scavio. 保留所有权利。

Featured on TAAFT
服务条款隐私政策