当基于当前的网络数据而不是仅仅依赖于训练数据时,大型语言模型可以产生更高质量的答案。本教程构建了一个管道,用于获取用户问题的实时 Google 结果,将最重要的结果格式化为上下文,并将它们发送到 GPT,并附有仅使用提供的源进行回答的说明。结果是一个被引用的最新答案,类似于 Perplexity 或 Bing Chat,用不到 50 行 Python 代码构建。
前置条件
- Python 3.10 或更高版本
- pip 安装请求 openai
- Scavio API 密钥
- OpenAI API 密钥
操作指南
步骤 1: 获取问题的搜索结果
使用 Scavio API 获取用户问题的最佳有机结果。这些将作为基础背景。
import os
import requests
API_KEY = os.environ.get("SCAVIO_API_KEY", "your_scavio_api_key")
def fetch_context(question: str, n: int = 5) -> list[dict]:
r = requests.post(
"https://api.scavio.dev/api/v1/search",
headers={"x-api-key": API_KEY},
json={"query": question, "country_code": "us"}
)
r.raise_for_status()
return r.json().get("organic_results", [])[:n]步骤 2: 将结果格式化为上下文
将搜索结果转换为 LLM 可以通过源编号引用的编号上下文块。
def format_context(results: list[dict]) -> str:
lines = []
for i, r in enumerate(results, 1):
lines.append(f"[{i}] {r.get('title', '')}")
lines.append(f" URL: {r.get('link', '')}")
lines.append(f" {r.get('snippet', '')}")
return "\n".join(lines)步骤 3: 发送至 GPT 并附上接地说明
将上下文和问题传递给 GPT,并显示系统提示,要求按编号引用来源。
from openai import OpenAI
client = OpenAI()
def ask_with_context(question: str, context: str) -> str:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "Answer the question using ONLY the provided search results. Cite sources using [n] notation. If the results do not contain the answer, say so."},
{"role": "user", "content": f"Search results:\n{context}\n\nQuestion: {question}"}
],
temperature=0
)
return response.choices[0].message.content步骤 4: 运行完整管道
将任何用户问题的获取、格式化和回答步骤链接在一起。
def answer(question: str) -> str:
results = fetch_context(question)
context = format_context(results)
return ask_with_context(question, context)
print(answer("What are the best Python testing frameworks in 2026?"))Python 示例
import os
import requests
from openai import OpenAI
SCAVIO_KEY = os.environ.get("SCAVIO_API_KEY", "your_scavio_api_key")
client = OpenAI()
def fetch_context(question: str) -> list[dict]:
r = requests.post("https://api.scavio.dev/api/v1/search",
headers={"x-api-key": SCAVIO_KEY},
json={"query": question, "country_code": "us"})
r.raise_for_status()
return r.json().get("organic_results", [])[:5]
def format_context(results: list[dict]) -> str:
return "\n".join(f"[{i}] {r['title']}\n {r.get('snippet', '')}\n {r['link']}" for i, r in enumerate(results, 1))
def answer(question: str) -> str:
ctx = format_context(fetch_context(question))
resp = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "Answer using ONLY the search results. Cite with [n]."},
{"role": "user", "content": f"Results:\n{ctx}\n\nQuestion: {question}"}
], temperature=0)
return resp.choices[0].message.content
if __name__ == "__main__":
print(answer("What are the best Python testing frameworks in 2026?"))JavaScript 示例
const SCAVIO_KEY = process.env.SCAVIO_API_KEY || "your_scavio_api_key";
const { OpenAI } = require("openai");
const client = new OpenAI();
async function fetchContext(question) {
const res = 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: question, country_code: "us" })
});
const data = await res.json();
return (data.organic_results || []).slice(0, 5);
}
async function answer(question) {
const results = await fetchContext(question);
const ctx = results.map((r, i) => `[${i + 1}] ${r.title}\n ${r.snippet || ""}\n ${r.link}`).join("\n");
const resp = await client.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "Answer using ONLY the search results. Cite with [n]." },
{ role: "user", content: `Results:\n${ctx}\n\nQuestion: ${question}` }
], temperature: 0
});
console.log(resp.choices[0].message.content);
}
answer("Best Python testing frameworks 2026").catch(console.error);预期输出
Based on search results, the top Python testing frameworks in 2026 are:
1. **pytest** - The most popular framework with extensive plugin support [1]
2. **Hypothesis** - Property-based testing gaining rapid adoption [2]
3. **Playwright for Python** - Leading choice for end-to-end browser testing [3]
Sources:
[1] https://example.com/python-testing-2026
[2] https://example.com/hypothesis-testing
[3] https://example.com/playwright-python