ScavioScavio
产品定价文档
登录开始使用
  1. 首页
  2. 教程
  3. 如何向 Ollama 个人助理添加搜索
教程

如何向 Ollama 个人助理添加搜索

为您的 Ollama 私人助理提供实时网络搜索。当地法学硕士通过搜索回答有关时事、价格和新闻的问题。

获取免费API密钥API文档

Ollama 非常适合在本地和私人经营法学硕士,但本地模式有知识限制。您的私人助理无法回答有关时事、实时价格或最新发布的问题。添加搜索工具使 Ollama 能够访问实时数据,同时保持法学硕士本身的本地化。本教程将 Ollama 连接到 Scavio API(每次搜索 0.005 美元),以便您的助手在需要最新信息时可以搜索 Google、Reddit、YouTube 等。

前置条件

  • Ollama 至少安装一种型号(推荐llama3)
  • 已安装 Python 3.9+
  • 请求已安装库
  • 来自 scavio.dev 的 Scavio API 密钥

操作指南

步骤 1: 构建支持搜索的助手

创建一个 Python 助手,用搜索工具包装 Ollama。助手根据问题决定何时进行搜索。

Python
import os, requests

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
OLLAMA_URL = 'http://localhost:11434/v1/chat/completions'

def search_web(query: str, num: 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', 'num_results': num})
    results = resp.json().get('organic_results', [])
    return '\n'.join(f'[{i+1}] {r["title"]}: {r.get("snippet", "")}\nURL: {r["link"]}'
                     for i, r in enumerate(results))

def needs_search(question: str) -> bool:
    triggers = ['latest', 'current', 'today', '2026', '2025', 'now',
                'price', 'cost', 'version', 'release', 'news',
                'best', 'top', 'compare', 'vs', 'weather',
                'who won', 'what happened', 'how much']
    q = question.lower()
    return any(t in q for t in triggers)

def ask_assistant(question: str) -> dict:
    use_search = needs_search(question)
    context = ''
    if use_search:
        context = f'Web search results:\n{search_web(question)}\n\n'
    messages = [
        {'role': 'system', 'content': (
            'You are a helpful personal assistant. '
            + ('Use the web search results to answer accurately. Cite sources [1],[2]. '
               if use_search else 'Answer from your knowledge. Say if you are unsure.')
        )},
        {'role': 'user', 'content': f'{context}Question: {question}'}
    ]
    resp = requests.post(OLLAMA_URL, json={
        'model': 'llama3', 'messages': messages, 'max_tokens': 512
    })
    return {
        'answer': resp.json()['choices'][0]['message']['content'],
        'searched': use_search,
        'cost': 0.005 if use_search else 0,
    }

result = ask_assistant('What is the latest Python version in 2026?')
print(f'[{"SEARCHED" if result["searched"] else "LOCAL"}] ${result["cost"]}')
print(result['answer'])

步骤 2: 添加特定于平台的搜索命令

让助手搜索特定平台。在问题前加上平台名称前缀,可以针对 Reddit 获取意见,针对 YouTube 获取教程,或者针对 Amazon 获取产品。

Python
def search_platform(query: str, platform: str = 'google') -> str:
    site_map = {'reddit': 'site:reddit.com', 'youtube': 'site:youtube.com',
                'amazon': 'site:amazon.com', 'walmart': 'site:walmart.com'}
    prefix = site_map.get(platform, '')
    full_query = f'{prefix} {query}'.strip()
    return search_web(full_query)

def detect_platform(question: str) -> tuple[str, str]:
    """Detect if a platform is mentioned and return (platform, cleaned_question)."""
    q = question.lower()
    if 'on reddit' in q or 'reddit thinks' in q:
        return 'reddit', question.replace('on reddit', '').replace('reddit thinks', '').strip()
    if 'on youtube' in q or 'youtube tutorial' in q:
        return 'youtube', question.replace('on youtube', '').replace('youtube tutorial', '').strip()
    if 'on amazon' in q or 'amazon price' in q:
        return 'amazon', question.replace('on amazon', '').replace('amazon price', '').strip()
    return 'google', question

def smart_assistant(question: str) -> dict:
    platform, clean_q = detect_platform(question)
    use_search = needs_search(clean_q) or platform != 'google'
    context = ''
    if use_search:
        results = search_platform(clean_q, platform)
        context = f'Search results from {platform.upper()}:\n{results}\n\n'
    messages = [
        {'role': 'system', 'content': f'You are a helpful assistant. '
            f'{"Answer from " + platform + " search results. Cite [1],[2]." if use_search else "Answer from knowledge."}'}
        ,
        {'role': 'user', 'content': f'{context}Question: {question}'}
    ]
    resp = requests.post(OLLAMA_URL, json={'model': 'llama3', 'messages': messages, 'max_tokens': 512})
    return {'answer': resp.json()['choices'][0]['message']['content'],
            'platform': platform, 'searched': use_search, 'cost': 0.005 if use_search else 0}

for q in ['What does reddit think about mechanical keyboards?',
          'What is a Python list comprehension?',
          'Best noise cancelling headphones on amazon']:
    r = smart_assistant(q)
    print(f'[{r["platform"]:8s}] ${r["cost"]} - {q[:50]}')
    print(f'  {r["answer"][:80]}...')
    print()

步骤 3: 构建交互式聊天循环

创建基于终端的聊天界面,用于维护对话历史记录并在需要时进行搜索。

Python
def chat_loop():
    """Interactive chat with search-augmented Ollama."""
    history = []
    total_cost = 0
    print('Ollama Assistant with Web Search')
    print('Type "quit" to exit, "cost" for session cost')
    print('-' * 40)
    while True:
        question = input('\nYou: ').strip()
        if not question:
            continue
        if question.lower() == 'quit':
            print(f'\nSession cost: ${total_cost:.3f}')
            break
        if question.lower() == 'cost':
            print(f'Session cost so far: ${total_cost:.3f}')
            continue
        result = smart_assistant(question)
        total_cost += result['cost']
        source = f'{result["platform"]} search' if result['searched'] else 'local knowledge'
        print(f'\nAssistant [{source}, ${result["cost"]}]:')
        print(result['answer'])
        history.append({'question': question, **result})

# Run the chat loop (uncomment to use interactively)
# chat_loop()

# Simulate for the tutorial
for q in ['What is the latest Node.js version?', 'Explain Python decorators']:
    r = smart_assistant(q)
    source = f'{r["platform"]} search' if r['searched'] else 'local'
    print(f'You: {q}')
    print(f'Assistant [{source}]: {r["answer"][:100]}...')
    print()

步骤 4: 添加对话记忆和上下文

跟踪对话历史记录,以便助手记住之前的答案并可以参考之前的搜索。

Python
class SearchAssistant:
    def __init__(self, model: str = 'llama3'):
        self.model = model
        self.history = []
        self.total_cost = 0
        self.search_count = 0

    def ask(self, question: str) -> str:
        platform, clean_q = detect_platform(question)
        use_search = needs_search(clean_q) or platform != 'google'
        context = ''
        if use_search:
            context = f'\nWeb results ({platform}):\n{search_platform(clean_q, platform)}\n'
            self.search_count += 1
            self.total_cost += 0.005
        # Build messages with history
        messages = [{'role': 'system', 'content': (
            'You are a helpful personal assistant with web search access. '
            'Cite search results as [1],[2]. Remember previous conversation.'
        )}]
        # Add recent history (last 4 exchanges)
        for h in self.history[-4:]:
            messages.append({'role': 'user', 'content': h['question']})
            messages.append({'role': 'assistant', 'content': h['answer']})
        messages.append({'role': 'user', 'content': f'{context}\n{question}'})
        resp = requests.post(OLLAMA_URL, json={
            'model': self.model, 'messages': messages, 'max_tokens': 512
        })
        answer = resp.json()['choices'][0]['message']['content']
        self.history.append({'question': question, 'answer': answer})
        return answer

    def stats(self):
        print(f'Questions: {len(self.history)}')
        print(f'Searches: {self.search_count}')
        print(f'Total cost: ${self.total_cost:.3f}')

assistant = SearchAssistant()
print(assistant.ask('What is the latest Python version?'))
print(assistant.ask('Tell me more about its new features'))
assistant.stats()

Python 示例

Python
import os, requests

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']

def search(query, num=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', 'num_results': num})
    return '\n'.join(f'[{i+1}] {r["title"]}: {r.get("snippet","")}'
                     for i, r in enumerate(resp.json().get('organic_results', [])))

def ask(question):
    triggers = ['latest', 'current', '2026', 'price', 'best', 'news', 'vs']
    use_search = any(t in question.lower() for t in triggers)
    ctx = f'Search results:\n{search(question)}\n\n' if use_search else ''
    resp = requests.post('http://localhost:11434/v1/chat/completions', json={
        'model': 'llama3', 'messages': [
            {'role': 'system', 'content': 'Helpful assistant. Cite search results [1],[2] when available.'},
            {'role': 'user', 'content': f'{ctx}Q: {question}'}], 'max_tokens': 512})
    return resp.json()['choices'][0]['message']['content']

print(ask('What is the latest Python version in 2026?'))

JavaScript 示例

JavaScript
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;

async function search(query, num = 5) {
  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', num_results: num })
  });
  return ((await resp.json()).organic_results || []).map((r, i) => `[${i+1}] ${r.title}: ${r.snippet || ''}`).join('\n');
}

async function ask(question) {
  const needsSearch = /latest|current|2026|price|best|news|vs/i.test(question);
  const ctx = needsSearch ? `Search results:\n${await search(question)}\n\n` : '';
  const resp = await fetch('http://localhost:11434/v1/chat/completions', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ model: 'llama3', messages: [
      { role: 'system', content: 'Helpful assistant. Cite [1],[2] from search results.' },
      { role: 'user', content: `${ctx}Q: ${question}` }], max_tokens: 512 })
  });
  return (await resp.json()).choices[0].message.content;
}

ask('latest Python version 2026').then(console.log);

预期输出

JSON
[SEARCHED] $0.005
Based on the search results, the latest Python version as of 2026 is
Python 3.15, released in October 2025 [1]. The 3.15 release includes
performance improvements and new syntax features [2].

[reddit  ] $0.005 - What does reddit think about mechanical keyboards?
  According to Reddit discussions, r/MechanicalKeyboards recomm...

[google  ] $0.000 - What is a Python list comprehension?
  A list comprehension is a concise way to create lists in Pyth...

Questions: 2
Searches: 1
Total cost: $0.005

相关教程

  • 如何利用本地法学硕士和搜索建立个人知识库
  • 如何利用多平台搜索数据奠定本地法学硕士的基础
  • 如何将搜索 API 添加到 OpenWebUI
  • 如何使用 LangChain 和 Scavio 构建 RAG 代理

常见问题

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

Ollama 至少安装一种型号(推荐llama3). 已安装 Python 3.9+. 请求已安装库. 来自 scavio.dev 的 Scavio API 密钥. Scavio API密钥注册即送50个免费积分。

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

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

相关资源

Best Of

2026年本地LLM接地最佳搜索API

Read more
Best Of

2026年5月本地LLM最佳网页搜索工具

Read more
Solution

Google收费墙后的本地LLM搜索方案

Read more
Workflow

本地法学硕士接地管道工作流程

Read more
Workflow

每日本地法学硕士搜索接地管道

Read more
Glossary

LLM 流量取代

Read more

开始构建

为您的 Ollama 私人助理提供实时网络搜索。当地法学硕士通过搜索回答有关时事、价格和新闻的问题。

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

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

产品

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

开发者

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

替代方案

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

工具

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

© 2026 Scavio. 保留所有权利。

Featured on TAAFT
服务条款隐私政策