ScavioScavio
产品定价文档
登录开始使用
  1. 首页
  2. 教程
  3. 如何建立 DeepSeek 搜索基础
教程

如何建立 DeepSeek 搜索基础

使用实时搜索数据来地面 DeepSeek 模型响应。将 Web 搜索添加到基于 DeepSeek 的代理的分步 Python 教程。

获取免费API密钥API文档

DeepSeek 模型提供强大的推理能力,但缺乏内置的网络搜索访问。当用户询问时事、定价或最新版本时,DeepSeek 要么拒绝回答,要么产生过时的信息。搜索基础通过获取相关 SERP 数据并将其注入到 DeepSeek 生成响应之前的提示上下文中来解决此问题。本教程展示如何使用 Scavio API 以每次搜索 0.005 美元的价格向任何基于 DeepSeek 的代理添加搜索基础。

前置条件

  • 已安装 Python 3.9+
  • 安装了 openai 库(DeepSeek 使用 OpenAI 兼容的 API)
  • 请求已安装库
  • DeepSeek API 密钥和 Scavio API 密钥

操作指南

步骤 1: 设置 DeepSeek 客户端

DeepSeek 使用 OpenAI 兼容的 API,因此您可以使用带有自定义基本 URL 的 OpenAI Python 库。设置 DeepSeek 和搜索客户端。

Python
from openai import OpenAI
import requests, os

# DeepSeek client
deepseek = OpenAI(
    api_key=os.environ['DEEPSEEK_API_KEY'],
    base_url='https://api.deepseek.com'
)

# Search client
SCAVIO_KEY = os.environ['SCAVIO_API_KEY']

def web_search(query: str, max_results: int = 5) -> str:
    resp = requests.post('https://api.scavio.dev/api/v1/search',
        headers={'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'},
        json={'query': query, 'country_code': 'us'})
    results = resp.json().get('organic_results', [])[:max_results]
    return '\n\n'.join(
        f'Source: {r["link"]}\nTitle: {r["title"]}\n{r.get("snippet", "")}'
        for r in results
    )

print('DeepSeek + Search grounding ready')

步骤 2: 检测何时需要接地

并非每个查询都需要搜索。构建一个分类器,根据查询内容决定是否进行搜索或让 DeepSeek 从其训练数据中进行回答。

Python
def needs_grounding(user_message: str) -> bool:
    grounding_signals = [
        'latest', 'current', 'today', 'now', '2025', '2026',
        'price', 'cost', 'how much', 'release', 'version',
        'news', 'update', 'recent', 'best', 'top', 'compare'
    ]
    message_lower = user_message.lower()
    return any(signal in message_lower for signal in grounding_signals)

# Test:
for q in ['explain quantum computing', 'best Python IDE 2026', 'what is recursion']:
    print(f'Ground: {needs_grounding(q):5} | {q}')

步骤 3: 构建接地气的DeepSeek聊天功能

创建主函数,该函数可以选择搜索、构建上下文,并使用接地或非接地提示调用 DeepSeek。

Python
def ask_deepseek(user_message: str, ground: bool = None) -> str:
    should_ground = ground if ground is not None else needs_grounding(user_message)
    messages = []
    if should_ground:
        search_context = web_search(user_message)
        system_prompt = f"""You are a helpful assistant with access to current web search results.
Use the search results below to provide accurate, up-to-date answers.
Cite sources with URLs when referencing specific facts.
If the search results do not contain relevant information, say so.

Search Results:
{search_context}"""
        messages.append({'role': 'system', 'content': system_prompt})
    else:
        messages.append({'role': 'system',
                        'content': 'You are a helpful assistant. Answer from your knowledge.'})
    messages.append({'role': 'user', 'content': user_message})
    response = deepseek.chat.completions.create(
        model='deepseek-chat',
        messages=messages,
        max_tokens=1000,
        temperature=0.7
    )
    return response.choices[0].message.content

# Test grounded query:
answer = ask_deepseek('What are the top Python web frameworks in 2026?')
print(answer)

步骤 4: 添加多轮对话支持

对于对话,请保留消息历史记录,并且仅在当前回合需要时才接地。以前的接地背景已经成为历史。

Python
class GroundedDeepSeek:
    def __init__(self):
        self.history = []
        self.search_count = 0

    def chat(self, user_message: str) -> str:
        self.history.append({'role': 'user', 'content': user_message})
        if needs_grounding(user_message):
            context = web_search(user_message)
            self.search_count += 1
            system = f'Use these search results:\n{context}'
            messages = [{'role': 'system', 'content': system}] + self.history
        else:
            messages = self.history.copy()
        response = deepseek.chat.completions.create(
            model='deepseek-chat',
            messages=messages,
            max_tokens=1000
        )
        answer = response.choices[0].message.content
        self.history.append({'role': 'assistant', 'content': answer})
        return answer

    def cost_so_far(self) -> str:
        return f'{self.search_count} searches = ${self.search_count * 0.005:.3f}'

agent = GroundedDeepSeek()
print(agent.chat('What is the latest DeepSeek model?'))
print(f'Search cost: {agent.cost_so_far()}')

Python 示例

Python
from openai import OpenAI
import os, requests

deepseek = OpenAI(api_key=os.environ['DEEPSEEK_API_KEY'], base_url='https://api.deepseek.com')
SCAVIO_KEY = os.environ['SCAVIO_API_KEY']

def search(query, k=5):
    resp = requests.post('https://api.scavio.dev/api/v1/search',
        headers={'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'},
        json={'query': query, 'country_code': 'us'})
    return '\n'.join(f'{r["title"]}: {r.get("snippet", "")}'
        for r in resp.json().get('organic_results', [])[:k])

def ask(question):
    ctx = search(question)
    resp = deepseek.chat.completions.create(
        model='deepseek-chat',
        messages=[
            {'role': 'system', 'content': f'Use search results:\n{ctx}'},
            {'role': 'user', 'content': question}
        ], max_tokens=500)
    return resp.choices[0].message.content

print(ask('Best Python web frameworks 2026'))

JavaScript 示例

JavaScript
import OpenAI from 'openai';

const deepseek = new OpenAI({
  apiKey: process.env.DEEPSEEK_API_KEY,
  baseURL: 'https://api.deepseek.com'
});
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;

async function search(query) {
  const resp = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST',
    headers: { 'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, country_code: 'us' })
  });
  const data = await resp.json();
  return (data.organic_results || []).slice(0, 5)
    .map(r => `${r.title}: ${r.snippet || ''}`).join('\n');
}

async function ask(question) {
  const ctx = await search(question);
  const resp = await deepseek.chat.completions.create({
    model: 'deepseek-chat',
    messages: [
      { role: 'system', content: `Search results:\n${ctx}` },
      { role: 'user', content: question }
    ], max_tokens: 500
  });
  console.log(resp.choices[0].message.content);
}

ask('Best Python frameworks 2026');

预期输出

JSON
Ground: False | explain quantum computing
Ground:  True | best Python IDE 2026
Ground: False | what is recursion

Based on current search results, the top Python web frameworks in 2026 are:
1. FastAPI - async-first, ideal for APIs (Source: https://...)
2. Django - full-featured with built-in admin (Source: https://...)
3. Flask - lightweight and flexible (Source: https://...)

Search cost: 1 searches = $0.005

相关教程

  • 如何为任何 Python 代理添加搜索基础
  • 如何使用搜索 API 修复 Hermes v0.13.0 损坏的搜索
  • 如何设置初级代理搜索基础

常见问题

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

已安装 Python 3.9+. 安装了 openai 库(DeepSeek 使用 OpenAI 兼容的 API). 请求已安装库. DeepSeek API 密钥和 Scavio API 密钥. 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

开始构建

使用实时搜索数据来地面 DeepSeek 模型响应。将 Web 搜索添加到基于 DeepSeek 的代理的分步 Python 教程。

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

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

产品

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

开发者

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

替代方案

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

工具

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

© 2026 Scavio. 保留所有权利。

Featured on TAAFT
服务条款隐私政策