关于 web-search
web-search 是一项技能,指导开发者使用 z-ai-web-dev-sdk 在应用中实现网络搜索,也可通过 z-ai CLI 执行简单查询。支持获取最新网页结果,并提供结果数量、时间范围及处理选项。
主要功能
- 01通过 SDK 搜索网页
- 02使用 z-ai CLI 执行查询
- 03限制结果数量并按时间筛选
- 04将结果保存为 JSON
- 05处理并校验搜索结果
适用场景
- 01获取最新新闻或其他信息
- 02研究主题并查找文档
- 03在后端应用中集成网页搜索
- 04收集结果以核查事实
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ answerzhao/ agent-skills --skill web-search安装后在 Claude Code 中输入/web-search确认已加载。
附带文件LICENSE.txtscripts/web_search.ts
详细介绍
网页搜索技能
本技能指导如何使用 z-ai-web-dev-sdk 包实现网页搜索功能,使应用能够搜索网页并获取当前信息。
安装路径
推荐位置:{project_path}/skills/web-search
将此技能包解压到项目中的上述路径。
参考脚本:{project_path}/skills/web-search/scripts/ 目录中提供了示例测试脚本,供快速测试和参考。参见 {project_path}/skills/web-search/scripts/web_search.ts 获取可运行的示例。
概述
网页搜索技能允许你构建能够搜索互联网、获取当前信息并访问网页来源实时数据的应用。
重要:z-ai-web-dev-sdk 必须仅在 后端代码中使用。切勿在客户端代码中使用。
前置条件
z-ai-web-dev-sdk 包已安装。按下方示例所示导入它。
命令行用法(适用于简单任务)
对于简单的网页搜索查询,你可以使用 z-ai 命令行,而无需编写代码。这非常适合快速检索信息、测试搜索功能或命令行自动化。
基本网页搜索
# Simple search query
z-ai function --name "web_search" --args '{"query": "artificial intelligence"}'
# Using short options
z-ai function -n web_search -a '{"query": "latest tech news"}'
使用自定义参数搜索
# Limit number of results
z-ai function \
-n web_search \
-a '{"query": "machine learning", "num": 5}'
# Search with recency filter (results from last N days)
z-ai function \
-n web_search \
-a '{"query": "cryptocurrency news", "num": 10, "recency_days": 7}'
保存搜索结果
# Save results to JSON file
z-ai function \
-n web_search \
-a '{"query": "climate change research", "num": 5}' \
-o search_results.json
# Recent news with file output
z-ai function \
-n web_search \
-a '{"query": "AI breakthroughs", "num": 3, "recency_days": 1}' \
-o ai_news.json
高级搜索示例
# Search for specific topics
z-ai function \
-n web_search \
-a '{"query": "quantum computing applications", "num": 8}' \
-o quantum.json
# Find recent scientific papers
z-ai function \
-n web_search \
-a '{"query": "genomics research", "num": 5, "recency_days": 30}' \
-o genomics.json
# Technology news from last 24 hours
z-ai function \
-n web_search \
-a '{"query": "tech industry updates", "recency_days": 1}' \
-o today_tech.json
命令行参数
--name, -n:必需 - 函数名称(使用 "web_search")--args, -a:必需 - JSON 参数对象,包含:query(字符串,必需):搜索关键词num(数字,可选):结果数量(默认:10)recency_days(数字,可选):筛选最近 N 天的结果
--output, -o <path>:可选 - 输出文件路径(JSON 格式)
搜索结果结构
每条结果包含:
url:结果的完整 URLname:页面标题snippet:预览文本/描述host_name:域名rank:结果排名date:发布/更新日期favicon:网站图标 URL
何时使用命令行与 SDK
在以下情况使用命令行:
- 快速查询信息
- 测试搜索查询
- 简单的自动化脚本
- 一次性研究任务
在以下情况使用 SDK:
- 应用中的动态搜索
- 多步骤搜索工作流
- 自定义结果处理和过滤
- 具有复杂逻辑的生产应用
搜索结果类型
每条搜索结果都是一个 SearchFunctionResultItem,其结构如下:
interface SearchFunctionResultItem {
url: string; // Full URL of the result
name: string; // Title of the page
snippet: string; // Preview text/description
host_name: string; // Domain name
rank: number; // Result ranking
date: string; // Publication/update date
favicon: string; // Favicon URL
}
基本网页搜索
简单搜索查询
import ZAI from 'z-ai-web-dev-sdk';
async function searchWeb(query) {
const zai = await ZAI.create();
const results = await zai.functions.invoke('web_search', {
query: query,
num: 10
});
return results;
}
// Usage
const searchResults = await searchWeb('What is the capital of France?');
console.log('Search Results:', searchResults);
使用自定义结果数量搜索
import ZAI from 'z-ai-web-dev-sdk';
async function searchWithLimit(query, numberOfResults) {
const zai = await ZAI.create();
const results = await zai.functions.invoke('web_search', {
query: query,
num: numberOfResults
});
return results;
}
// Usage - Get top 5 results
const topResults = await searchWithLimit('artificial intelligence news', 5);
// Usage - Get top 20 results
const moreResults = await searchWithLimit('JavaScript frameworks', 20);
格式化搜索结果
import ZAI from 'z-ai-web-dev-sdk';
async function getFormattedResults(query) {
const zai = await ZAI.create();
const results = await zai.functions.invoke('web_search', {
query: query,
num: 10
});
// Format results for display
const formatted = results.map((item, index) => ({
position: index + 1,
title: item.name,
url: item.url,
description: item.snippet,
domain: item.host_name,
publishDate: item.date
}));
return formatted;
}
// Usage
const results = await getFormattedResults('climate change solutions');
results.forEach(result => {
console.log(`${result.position}. ${result.title}`);
console.log(` ${result.url}`);
console.log(` ${result.description}`);
console.log('');
});
高级用例
带结果处理的搜索
import ZAI from 'z-ai-web-dev-sdk';
class SearchProcessor {
constructor() {
this.zai = null;
}
async initialize() {
this.zai = await ZAI.create();
}
async search(query, options = {}) {
const {
num = 10,
filterDomain = null,
minSnippetLength = 0
} = options;
const results = await this.zai.functions.invoke('web_search', {
query: query,
num: num
});
// Filter results
let filtered = results;
if (filterDomain) {
filtered = filtered.filter(item =>
item.host_name.includes(filterDomain)
);
}
if (minSnippetLength > 0) {
filtered = filtered.filter(item =>
item.snippet.length >= minSnippetLength
);
}
return filtered;
}
extractDomains(results) {
return [...new Set(results.map(item => item.host_name))];
}
groupByDomain(results) {
const grouped = {};
results.forEach(item => {
if (!grouped[item.host_name]) {
grouped[item.host_name] = [];
}
grouped[item.host_name].push(item);
});
return grouped;
}
sortByDate(results, ascending = false) {
return results.sort((a, b) => {
const dateA = new Date(a.date);
const dateB = new Date(b.date);
return ascending ? dateA - dateB : dateB - dateA;
});
}
}
// Usage
const processor = new SearchProcessor();
await processor.initialize();
const results = await processor.search('machine learning tutorials', {
num: 15,
minSnippetLength: 50
});
console.log('Domains found:', processor.extractDomains(results));
console.log('Grouped by domain:', processor.groupByDomain(results));
console.log('Sorted by date:', processor.sortByDate(results));
新闻搜索
import ZAI from 'z-ai-web-dev-sdk';
async function searchNews(topic, timeframe = 'recent') {
const zai = await ZAI.create();
// Add time-based keywords to query
const timeKeywords = {
recent: 'latest news',
today: 'today news',
week: 'this week news',
month: 'this month news'
};
const query = `${topic} ${timeKeywords[timeframe] || timeKeywords.recent}`;
const results = await zai.functions.invoke('web_search', {
query: query,
num: 10
});
// Sort by date (most recent first)
const sortedResults = results.sort((a, b) => {
return new Date(b.date) - new Date(a.date);
});
return sortedResults;
}
// Usage
const aiNews = await searchNews('artificial intelligence', 'today');
const techNews = await searchNews('technology', 'week');
console.log('Latest AI News:');
aiNews.forEach(item => {
console.log(`${item.name} (${item.date})`);
console.log(`${item.snippet}\n`);
});
研究助手
import ZAI from 'z-ai-web-dev-sdk';
class ResearchAssistant {
constructor() {
this.zai = null;
}
async initialize() {
this.zai = await ZAI.create();
}
async researchTopic(topic, depth = 'standard') {
const numResults = {
quick: 5,
standard: 10,
deep: 20
};
const results = await this.zai.functions.invoke('web_search', {
query: topic,
num: numResults[depth] || 10
});
// Analyze results
const analysis = {
topic: topic,
totalResults: results.length,
sources: this.extractDomains(results),
topResults: results.slice(0, 5).map(r => ({
title: r.name,
url: r.url,
summary: r.snippet
})),
dateRange: this.getDateRange(results)
};
return analysis;
}
extractDomains(results) {
const domains = {};
results.forEach(item => {
domains[item.host_name] = (domains[item.host_name] || 0) + 1;
});
return domains;
}
getDateRange(results) {
const dates = results
.map(r => new Date(r.date))
.filter(d => !isNaN(d));
if (dates.length === 0) return null;
return {
earliest: new Date(Math.min(...dates)),
latest: new Date(Math.max(...dates))
};
}
async compareTopics(topic1, topic2) {
const [results1, results2] = await Promise.all([
this.zai.functions.invoke('web_search', { query: topic1, num: 10 }),
this.zai.functions.invoke('web_search', { query: topic2, num: 10 })
]);
const domains1 = new Set(results1.map(r => r.host_name));
const domains2 = new Set(results2.map(r => r.host_name));
const commonDomains = [...domains1].filter(d => domains2.has(d));
return {
topic1: {
name: topic1,
results: results1.length,
uniqueDomains: domains1.size
},
topic2: {
name: topic2,
results: results2.length,
uniqueDomains: domains2.size
},
commonDomains: commonDomains
};
}
}
// Usage
const assistant = new ResearchAssistant();
await assistant.initialize();
const research = await assistant.researchTopic('quantum computing', 'deep');
console.log('Research Analysis:', research);
const comparison = await assistant.compareTopics(
'renewable energy',
'solar power'
);
console.log('Topic Comparison:', comparison);
搜索结果验证
import ZAI from 'z-ai-web-dev-sdk';
async function validateSearchResults(query) {
const zai = await ZAI.create();
const results = await zai.functions.invoke('web_search', {
query: query,
num: 10
});
// Validate and score results
const validated = results.map(item => {
let score = 0;
let flags = [];
// Check snippet quality
if (item.snippet && item.snippet.length > 50) {
score += 20;
} else {
flags.push('short_snippet');
}
// Check date availability
if (item.date && item.date !== 'N/A') {
score += 20;
} else {
flags.push('no_date');
}
// Check URL validity
try {
new URL(item.url);
score += 20;
} catch (e) {
flags.push('invalid_url');
}
// Check domain quality (not perfect, but basic check)
if (!item.host_name.includes('spam') &&
!item.host_name.includes('ads')) {
score += 20;
} else {
flags.push('suspicious_domain');
}
// Check title quality
if (item.name && item.name.length > 10) {
score += 20;
} else {
flags.push('short_title');
}
return {
...item,
qualityScore: score,
validationFlags: flags,
isHighQuality: score >= 80
};
});
// Sort by quality score
return validated.sort((a, b) => b.qualityScore - a.qualityScore);
}
// Usage
const validated = await validateSearchResults('best programming practices');
console.log('High quality results:',
validated.filter(r => r.isHighQuality).length
);
最佳实践
1. 查询优化
// Bad: Too vague
const bad = await searchWeb('information');
// Good: Specific and targeted
const good = await searchWeb('JavaScript async/await best practices 2024');
// Good: Include context
const goodWithContext = await searchWeb('React hooks tutorial for beginners');
2. 错误处理
import ZAI from 'z-ai-web-dev-sdk';
async function safeSearch(query, retries = 3) {
let lastError;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const zai = await ZAI.create();
const results = await zai.functions.invoke('web_search', {
query: query,
num: 10
});
if (!Array.isArray(results) || results.length === 0) {
throw new Error('No results found or invalid response');
}
return {
success: true,
results: results,
attempts: attempt
};
} catch (error) {
lastError = error;
console.error(`Attempt ${attempt} failed:`, error.message);
if (attempt < retries) {
// Wait before retry (exponential backoff)
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
return {
success: false,
error: lastError.message,
attempts: retries
};
}
3. 结果缓存
import ZAI from 'z-ai-web-dev-sdk';
class CachedSearch {
constructor(cacheDuration = 3600000) { // 1 hour default
this.cache = new Map();
this.cacheDuration = cacheDuration;
this.zai = null;
}
async initialize() {
this.zai = await ZAI.create();
}
getCacheKey(query, num) {
return `${query}_${num}`;
}
async search(query, num = 10) {
const cacheKey = this.getCacheKey(query, num);
const cached = this.cache.get(cacheKey);
// Check if cached and not expired
if (cached && Date.now() - cached.timestamp < this.cacheDuration) {
console.log('Returning cached results');
return {
...cached.data,
cached: true
};
}
// Perform fresh search
const results = await this.zai.functions.invoke('web_search', {
query: query,
num: num
});
// Cache results
this.cache.set(cacheKey, {
data: results,
timestamp: Date.now()
});
return {
results: results,
cached: false
};
}
clearCache() {
this.cache.clear();
}
getCacheSize() {
return this.cache.size;
}
}
// Usage
const search = new CachedSearch(1800000); // 30 minutes cache
await search.initialize();
const result1 = await search.search('TypeScript tutorial');
console.log('Cached:', result1.cached); // false
const result2 = await search.search('TypeScript tutorial');
console.log('Cached:', result2.cached); // true
4. 速率限制
class RateLimitedSearch {
constructor(requestsPerMinute = 60) {
this.zai = null;
this.requestsPerMinute = requestsPerMinute;
this.requests = [];
}
async initialize() {
this.zai = await ZAI.create();
}
async search(query, num = 10) {
await this.checkRateLimit();
const results = await this.zai.functions.invoke('web_search', {
query: query,
num: num
});
this.requests.push(Date.now());
return results;
}
async checkRateLimit() {
const now = Date.now();
const oneMinuteAgo = now - 60000;
// Remove requests older than 1 minute
this.requests = this.requests.filter(time => time > oneMinuteAgo);
if (this.requests.length >= this.requestsPerMinute) {
const oldestRequest = this.requests[0];
const waitTime = 60000 - (now - oldestRequest);
console.log(`Rate limit reached. Waiting ${waitTime}ms`);
await new Promise(resolve => setTimeout(resolve, waitTime));
// Recheck after waiting
return this.checkRateLimit();
}
}
}
常见用例
- 实时信息检索:获取当前新闻、股票价格、天气
- 研究与分析:收集特定主题的信息
- 内容发现:查找文章、教程、文档
- 竞品分析:研究竞争对手和市场趋势
- 事实核查:对照网页来源核实信息
- SEO 与内容研究:分析搜索结果以制定内容策略
- 新闻聚合:从各种来源收集新闻
- 学术研究:查找论文、研究和学术内容
集成示例
Express.js 搜索 API
import express from 'express';
import ZAI from 'z-ai-web-dev-sdk';
const app = express();
app.use(express.json());
let zaiInstance;
async function initZAI() {
zaiInstance = await ZAI.create();
}
app.get('/api/search', async (req, res) => {
try {
const { q: query, num = 10 } = req.query;
if (!query) {
return res.status(400).json({ error: 'Query parameter "q" is required' });
}
const numResults = Math.min(parseInt(num) || 10, 20);
const results = await zaiInstance.functions.invoke('web_search', {
query: query,
num: numResults
});
res.json({
success: true,
query: query,
totalResults: results.length,
results: results
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.get('/api/search/news', async (req, res) => {
try {
const { topic, timeframe = 'recent' } = req.query;
if (!topic) {
return res.status(400).json({ error: 'Topic parameter is required' });
}
const timeKeywords = {
recent: 'latest news',
today: 'today news',
week: 'this week news'
};
const query = `${topic} ${timeKeywords[timeframe] || timeKeywords.recent}`;
const results = await zaiInstance.functions.invoke('web_search', {
query: query,
num: 15
});
// Sort by date
const sortedResults = results.sort((a, b) => {
return new Date(b.date) - new Date(a.date);
});
res.json({
success: true,
topic: topic,
timeframe: timeframe,
results: sortedResults
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
initZAI().then(() => {
app.listen(3000, () => {
console.log('Search API running on port 3000');
});
});
带 AI 摘要的搜索
import ZAI from 'z-ai-web-dev-sdk';
async function searchAndSummarize(query) {
const zai = await ZAI.create();
// Step 1: Search the web
const searchResults = await zai.functions.invoke('web_search', {
query: query,
num: 10
});
// Step 2: Create summary using chat completions
const searchContext = searchResults
.slice(0, 5)
.map((r, i) => `${i + 1}. ${r.name}\n${r.snippet}`)
.join('\n\n');
const completion = await zai.chat.completions.create({
messages: [
{
role: 'assistant',
content: 'You are a research assistant. Summarize search results clearly and concisely.'
},
{
role: 'user',
content: `Query: "${query}"\n\nSearch Results:\n${searchContext}\n\nProvide a comprehensive summary of these results.`
}
],
thinking: { type: 'disabled' }
});
const summary = completion.choices[0]?.message?.content;
return {
query: query,
summary: summary,
sources: searchResults.slice(0, 5).map(r => ({
title: r.name,
url: r.url
})),
totalResults: searchResults.length
};
}
// Usage
const result = await searchAndSummarize('benefits of renewable energy');
console.log('Summary:', result.summary);
console.log('Sources:', result.sources);
故障排除
问题:"SDK 必须在后端使用"
- 解决方案:确保 z-ai-web-dev-sdk 仅在服务端代码中导入和使用
问题:返回空结果或无结果
- 解决方案:尝试不同的查询词,检查网络连接,验证 API 状态
问题:响应格式不符合预期
- 解决方案:验证响应是否为数组,检查 API 是否变更,添加类型校验
问题:限流错误
- 解决方案:实现请求节流,在搜索之间添加延迟,使用缓存
问题:搜索结果质量低
- 解决方案:优化查询词,按域名或日期筛选结果,验证结果质量
性能建议
- 复用 SDK 实例:创建一次 ZAI 实例并在多次搜索中复用
- 实现缓存:缓存搜索结果以减少 API 调用
- 优化查询词:使用具体、有针对性的查询以获得更好的结果
- 限制结果数量:只请求你需要的数量
- 并行搜索:对多个独立搜索使用 Promise.all
- 结果过滤:尽可能在客户端侧过滤结果
安全注意事项
- 输入校验:清理并校验用户的搜索查询
- 限流:实现速率限制以防止滥用
- API 密钥保护:切勿在客户端侧代码中暴露 SDK 凭据
- 结果过滤:过滤潜在有害或不适宜的内容
- URL 校验:在将用户重定向之前验证 URL
- 隐私:不要记录敏感的用户搜索查询
请记住
- 始终仅在后端代码中使用 z-ai-web-dev-sdk
- SDK 已安装——按示例所示导入
- 搜索结果以 SearchFunctionResultItem 对象的数组形式返回
- 为生产环境实现适当的错误处理和重试
- 在适当的时候缓存结果以减少 API 调用
- 使用具体的查询词以获得更好的搜索结果
- 在向用户显示之前校验并过滤结果
- 查看
scripts/web_search.ts获取快速入门示例
评论
支持 Markdown