ScavioScavio
产品定价文档
登录开始使用
  1. 首页
  2. 教程
  3. 如何设置初级代理搜索基础
教程

如何设置初级代理搜索基础

在 15 分钟内为您的第一个 AI 代理设置搜索基础。不需要框架。带有请求库和任何 LLM 的纯 Python。

获取免费API密钥API文档

搜索接地意味着让您的人工智能代理能够访问实时网络结果,以便它可以回答有关当前事件、价格和最近变化的问题,而不会产生幻觉。您不需要 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脚本对其进行测试以确保其有效。

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 行代码。

Python
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: 建立接地提示

将搜索结果与提示模板中的用户问题结合起来。告诉法学硕士使用搜索结果并引用来源。

Python
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 的工作方式相同。

Python
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: 添加对话循环

将一次性查询转变为对话代理。每条用户消息都以新鲜的搜索结果为基础。

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

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

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

预期输出

JSON
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/

相关教程

  • 如何为任何 Python 代理添加搜索基础
  • 2026 年如何构建 MCP 多功能工具代理
  • 如何建立 DeepSeek 搜索基础

常见问题

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

已安装 Python 3.8+. 安装请求库(pip install requests). 来自 scavio.dev 的 Scavio API 密钥(每月 250 个免费积分). 任何 LLM API 密钥(OpenAI、Anthropic 等)或本地模型. Scavio API密钥注册即送50个免费积分。

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

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

相关资源

Best Of

2026 年最佳 AI 生产力应用程序

Read more
Best Of

2026年最佳SerpAPI替代方案

Read more
Glossary

搜索 API 供应商格局(2026)

Read more
Glossary

搜索付费墙时代(2026)

Read more
Use Case

2026 开源 AI 网络访问方案

Read more
Comparison

DataForSEO vs Serper

Read more

开始构建

在 15 分钟内为您的第一个 AI 代理设置搜索基础。不需要框架。带有请求库和任何 LLM 的纯 Python。

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

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

产品

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

开发者

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

替代方案

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

工具

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

© 2026 Scavio. 保留所有权利。

Featured on TAAFT
服务条款隐私政策