在 Python 中使用 Ollama Web Search API

发布: (2025年12月5日 GMT+8 13:41)
4 min read
原文: Dev.to

Source: Dev.to

入门指南

安装
安装 0.6.0 及以上版本:

pip install 'ollama>=0.6.0'

环境设置
在管理 Python 环境和依赖时,建议使用 uv 或使用 venv 创建虚拟环境。

从你的 Ollama 账户 创建 API 密钥,并将其设置为环境变量:

export OLLAMA_API_KEY="your_api_key"

在 Windows PowerShell 中:

$env:OLLAMA_API_KEY = "your_api_key"

基础网页搜索

import ollama

# 简单网页搜索
response = ollama.web_search("What is Ollama?")
print(response)

示例输出

results = [
    {
        "title": "Ollama",
        "url": "https://ollama.com/",
        "content": "Cloud models are now available in Ollama..."
    },
    {
        "title": "What is Ollama? Features, Pricing, and Use Cases",
        "url": "https://www.walturn.com/insights/what-is-ollama",
        "content": "Our services..."
    },
    {
        "title": "Complete Ollama Guide: Installation, Usage & Code Examples",
        "url": "https://collabnix.com/complete-ollama-guide",
        "content": "Join our Discord Server..."
    }
]

控制结果数量

import ollama

# 获取更多结果
response = ollama.web_search("latest AI news", max_results=10)

for result in response.results:
    print(f"📌 {result.title}")
    print(f"   {result.url}")
    print(f"   {result.content[:100]}...")
    print()

获取完整页面内容

web_search 返回多个搜索结果(标题、URL 和摘要)。
web_fetch 用于获取指定 URL 的完整内容,返回页面标题、Markdown 内容以及链接。

from ollama import web_fetch

result = web_fetch('https://ollama.com')
print(result)

示例输出

WebFetchResponse(
    title='Ollama',
    content='[Cloud models](https://ollama.com/blog/cloud-models) are now available in Ollama\n\n**Chat & build with open models**\n\n[Download](https://ollama.com/download) [Explore models](https://ollama.com/models)\n\nAvailable for macOS, Windows, and Linux',
    links=['https://ollama.com/', 'https://ollama.com/models', 'https://github.com/ollama/ollama']
)

关于将 HTML 转换为 Markdown 的更多信息,请参阅我们的指南《使用 Python 将 HTML 转换为 Markdown》。

组合搜索与获取

常见的做法是先搜索,再从相关结果中获取完整内容:

from ollama import web_search, web_fetch

# 搜索信息
search_results = web_search("Ollama new features 2025")

# 从第一个结果获取完整内容
if search_results.results:
    first_url = search_results.results[0].url
    full_content = web_fetch(first_url)

    print(f"Title: {full_content.title}")
    print(f"Content: {full_content.content[:500]}...")
    print(f"Links found: {len(full_content.links)}")

构建搜索代理

具备强大工具使用能力的模型效果最佳,例如 qwen3gpt-oss,以及云模型如 qwen3:480b-clouddeepseek-v3.1-cloud。高级用例请参考《使用 Ollama 与 Qwen3 进行结构化输出的 LLMs》。

首先,拉取一个能力较强的模型:

ollama pull qwen3:4b

简单搜索代理

一个能够自主决定何时进行搜索的基础代理示例:

from ollama import chat, web_fetch, web_search

available_tools = {'web_search': web_search, 'web_fetch': web_fetch}
messages = [{'role': 'user', 'content': "what is ollama's new engine"}]

while True:
    response = chat(
        model='qwen3:4b',
        messages=messages,
        tools=[web_search, web_fetch],
        think=True
    )

    if response.message.thinking:
        print('🧠 Thinking:', response.message.thinking[:200], '...')

    if response.message.content:
        print('💬 Response:', response.message.content)

    messages.append(response.message)

    if response.message.tool_calls:
        print('🔧 Tool calls:', response.message.tool_calls)
        for tool_call in response.message.tool_calls:
            function_to_call = available_tools.get(tool_call.function.name)
            if function_to_call:
                args = tool_call.function.arguments
                result = function_to_call(**args)
                print('📥 Result:', str(result)[:200], '...')
                # 为了适配上下文长度限制,对结果进行截断
                messages.append({
                    'role': 'tool',
                    'content': str(result)[:2000 * 4],
                    'tool_name': tool_call.function.name
                })
            else:
                messages.append({
                    'role': 'tool',
                    'content': f'Tool {tool_call.function.name} not found',
                    'tool_name': tool_call.function.name
                })
    else:
        break

处理大量网页搜索结果
在将结果传递给模型之前,需要将其截断至上下文限制(约 8000 字符,即 2000 token × 4 字符)。

带错误处理的高级搜索代理

加入更完善错误处理的增强版示例:

from ollama import chat, web_fetch, web_search
import json

class SearchAgent:
    def __init__(self, model: str = 'qwen3:4b'):
        self.model = model
        self.tools = {'web_search': web_search, 'web_fetch': web_fetch}
        self.messages = []
        self.max_iterations = 10

    def query(self, question: str) -> str:
        self.messages = [{'role': 'user', 'content': question}]

        for iteration in range(self.max_iterations):
            try:
                response = chat(
                    model=self.model,
                    messages=self.messages,
                    tools=[web_search, web_fetch],
                    think=True
                )
            except Exception as e:
                return f"Error during chat: {e}"

            self.messages.append(response.message)

            # 若没有工具调用,则得到最终答案
            if not response.message.tool_calls:
                return 
Back to Blog

相关文章

阅读更多 »