修:安卓端文件上传一直是坏的(字段名对不上)+ 新增通用联网搜索工具
【一、文件上传:客户端和内核的字段名不一致】
用户报"无法上传文件"。真机上查下来是两层问题。
第 1 层:选择器被抢
GetContent() 用的是 ACTION_GET_CONTENT,**任何 App 都能注册这个 intent**。
实测在真机上点「附件」直接打开了豆包 App 的拍照界面
(com.larus.nova/…CameraCaptureActivity),压根选不到文件。
改用 OpenDocument()(ACTION_OPEN_DOCUMENT),只有系统文档提供者能响应,
抢不走,顺带拿到长期可读权限。改完在真机上打开的是 ColorOS 文件选择器。
第 2 层:字段名对不上(这才是"上传失败"的真身)
客户端发 {"name":…, "data": dataUrl}
Python 内核收 body.get('dataUrl') or body.get('base64')
Node 内核收 body.dataUrl || body.base64
两边都拿不到 → 内核报"缺少 name 或 base64" → 返回 400 →
客户端只看 "file" 在不在 → 一句没有原因的"上传失败"。
**安卓端的上传因此一直是坏的**,不是实体机特有的问题,只是之前没端到端测过。
修:客户端改发 dataUrl;两份内核额外兼容 data(已经装在手机上的旧版本还能用);
客户端失败时把内核的原话抛出来 —— 字段名这种错本该一眼看穿,不该查半天。
第 3 层:读文件放 IO 线程
回调本身跑在主线程,readBytes() 一张几 MB 的照片就会掉帧甚至 ANR。
顺带把文件名改成查 OpenableColumns.DISPLAY_NAME —— 文档 URI 的
lastPathSegment 是 "image:1234" 这种内部 id,不是文件名。
另外 bytes 为 null 时以前是**静默什么都不做**,现在每种失败都有明确提示。
排查过程的教训(写进 README 吧):这台 ROM 把应用日志全吞了,
logcat 里一条 app 记录都没有,只能靠"选完立刻截图"去抓那个只活 2.5 秒的提示条
才看到"上传失败"四个字。**提示条 2.5 秒对错误信息太短了**,后面要改长。
【二、通用联网搜索工具 tools/web_search.py】
用户要"所有模型都能用的搜索工具"。
火山方舟的 web_search 只有它自己有,而且只能走 Responses API,换一家就没有。
做成**函数调用工具**就十家一视同仁 —— 函数调用是 OpenAI 兼容接口的公共部分。
- 零依赖、不需要 Key:默认走 Bing / DuckDuckGo 的公开结果页
- 后端顺序有讲究:**Bing 在前**。DuckDuckGo 国内基本连不上,
拿它当第一选择会让每次搜索先白等一次超时
- 配了 TAVILY_API_KEY / BRAVE_API_KEY 就自动升级到它(质量明显更好)
- 全挂时报清楚每个后端为什么挂 —— 尤其"连不上"和"没搜到"是两件事,
不能让模型误以为是没有结果
- 顺带剥掉 Bing/DuckDuckGo 的跳转包装,给模型的是真实地址
实测:PC 上搜"DeepSeek 最新模型"拿到 4 条真实结果;
真机上(安卓 App 内)搜"今天有什么科技新闻"也拿到 3 条,后端都是 bing。
回归:Markdown 对拍 19/19、语音验收 36/36。
This commit is contained in:
@@ -300,11 +300,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
val file = withContext(Dispatchers.IO) { client.uploadFile(name, mime, bytes, false) }
|
val file = withContext(Dispatchers.IO) { client.uploadFile(name, mime, bytes, false) }
|
||||||
|
// uploadFile 现在失败会抛异常并带上内核原话,所以走到这儿基本就是成功;
|
||||||
|
// 留个兜底是因为万一内核换了个返回形状,也不能静默什么都不做
|
||||||
if (file != null) {
|
if (file != null) {
|
||||||
addAttachment(file)
|
addAttachment(file)
|
||||||
showHint("已添加 ${file.name}")
|
showHint("已添加 ${file.name}")
|
||||||
} else {
|
} else {
|
||||||
showHint("上传失败")
|
showHint("上传失败:内核没有返回文件信息")
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showHint("上传失败:${e.message}")
|
showHint("上传失败:${e.message}")
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import androidx.activity.compose.rememberLauncherForActivityResult
|
|||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import android.util.Log
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.core.animateFloatAsState
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
import androidx.compose.animation.core.tween
|
import androidx.compose.animation.core.tween
|
||||||
@@ -53,9 +55,20 @@ import androidx.compose.ui.unit.sp
|
|||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import com.doubao.lynxclone.data.ChatMessage
|
import com.doubao.lynxclone.data.ChatMessage
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import com.doubao.lynxclone.speech.SpeechController
|
import com.doubao.lynxclone.speech.SpeechController
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
|
private const val TAG = "ChatScreen"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 附件大小上限。和内核对齐:uploads.COPY_LIMIT 是 25MB,
|
||||||
|
* 而 base64 会让体积涨 1/3,正好卡在 /api/upload 那条 40MB 的请求体上限内。
|
||||||
|
* 客户端先挡一道,免得几 MB 的流量白传一趟再被拒。
|
||||||
|
*/
|
||||||
|
private const val MAX_UPLOAD_BYTES = 25 * 1024 * 1024
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对话页。
|
* 对话页。
|
||||||
*
|
*
|
||||||
@@ -105,21 +118,65 @@ fun ChatScreen(vm: AppViewModel) {
|
|||||||
val listState = rememberLazyListState()
|
val listState = rememberLazyListState()
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|
||||||
val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
// ★ 必须声明在 picker 之前:picker 的回调要捕获它
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
|
// ★ 用 OpenDocument 而不是 GetContent。
|
||||||
|
//
|
||||||
|
// GetContent 走的是 ACTION_GET_CONTENT —— **任何 App 都能注册这个 intent**。
|
||||||
|
// 实测在真机上点「附件」直接打开了豆包 App 的拍照界面
|
||||||
|
// (com.larus.nova/…CameraCaptureActivity),压根选不到文件,
|
||||||
|
// 这就是"无法上传文件"的直接原因。
|
||||||
|
//
|
||||||
|
// OpenDocument 走 ACTION_OPEN_DOCUMENT,只有系统文档提供者(文件/相册)能响应,
|
||||||
|
// 抢不走;顺带还拿到长期可读权限。
|
||||||
|
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
if (uri == null) return@rememberLauncherForActivityResult
|
if (uri == null) return@rememberLauncherForActivityResult
|
||||||
|
scope.launch {
|
||||||
|
// 读文件放 IO 线程:手机上随手一张照片就几 MB,在主线程 readBytes
|
||||||
|
// 轻则掉帧重则 ANR。回调本身是在主线程跑的。
|
||||||
|
val picked = withContext(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
val name = uri.lastPathSegment?.substringAfterLast('/') ?: "upload"
|
val resolver = context.contentResolver
|
||||||
val mime = context.contentResolver.getType(uri) ?: "application/octet-stream"
|
// 文件名必须查 OpenableColumns:文档 URI 的 lastPathSegment 是
|
||||||
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
// "image:1234" 这种内部 id,不是文件名,直接拿来当文件名会很难看
|
||||||
if (bytes != null) vm.uploadAndAttach(name, mime, bytes)
|
val display = runCatching {
|
||||||
|
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||||
|
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||||
|
}.getOrNull()
|
||||||
|
val name = display?.takeIf { it.isNotBlank() }
|
||||||
|
?: uri.lastPathSegment?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
|
||||||
|
?: "upload"
|
||||||
|
val mime = resolver.getType(uri) ?: "application/octet-stream"
|
||||||
|
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||||
|
Log.i(TAG, "选到文件 name=$name mime=$mime size=${bytes?.size ?: -1}")
|
||||||
|
Triple(name, mime, bytes)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
vm.showHint("读取文件失败:${e.message}")
|
Log.w(TAG, "读文件失败", e)
|
||||||
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val onPickFile: () -> Unit = { picker.launch("*/*") }
|
|
||||||
|
if (picked == null) {
|
||||||
|
vm.showHint("读取文件失败,换个文件试试")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val (name, mime, bytes) = picked
|
||||||
|
// 以前 bytes 为 null 时是**静默什么都不做**的 —— 用户点了半天没反应也没提示。
|
||||||
|
// 每种失败都得说清楚。
|
||||||
|
when {
|
||||||
|
bytes == null -> vm.showHint("打不开这个文件(可能已被移动或没有权限)")
|
||||||
|
bytes.isEmpty() -> vm.showHint("「$name」是空文件")
|
||||||
|
bytes.size > MAX_UPLOAD_BYTES ->
|
||||||
|
vm.showHint("「$name」${bytes.size / 1024 / 1024}MB,超过了 ${MAX_UPLOAD_BYTES / 1024 / 1024}MB 上限")
|
||||||
|
else -> vm.uploadAndAttach(name, mime, bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// OpenDocument 要的是 MIME 数组,不是单个字符串
|
||||||
|
val onPickFile: () -> Unit = { picker.launch(arrayOf("*/*")) }
|
||||||
|
|
||||||
// ---------------- 语音 ----------------
|
// ---------------- 语音 ----------------
|
||||||
val scope = rememberCoroutineScope()
|
|
||||||
val speech = remember { SpeechController(context, vm.client, scope) }
|
val speech = remember { SpeechController(context, vm.client, scope) }
|
||||||
DisposableEffect(Unit) {
|
DisposableEffect(Unit) {
|
||||||
onDispose { speech.release() }
|
onDispose { speech.release() }
|
||||||
|
|||||||
@@ -708,7 +708,13 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
if pathname == '/api/upload' and method == 'POST':
|
if pathname == '/api/upload' and method == 'POST':
|
||||||
body = self.read_json_body(40 * 1024 * 1024)
|
body = self.read_json_body(40 * 1024 * 1024)
|
||||||
try:
|
try:
|
||||||
item = uploads.save_upload(body.get('name'), body.get('dataUrl') or body.get('base64'))
|
# 三个字段名都收:dataUrl 是约定名,base64 是历史名,
|
||||||
|
# data 是安卓客户端曾经错发过的名字 —— 收下它,
|
||||||
|
# 免得已经装在手机上的旧版本一直传不上来。
|
||||||
|
item = uploads.save_upload(
|
||||||
|
body.get('name'),
|
||||||
|
body.get('dataUrl') or body.get('base64') or body.get('data'),
|
||||||
|
)
|
||||||
if body.get('pending'):
|
if body.get('pending'):
|
||||||
uploads.add_pending([item])
|
uploads.add_pending([item])
|
||||||
self.send_json(200, {'ok': True, 'file': item})
|
self.send_json(200, {'ok': True, 'file': item})
|
||||||
|
|||||||
@@ -644,7 +644,9 @@ async function handleApi(req, res, url) {
|
|||||||
if (pathname === '/api/upload' && method === 'POST') {
|
if (pathname === '/api/upload' && method === 'POST') {
|
||||||
const body = await readBody(req, 40 * 1024 * 1024);
|
const body = await readBody(req, 40 * 1024 * 1024);
|
||||||
try {
|
try {
|
||||||
const item = saveUpload({ name: body.name, base64: body.dataUrl || body.base64 });
|
// 三个字段名都收:dataUrl 是约定名,base64 是历史名,
|
||||||
|
// data 是安卓客户端曾经错发过的名字 —— 收下它,免得旧版本一直传不上来
|
||||||
|
const item = saveUpload({ name: body.name, base64: body.dataUrl || body.base64 || body.data });
|
||||||
if (body.pending) addPending([item]);
|
if (body.pending) addPending([item]);
|
||||||
sendJson(res, 200, { ok: true, file: item });
|
sendJson(res, 200, { ok: true, file: item });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
222
tools/web_search.py
Normal file
222
tools/web_search.py
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
"""联网搜索工具:给模型真正能用的"搜一下"。
|
||||||
|
|
||||||
|
为什么要做成工具而不是内置能力:
|
||||||
|
火山方舟的 web_search 只有它自己有,而且只能走 Responses API;
|
||||||
|
换到 DeepSeek / Kimi / 智谱 / 本地 Ollama 就没了。
|
||||||
|
做成函数调用工具之后,**十家提供商一视同仁** —— 因为函数调用是
|
||||||
|
OpenAI 兼容接口的公共部分,谁家都支持。
|
||||||
|
|
||||||
|
不依赖任何第三方库,也不需要 Key(默认走 Bing / DuckDuckGo 的公开页面)。
|
||||||
|
想更稳的话可以在内核数据目录的 .env 里配一个搜索 API:
|
||||||
|
TAVILY_API_KEY=... 或
|
||||||
|
BRAVE_API_KEY=...
|
||||||
|
配了就用它(结果质量明显更好),没配就退回免费后端。
|
||||||
|
|
||||||
|
后端顺序是有讲究的:**Bing 放前面**,因为 DuckDuckGo 在国内基本连不上,
|
||||||
|
拿它当第一选择会让每次搜索都先白等一次超时。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import html
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
from _protocol import serve # noqa: E402
|
||||||
|
|
||||||
|
TOOL = {
|
||||||
|
"name": "web_search",
|
||||||
|
"description": (
|
||||||
|
"联网搜索。查最新消息、实时数据、你不确定的事实、或者超出训练时间的内容时用它。"
|
||||||
|
"返回若干条结果的标题、链接和摘要;需要看某条详情再用 web_fetch 打开链接。"
|
||||||
|
),
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"query": {"type": "string", "description": "搜索词,像人在搜索框里打的那样,别写成一整句话"},
|
||||||
|
"count": {"type": "number", "description": "返回几条结果,默认 6,最多 10"},
|
||||||
|
},
|
||||||
|
"required": ["query"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
UA = (
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
|
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36"
|
||||||
|
)
|
||||||
|
TIMEOUT = 20
|
||||||
|
SCRIPT_RE = re.compile(r"<(script|style|noscript)[^>]*>.*?</\1>", re.S | re.I)
|
||||||
|
TAG_RE = re.compile(r"<[^>]+>")
|
||||||
|
|
||||||
|
|
||||||
|
def _get(url, headers=None, data=None, timeout=TIMEOUT):
|
||||||
|
req = urllib.request.Request(url, data=data, method="POST" if data else "GET")
|
||||||
|
req.add_header("User-Agent", UA)
|
||||||
|
req.add_header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||||
|
for key, value in (headers or {}).items():
|
||||||
|
req.add_header(key, value)
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||||
|
charset = resp.headers.get_content_charset() or "utf-8"
|
||||||
|
return resp.read(2_000_000).decode(charset, errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
def _text(fragment):
|
||||||
|
"""把一小段 HTML 变成纯文本"""
|
||||||
|
return html.unescape(TAG_RE.sub("", SCRIPT_RE.sub(" ", fragment))).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_url(url):
|
||||||
|
"""Bing / DuckDuckGo 都会把真实地址藏在跳转参数里,剥出来"""
|
||||||
|
if not url:
|
||||||
|
return ""
|
||||||
|
url = html.unescape(url)
|
||||||
|
if url.startswith("//"):
|
||||||
|
url = "https:" + url
|
||||||
|
# duckduckgo: /l/?uddg=<百分号编码的真实地址>
|
||||||
|
if "uddg=" in url:
|
||||||
|
query = urllib.parse.urlparse(url).query
|
||||||
|
real = urllib.parse.parse_qs(query).get("uddg")
|
||||||
|
if real:
|
||||||
|
return real[0]
|
||||||
|
# bing: https://www.bing.com/ck/a?...&u=a1<base64>
|
||||||
|
if "bing.com/ck/a" in url:
|
||||||
|
query = urllib.parse.urlparse(url).query
|
||||||
|
raw = urllib.parse.parse_qs(query).get("u", [""])[0]
|
||||||
|
if raw.startswith("a1"):
|
||||||
|
import base64
|
||||||
|
try:
|
||||||
|
padded = raw[2:] + "=" * (-len(raw[2:]) % 4)
|
||||||
|
return base64.urlsafe_b64decode(padded).decode("utf-8", "replace")
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 各后端:都返回 [{title, url, snippet}],失败就抛异常由上层换下一个
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def _search_tavily(query, count):
|
||||||
|
key = (os.environ.get("TAVILY_API_KEY") or "").strip()
|
||||||
|
if not key:
|
||||||
|
raise RuntimeError("没配 TAVILY_API_KEY")
|
||||||
|
payload = json.dumps({
|
||||||
|
"api_key": key,
|
||||||
|
"query": query,
|
||||||
|
"max_results": count,
|
||||||
|
"search_depth": "basic",
|
||||||
|
}).encode("utf-8")
|
||||||
|
raw = _get("https://api.tavily.com/search", {"Content-Type": "application/json"}, payload)
|
||||||
|
data = json.loads(raw)
|
||||||
|
return [
|
||||||
|
{"title": it.get("title", ""), "url": it.get("url", ""), "snippet": it.get("content", "")}
|
||||||
|
for it in (data.get("results") or [])[:count]
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _search_brave(query, count):
|
||||||
|
key = (os.environ.get("BRAVE_API_KEY") or "").strip()
|
||||||
|
if not key:
|
||||||
|
raise RuntimeError("没配 BRAVE_API_KEY")
|
||||||
|
url = "https://api.search.brave.com/res/v1/web/search?" + urllib.parse.urlencode(
|
||||||
|
{"q": query, "count": count}
|
||||||
|
)
|
||||||
|
raw = _get(url, {"Accept": "application/json", "X-Subscription-Token": key})
|
||||||
|
data = json.loads(raw)
|
||||||
|
items = ((data.get("web") or {}).get("results") or [])[:count]
|
||||||
|
return [
|
||||||
|
{"title": it.get("title", ""), "url": it.get("url", ""), "snippet": it.get("description", "")}
|
||||||
|
for it in items
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _search_bing(query, count):
|
||||||
|
"""Bing 的公开结果页。国内可直连,所以放在免费后端的第一位。"""
|
||||||
|
url = "https://cn.bing.com/search?" + urllib.parse.urlencode({"q": query, "setlang": "zh-CN"})
|
||||||
|
page = _get(url)
|
||||||
|
out = []
|
||||||
|
# <li class="b_algo"> 里是 <h2><a href>标题</a></h2> 和一段摘要
|
||||||
|
for block in re.findall(r'<li class="b_algo".*?</li>', page, re.S)[: count * 2]:
|
||||||
|
link = re.search(r'<h2[^>]*>\s*<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', block, re.S)
|
||||||
|
if not link:
|
||||||
|
continue
|
||||||
|
snippet = ""
|
||||||
|
cap = re.search(r'<p[^>]*>(.*?)</p>', block, re.S)
|
||||||
|
if cap:
|
||||||
|
snippet = _text(cap.group(1))
|
||||||
|
out.append({
|
||||||
|
"title": _text(link.group(2)),
|
||||||
|
"url": _clean_url(link.group(1)),
|
||||||
|
"snippet": snippet,
|
||||||
|
})
|
||||||
|
if len(out) >= count:
|
||||||
|
break
|
||||||
|
if not out:
|
||||||
|
raise RuntimeError("Bing 没解析出结果(页面结构可能变了)")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _search_duckduckgo(query, count):
|
||||||
|
"""DuckDuckGo 的 HTML 版。结果质量好,但国内基本连不上,所以放第二位。"""
|
||||||
|
payload = urllib.parse.urlencode({"q": query, "kl": "cn-zh"}).encode("utf-8")
|
||||||
|
page = _get("https://html.duckduckgo.com/html/", {"Content-Type": "application/x-www-form-urlencoded"}, payload)
|
||||||
|
out = []
|
||||||
|
for block in re.findall(r'<div class="result[^"]*".*?</div>\s*</div>', page, re.S)[: count * 2]:
|
||||||
|
link = re.search(r'<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>', block, re.S)
|
||||||
|
if not link:
|
||||||
|
continue
|
||||||
|
snip = re.search(r'class="result__snippet"[^>]*>(.*?)</a>', block, re.S)
|
||||||
|
out.append({
|
||||||
|
"title": _text(link.group(2)),
|
||||||
|
"url": _clean_url(link.group(1)),
|
||||||
|
"snippet": _text(snip.group(1)) if snip else "",
|
||||||
|
})
|
||||||
|
if len(out) >= count:
|
||||||
|
break
|
||||||
|
if not out:
|
||||||
|
raise RuntimeError("DuckDuckGo 没解析出结果")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
BACKENDS = [
|
||||||
|
("tavily", _search_tavily),
|
||||||
|
("brave", _search_brave),
|
||||||
|
("bing", _search_bing),
|
||||||
|
("duckduckgo", _search_duckduckgo),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(args):
|
||||||
|
query = str(args.get("query", "")).strip()
|
||||||
|
if not query:
|
||||||
|
raise ValueError("query 不能为空")
|
||||||
|
count = max(1, min(10, int(args.get("count", 6) or 6)))
|
||||||
|
|
||||||
|
tried = []
|
||||||
|
for name, fn in BACKENDS:
|
||||||
|
try:
|
||||||
|
results = fn(query, count)
|
||||||
|
if results:
|
||||||
|
return {
|
||||||
|
"query": query,
|
||||||
|
"backend": name,
|
||||||
|
"count": len(results),
|
||||||
|
"results": results,
|
||||||
|
# 提醒模型:摘要可能不全,需要细节就用 web_fetch 打开链接
|
||||||
|
"note": "摘要可能不完整;要看某条的具体内容,用 web_fetch 打开它的 url。",
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
tried.append(f"{name}: {exc}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 全挂了就说清楚每个为什么挂 —— 尤其国内访问不了 DuckDuckGo 是常态,
|
||||||
|
# 别让模型以为是"没搜到结果"(那是完全不同的两件事)
|
||||||
|
raise RuntimeError("所有搜索后端都失败了 → " + ";".join(tried))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
serve(TOOL, run)
|
||||||
Reference in New Issue
Block a user