@morlay/dsh-web-access 0.0.0-stage → 0.2.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +22 -2
- package/dist/index.d.mts +60 -0
- package/dist/index.mjs +1 -0
- package/dist/server.d.mts +25 -0
- package/dist/server.mjs +30 -0
- package/dist/web-search-ollama.service-CSgHrsdE.mjs +219 -0
- package/dist/web-search-ollama.service-CUYZ3qmj.d.mts +68 -0
- package/package.json +43 -3
- package/src/contract/index.ts +2 -0
- package/src/contract/web.contract.ts +34 -0
- package/src/index.ts +9 -0
- package/src/server/index.ts +3 -0
- package/src/server/tool-web.provide.ts +10 -0
- package/src/server/tool-web.service.ts +23 -0
- package/src/server/web.provide.ts +15 -0
- package/src/web-fetch-http.service.ts +25 -0
- package/src/web-search-deepseek.service.ts +21 -0
- package/src/web-search-ollama.provider.ts +210 -0
- package/src/web-search-ollama.service.ts +42 -0
- package/src/web.service.ts +26 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 morlay
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @morlay/dsh-web-access
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
联网访问:搜索与抓取两个后端、一个 `Web` 契约,以及给模型的 web 工具行。
|
|
4
|
+
|
|
5
|
+
## 用法
|
|
6
|
+
|
|
7
|
+
- 导出:`Web` 契约与 `WebDefault`,两个后端行 `WebSearchDeepseek` / `WebFetchHttp`。
|
|
8
|
+
- 装配:`WebModule`;工具行 `ToolWeb` 从包根拿(`./server` 子出口已删——它零消费方)。
|
|
9
|
+
|
|
10
|
+
## 事实
|
|
11
|
+
|
|
12
|
+
- `WebFetchHttp` 是上游 `@deepseek-ai/dsh-web-fetch-http` 的一行适配:抓取的行为(协议/长度/凭据检查、同源重定向、字节与字符上限、超时)全在上游,本包不叠加策略。上游 0.2.2 的 fetch 不做地址策略,所以抓内网地址在这里表现为连接失败——这是上游的现状,不是本包的取舍。
|
|
13
|
+
- 行不走上游的 schemastery 解析,所以 `mount` 的 config 显式给同一组默认值(见 `web-fetch-http.service.ts`)。
|
|
14
|
+
|
|
15
|
+
## 已知债
|
|
16
|
+
|
|
17
|
+
- 本包有一个**自实现的后端**(不在上面的「用法」里):Ollama 搜索后端 `OllamaSearchProvider` + 注册行 `WebSearchOllama` +
|
|
18
|
+
`provideWebAccess()` 里被钉死的默认后端(`searchProvider: "ollama"`)。上游没有这个包、`searchProvider` 在上游也没有默认值,
|
|
19
|
+
所以它属于扩展形态而不属于这一层:为什么、以及销账条件见[债 20261122-适配层里自实现的能力](../.agents/debts/20261122-适配层里自实现的能力.md)。
|
|
20
|
+
|
|
21
|
+
## 设计
|
|
22
|
+
|
|
23
|
+
包内子域怎么分、契约与行各放哪,见[包内子域拆分与注册抽象](../.agents/designs/20261028-包内子域拆分与注册抽象.md)。
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { _ as WebCovered, a as WebSearchDeepseek, c as WebFetchProvider, d as WebRuntime, f as WebSearchProvider, g as Web, h as WebSearchSource, i as WebFetchHttp, l as WebFetchRequest, m as WebSearchResult, n as WebSearchOllamaConfig, o as WebDefault, p as WebSearchRequest, r as ToolWeb, s as WebError, t as WebSearchOllama, u as WebFetchResult } from "./web-search-ollama.service-CUYZ3qmj.mjs";
|
|
2
|
+
/** 注册进 `ctx.web` 的 id;与 llm route 同名,配置里看到的就是同一个 "ollama"。 */
|
|
3
|
+
export declare const OLLAMA_PROVIDER_ID = "ollama";
|
|
4
|
+
/** 默认端点;`/api/web_search` 是操作。 */
|
|
5
|
+
export declare const OLLAMA_DEFAULT_BASE_URL = "https://ollama.com";
|
|
6
|
+
/** Ollama `max_results` 的硬上限;超过它的值不发给服务端。 */
|
|
7
|
+
export declare const OLLAMA_MAX_RESULTS_LIMIT = 10;
|
|
8
|
+
/** `POST /api/web_search` 的一条结果;字段都可能缺失或为空串。 */
|
|
9
|
+
interface OllamaSearchResult {
|
|
10
|
+
readonly title?: string | null;
|
|
11
|
+
readonly url?: string | null;
|
|
12
|
+
readonly content?: string | null;
|
|
13
|
+
}
|
|
14
|
+
/** 成功信封。 */
|
|
15
|
+
interface OllamaSearchResponse {
|
|
16
|
+
readonly results?: readonly OllamaSearchResult[];
|
|
17
|
+
}
|
|
18
|
+
/** 构造参数。 */
|
|
19
|
+
export interface OllamaSearchProviderOptions {
|
|
20
|
+
/** 字面 key;给了就压过 `apiKeyEnv`。 */
|
|
21
|
+
readonly apiKey?: string | undefined;
|
|
22
|
+
/** 取不到 key 时报出来的变量名,便于用户知道去哪配。 */
|
|
23
|
+
readonly apiKeyEnv: string;
|
|
24
|
+
/** 端点根。 */
|
|
25
|
+
readonly baseURL: string;
|
|
26
|
+
/** 请求没带 `maxResults` 时的默认值;省略表示让 Ollama 用自己的默认。 */
|
|
27
|
+
readonly maxResults?: number | undefined;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* 一条 Ollama 结果 → 一个 source;没有 url 就丢掉(seam 的 source 必须有 url)。
|
|
31
|
+
* @param result - Ollama 的一条结果。
|
|
32
|
+
* @returns 归一化的 source,或 `undefined`。
|
|
33
|
+
*/
|
|
34
|
+
export declare function mapOllamaResult(result: OllamaSearchResult): WebSearchSource | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* 响应信封 → 归一化结果;形状不对就抛(由调用方包成 `WEB_PROVIDER_ERROR`)。
|
|
37
|
+
* @param response - Ollama 的响应体。
|
|
38
|
+
* @returns 归一化结果。
|
|
39
|
+
*/
|
|
40
|
+
export declare function mapOllamaResponse(response: OllamaSearchResponse): WebSearchResult;
|
|
41
|
+
/** Ollama 的搜索后端。 */
|
|
42
|
+
export declare class OllamaSearchProvider implements WebSearchProvider {
|
|
43
|
+
private readonly options;
|
|
44
|
+
readonly id = "ollama";
|
|
45
|
+
constructor(options: OllamaSearchProviderOptions);
|
|
46
|
+
available(): boolean;
|
|
47
|
+
search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult>;
|
|
48
|
+
/**
|
|
49
|
+
* 这次的 key:字面值优先,其次按 `apiKeyEnv` 读环境。
|
|
50
|
+
* @returns key,取不到就是 `undefined`。
|
|
51
|
+
*/
|
|
52
|
+
private apiKeyOf;
|
|
53
|
+
/**
|
|
54
|
+
* 取 key;取不到就点名变量,而不是发一个无授权请求。
|
|
55
|
+
* @returns key。
|
|
56
|
+
* @throws `WEB_PROVIDER_CREDENTIAL_MISSING`。
|
|
57
|
+
*/
|
|
58
|
+
private apiKey;
|
|
59
|
+
}
|
|
60
|
+
export { ToolWeb, Web, WebCovered, WebDefault, WebError, WebFetchHttp, type WebFetchProvider, type WebFetchRequest, type WebFetchResult, WebRuntime, WebSearchDeepseek, WebSearchOllama, WebSearchOllamaConfig, type WebSearchProvider, type WebSearchRequest, type WebSearchResult, type WebSearchSource };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { n as OLLAMA_DEFAULT_BASE_URL, r as OLLAMA_MAX_RESULTS_LIMIT, i as OLLAMA_PROVIDER_ID, a as OllamaSearchProvider, c as ToolWeb, m as Web, d as WebDefault, f as WebError, l as WebFetchHttp, p as WebRuntime, u as WebSearchDeepseek, t as WebSearchOllama, o as mapOllamaResponse, s as mapOllamaResult } from "./web-search-ollama.service-CSgHrsdE.mjs";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { a as WebSearchDeepseek, i as WebFetchHttp, o as WebDefault, r as ToolWeb, t as WebSearchOllama } from "./web-search-ollama.service-CUYZ3qmj.mjs";
|
|
2
|
+
/**
|
|
3
|
+
* 给 agent 的 `web_fetch` / `web_search` 工具行。
|
|
4
|
+
*
|
|
5
|
+
* 与 `provideWebAccess()` 分开:工具行要 `ToolRegistry` / `SystemPrompt`,那是 agent 栈的东西,
|
|
6
|
+
* 而 `provideWebAccess()` 只是「搜索 + 抓取两个后端」,装它的人(含测试)不该被拽进 agent 栈。
|
|
7
|
+
*/
|
|
8
|
+
export declare const provideToolWeb: (...features: import("@morlay/zephyr").ProviderFeature[]) => readonly [typeof ToolWeb];
|
|
9
|
+
export declare const provideWebAccess: (...features: import("@morlay/zephyr").ProviderFeature[]) => readonly [{
|
|
10
|
+
readonly provide: typeof WebDefault;
|
|
11
|
+
readonly config: {
|
|
12
|
+
readonly searchProvider: "ollama";
|
|
13
|
+
readonly fetchProvider: "http";
|
|
14
|
+
};
|
|
15
|
+
}, {
|
|
16
|
+
readonly provide: typeof WebSearchDeepseek;
|
|
17
|
+
readonly config: {
|
|
18
|
+
readonly apiKeyEnv: "DEEPSEEK_API_KEY";
|
|
19
|
+
};
|
|
20
|
+
}, {
|
|
21
|
+
readonly provide: typeof WebSearchOllama;
|
|
22
|
+
readonly config: {
|
|
23
|
+
readonly apiKeyEnv: "OLLAMA_API_KEY";
|
|
24
|
+
};
|
|
25
|
+
}, typeof WebFetchHttp];
|
package/dist/server.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { provide } from "@morlay/zephyr";
|
|
2
|
+
import { c as ToolWeb, d as WebDefault, l as WebFetchHttp, t as WebSearchOllama, u as WebSearchDeepseek } from "./web-search-ollama.service-CSgHrsdE.mjs";
|
|
3
|
+
// src/server/tool-web.provide.ts
|
|
4
|
+
/**
|
|
5
|
+
* 给 agent 的 `web_fetch` / `web_search` 工具行。
|
|
6
|
+
*
|
|
7
|
+
* 与 `provideWebAccess()` 分开:工具行要 `ToolRegistry` / `SystemPrompt`,那是 agent 栈的东西,
|
|
8
|
+
* 而 `provideWebAccess()` 只是「搜索 + 抓取两个后端」,装它的人(含测试)不该被拽进 agent 栈。
|
|
9
|
+
*/
|
|
10
|
+
const provideToolWeb = provide([ToolWeb]);
|
|
11
|
+
// src/server/web.provide.ts
|
|
12
|
+
const provideWebAccess = provide([
|
|
13
|
+
{
|
|
14
|
+
provide: WebDefault,
|
|
15
|
+
config: {
|
|
16
|
+
searchProvider: "ollama",
|
|
17
|
+
fetchProvider: "http"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
provide: WebSearchDeepseek,
|
|
22
|
+
config: { apiKeyEnv: "DEEPSEEK_API_KEY" }
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
provide: WebSearchOllama,
|
|
26
|
+
config: { apiKeyEnv: "OLLAMA_API_KEY" }
|
|
27
|
+
},
|
|
28
|
+
WebFetchHttp
|
|
29
|
+
]);
|
|
30
|
+
export { provideToolWeb, provideWebAccess };
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { Injectable, inject } from "@morlay/zephyr";
|
|
2
|
+
import WebRuntime, { WebError } from "@deepseek-ai/dsh-web";
|
|
3
|
+
import { fromCordis } from "@morlay/zephyr/compat";
|
|
4
|
+
import * as WebSearchDeepseekPlugin from "@deepseek-ai/dsh-web-search-deepseek";
|
|
5
|
+
import { DeepSeekAuthToken } from "@morlay/dsh-auth";
|
|
6
|
+
import * as WebFetchHttpPlugin from "@deepseek-ai/dsh-web-fetch-http";
|
|
7
|
+
import * as ToolWebPlugin from "@deepseek-ai/dsh-tool-web";
|
|
8
|
+
import { SystemPrompt, ToolRegistry } from "@morlay/dsh-agent";
|
|
9
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/decorate.js
|
|
10
|
+
function __decorate(decorators, target, key, desc) {
|
|
11
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
12
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
13
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
14
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
15
|
+
}
|
|
16
|
+
// src/contract/web.contract.ts
|
|
17
|
+
let Web = class Web {};
|
|
18
|
+
Web = __decorate([Injectable({ name: "web" })], Web);
|
|
19
|
+
// src/web.service.ts
|
|
20
|
+
let WebDefault = class WebDefault extends fromCordis(Web, WebRuntime) {
|
|
21
|
+
async onInit(ctx) {
|
|
22
|
+
await this.mount(ctx);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
WebDefault = __decorate([Injectable()], WebDefault);
|
|
26
|
+
// src/web-search-deepseek.service.ts
|
|
27
|
+
let WebSearchDeepseek = class WebSearchDeepseek extends fromCordis(WebSearchDeepseekPlugin) {
|
|
28
|
+
web = inject(Web);
|
|
29
|
+
/**
|
|
30
|
+
* 上游 0.2.3 起这条搜索后端也从 `ctx.deepseekAuth` 取凭据(`inject` 声明里有它):显式交给它,
|
|
31
|
+
* 装配顺序由这条依赖边定住(`provideAuth()` 要在 `provideWebAccess()` 之前)。
|
|
32
|
+
*/
|
|
33
|
+
deepseekAuth = inject(DeepSeekAuthToken);
|
|
34
|
+
async onInit(ctx) {
|
|
35
|
+
await this.mount(ctx, void 0, {
|
|
36
|
+
web: this.web,
|
|
37
|
+
deepseekAuth: this.deepseekAuth
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
WebSearchDeepseek = __decorate([Injectable()], WebSearchDeepseek);
|
|
42
|
+
// src/web-fetch-http.service.ts
|
|
43
|
+
let WebFetchHttp = class WebFetchHttp extends fromCordis(WebFetchHttpPlugin) {
|
|
44
|
+
web = inject(Web);
|
|
45
|
+
async onInit(ctx) {
|
|
46
|
+
await this.mount(ctx, {
|
|
47
|
+
maxResponseBytes: 5e6,
|
|
48
|
+
maxBodyChars: 1e5,
|
|
49
|
+
timeoutMs: 3e4,
|
|
50
|
+
maxRedirects: 5
|
|
51
|
+
}, { web: this.web });
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
WebFetchHttp = __decorate([Injectable()], WebFetchHttp);
|
|
55
|
+
// src/server/tool-web.service.ts
|
|
56
|
+
let ToolWeb = class ToolWeb extends fromCordis(ToolWebPlugin) {
|
|
57
|
+
tools = inject(ToolRegistry);
|
|
58
|
+
web = inject(Web);
|
|
59
|
+
systemPrompt = inject(SystemPrompt);
|
|
60
|
+
async onInit(ctx) {
|
|
61
|
+
await this.mount(ctx, void 0, {
|
|
62
|
+
tools: this.tools,
|
|
63
|
+
web: this.web,
|
|
64
|
+
systemPrompt: this.systemPrompt
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
ToolWeb = __decorate([Injectable()], ToolWeb);
|
|
69
|
+
// src/web-search-ollama.provider.ts
|
|
70
|
+
/** 注册进 `ctx.web` 的 id;与 llm route 同名,配置里看到的就是同一个 "ollama"。 */
|
|
71
|
+
const OLLAMA_PROVIDER_ID = "ollama";
|
|
72
|
+
/** 默认端点;`/api/web_search` 是操作。 */
|
|
73
|
+
const OLLAMA_DEFAULT_BASE_URL = "https://ollama.com";
|
|
74
|
+
/** Ollama `max_results` 的硬上限;超过它的值不发给服务端。 */
|
|
75
|
+
const OLLAMA_MAX_RESULTS_LIMIT = 10;
|
|
76
|
+
/** 每次请求带的归属头。 */
|
|
77
|
+
const USER_AGENT = "morlay-dsh-plugin/0.0.1";
|
|
78
|
+
/**
|
|
79
|
+
* 一条 Ollama 结果 → 一个 source;没有 url 就丢掉(seam 的 source 必须有 url)。
|
|
80
|
+
* @param result - Ollama 的一条结果。
|
|
81
|
+
* @returns 归一化的 source,或 `undefined`。
|
|
82
|
+
*/
|
|
83
|
+
function mapOllamaResult(result) {
|
|
84
|
+
const url = result.url;
|
|
85
|
+
if (typeof url !== "string" || url.length === 0) return void 0;
|
|
86
|
+
const title = typeof result.title === "string" && result.title.length > 0 ? result.title : void 0;
|
|
87
|
+
const snippet = typeof result.content === "string" && result.content.length > 0 ? result.content : void 0;
|
|
88
|
+
return {
|
|
89
|
+
url,
|
|
90
|
+
...title === void 0 ? {} : { title },
|
|
91
|
+
...snippet === void 0 ? {} : { snippet }
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* 响应信封 → 归一化结果;形状不对就抛(由调用方包成 `WEB_PROVIDER_ERROR`)。
|
|
96
|
+
* @param response - Ollama 的响应体。
|
|
97
|
+
* @returns 归一化结果。
|
|
98
|
+
*/
|
|
99
|
+
function mapOllamaResponse(response) {
|
|
100
|
+
const results = response.results;
|
|
101
|
+
if (results !== void 0 && !Array.isArray(results)) throw new TypeError("Ollama returned a non-array `results` field");
|
|
102
|
+
return {
|
|
103
|
+
sources: (results ?? []).map((result) => mapOllamaResult(result)).filter((source) => source !== void 0),
|
|
104
|
+
truncated: false
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** Ollama 的搜索后端。 */
|
|
108
|
+
var OllamaSearchProvider = class {
|
|
109
|
+
options;
|
|
110
|
+
id = OLLAMA_PROVIDER_ID;
|
|
111
|
+
constructor(options) {
|
|
112
|
+
this.options = options;
|
|
113
|
+
}
|
|
114
|
+
available() {
|
|
115
|
+
return this.apiKeyOf() !== void 0 && URL.canParse(this.options.baseURL) && (this.options.maxResults === void 0 || isPositiveInteger(this.options.maxResults));
|
|
116
|
+
}
|
|
117
|
+
async search(request, signal) {
|
|
118
|
+
const apiKey = this.apiKey();
|
|
119
|
+
const maxResults = clampMaxResults(request.maxResults ?? this.options.maxResults);
|
|
120
|
+
let response;
|
|
121
|
+
try {
|
|
122
|
+
response = await fetch(`${this.options.baseURL}/api/web_search`, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
redirect: "error",
|
|
125
|
+
headers: {
|
|
126
|
+
authorization: `Bearer ${apiKey}`,
|
|
127
|
+
"content-type": "application/json",
|
|
128
|
+
accept: "application/json",
|
|
129
|
+
"user-agent": USER_AGENT
|
|
130
|
+
},
|
|
131
|
+
body: JSON.stringify({
|
|
132
|
+
query: request.query,
|
|
133
|
+
...maxResults === void 0 ? {} : { max_results: maxResults }
|
|
134
|
+
}),
|
|
135
|
+
...signal === void 0 ? {} : { signal }
|
|
136
|
+
});
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (isAbortError(error)) throw searchAborted(error);
|
|
139
|
+
throw new WebError(`Ollama search request failed: ${String(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
140
|
+
}
|
|
141
|
+
if (!response.ok) {
|
|
142
|
+
let message = `Ollama API error (HTTP ${String(response.status)})`;
|
|
143
|
+
try {
|
|
144
|
+
const detail = (await response.json()).error;
|
|
145
|
+
if (typeof detail === "string" && detail.length > 0) message = detail;
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (isAbortError(error)) throw searchAborted(error);
|
|
148
|
+
}
|
|
149
|
+
throw new WebError(message, "WEB_PROVIDER_ERROR");
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
return mapOllamaResponse(await response.json());
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (isAbortError(error)) throw searchAborted(error);
|
|
155
|
+
throw new WebError(`Ollama returned an unprocessable response body: ${String(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* 这次的 key:字面值优先,其次按 `apiKeyEnv` 读环境。
|
|
160
|
+
* @returns key,取不到就是 `undefined`。
|
|
161
|
+
*/
|
|
162
|
+
apiKeyOf() {
|
|
163
|
+
const literal = this.options.apiKey;
|
|
164
|
+
if (literal !== void 0 && literal.length > 0) return literal;
|
|
165
|
+
const fromEnv = process.env[this.options.apiKeyEnv];
|
|
166
|
+
return fromEnv === void 0 || fromEnv.length === 0 ? void 0 : fromEnv;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* 取 key;取不到就点名变量,而不是发一个无授权请求。
|
|
170
|
+
* @returns key。
|
|
171
|
+
* @throws `WEB_PROVIDER_CREDENTIAL_MISSING`。
|
|
172
|
+
*/
|
|
173
|
+
apiKey() {
|
|
174
|
+
const key = this.apiKeyOf();
|
|
175
|
+
if (key === void 0) throw new WebError(`Ollama search has no API key for "${this.options.apiKeyEnv}"; export it in the launching environment or set a literal "apiKey" in the web-search-ollama config`, "WEB_PROVIDER_CREDENTIAL_MISSING");
|
|
176
|
+
return key;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
/**
|
|
180
|
+
* 把结果数夹到服务端上限。
|
|
181
|
+
* @param maxResults - 请求或配置给的值。
|
|
182
|
+
* @returns 夹过之后的值。
|
|
183
|
+
*/
|
|
184
|
+
function clampMaxResults(maxResults) {
|
|
185
|
+
return maxResults === void 0 ? void 0 : Math.min(maxResults, 10);
|
|
186
|
+
}
|
|
187
|
+
/** @returns 是不是正整数。 */
|
|
188
|
+
function isPositiveInteger(value) {
|
|
189
|
+
return Number.isInteger(value) && value > 0;
|
|
190
|
+
}
|
|
191
|
+
/** @returns 是不是取消。 */
|
|
192
|
+
function isAbortError(error) {
|
|
193
|
+
return error instanceof DOMException && error.name === "AbortError";
|
|
194
|
+
}
|
|
195
|
+
/** @returns 取消语义的错误(seam 按 code 分流)。 */
|
|
196
|
+
function searchAborted(cause) {
|
|
197
|
+
return new WebError("Ollama search aborted", "WEB_ABORTED", { cause });
|
|
198
|
+
}
|
|
199
|
+
// src/web-search-ollama.service.ts
|
|
200
|
+
let WebSearchOllama = class WebSearchOllama {
|
|
201
|
+
web = inject(Web);
|
|
202
|
+
/** 行配置:`configure(...)` 的 patch 由基类构造接住。 */
|
|
203
|
+
config;
|
|
204
|
+
constructor(config = {}) {
|
|
205
|
+
this.config = config;
|
|
206
|
+
}
|
|
207
|
+
onInit(ctx) {
|
|
208
|
+
const options = {
|
|
209
|
+
apiKeyEnv: this.config.apiKeyEnv ?? "OLLAMA_API_KEY",
|
|
210
|
+
baseURL: this.config.baseURL ?? "https://ollama.com",
|
|
211
|
+
...this.config.apiKey === void 0 ? {} : { apiKey: this.config.apiKey },
|
|
212
|
+
...this.config.maxResults === void 0 ? {} : { maxResults: this.config.maxResults }
|
|
213
|
+
};
|
|
214
|
+
const dispose = this.web.registerSearchProvider(new OllamaSearchProvider(options));
|
|
215
|
+
ctx.effect(() => dispose);
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
WebSearchOllama = __decorate([Injectable()], WebSearchOllama);
|
|
219
|
+
export { OllamaSearchProvider as a, ToolWeb as c, WebDefault as d, WebError as f, OLLAMA_PROVIDER_ID as i, WebFetchHttp as l, Web as m, OLLAMA_DEFAULT_BASE_URL as n, mapOllamaResponse as o, WebRuntime as p, OLLAMA_MAX_RESULTS_LIMIT as r, mapOllamaResult as s, WebSearchOllama as t, WebSearchDeepseek as u };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import WebRuntime, { WebError, WebFetchProvider, WebFetchRequest, WebFetchResult, WebSearchProvider, WebSearchRequest, WebSearchResult, WebSearchSource, default as WebRuntimeService } from "@deepseek-ai/dsh-web";
|
|
2
|
+
import { AssertCoveredStrict, AssertTrue } from "@morlay/zephyr-app/client";
|
|
3
|
+
import { Context } from "@morlay/zephyr";
|
|
4
|
+
import * as WebSearchDeepseekPlugin from "@deepseek-ai/dsh-web-search-deepseek";
|
|
5
|
+
import * as WebFetchHttpPlugin from "@deepseek-ai/dsh-web-fetch-http";
|
|
6
|
+
import * as ToolWebPlugin from "@deepseek-ai/dsh-tool-web";
|
|
7
|
+
import { SystemPrompt, ToolRegistry } from "@morlay/dsh-agent";
|
|
8
|
+
declare abstract class Web {
|
|
9
|
+
abstract readonly registerSearchProvider: WebRuntimeService["registerSearchProvider"];
|
|
10
|
+
abstract readonly registerFetchProvider: WebRuntimeService["registerFetchProvider"];
|
|
11
|
+
abstract readonly search: WebRuntimeService["search"];
|
|
12
|
+
abstract readonly fetch: WebRuntimeService["fetch"];
|
|
13
|
+
abstract readonly fetchReady: WebRuntimeService["fetchReady"];
|
|
14
|
+
abstract readonly searchReady: WebRuntimeService["searchReady"];
|
|
15
|
+
/** 当前可用的搜索 / 抓取 provider(诊断与选择器用)。 */
|
|
16
|
+
abstract readonly listProviders: WebRuntimeService["listProviders"];
|
|
17
|
+
/** 上游基类挂的 remote 绑定(gateway 靠它发现端点)。 */
|
|
18
|
+
abstract readonly typertRemote: WebRuntimeService["typertRemote"];
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* 覆盖守卫(严格):上游 `WebRuntimeService` 的每个成员都要有同名、同签名的对应项。
|
|
22
|
+
*
|
|
23
|
+
* 为什么不是 `implements`:上游那份是 cordis `Service` **类**(带私有成员),`implements` 会报
|
|
24
|
+
* TS2720("Did you mean to extend … and inherit its members as a subclass?")。签名守卫在这里等价:
|
|
25
|
+
* 漏成员或签名对不上,编译期都会报出成员名(诊断的第二行)。
|
|
26
|
+
*/
|
|
27
|
+
type WebCovered = AssertTrue<AssertCoveredStrict<WebRuntimeService, Web>>;
|
|
28
|
+
declare const WebDefault_base: import("@morlay/zephyr/compat").AdaptedClass<typeof Web, typeof WebRuntime>;
|
|
29
|
+
declare class WebDefault extends WebDefault_base {
|
|
30
|
+
onInit(ctx: Context): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
declare const WebSearchDeepseek_base: import("@morlay/zephyr/compat").AdaptedClass<import("@morlay/zephyr").TokenClass<unknown>, typeof WebSearchDeepseekPlugin>;
|
|
33
|
+
declare class WebSearchDeepseek extends WebSearchDeepseek_base {
|
|
34
|
+
web: Web & import("@morlay/zephyr").Required<Web>;
|
|
35
|
+
/**
|
|
36
|
+
* 上游 0.2.3 起这条搜索后端也从 `ctx.deepseekAuth` 取凭据(`inject` 声明里有它):显式交给它,
|
|
37
|
+
* 装配顺序由这条依赖边定住(`provideAuth()` 要在 `provideWebAccess()` 之前)。
|
|
38
|
+
*/
|
|
39
|
+
private readonly deepseekAuth;
|
|
40
|
+
onInit(ctx: Context): Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
declare const WebFetchHttp_base: import("@morlay/zephyr/compat").AdaptedClass<import("@morlay/zephyr").TokenClass<unknown>, typeof WebFetchHttpPlugin>;
|
|
43
|
+
declare class WebFetchHttp extends WebFetchHttp_base {
|
|
44
|
+
web: Web & import("@morlay/zephyr").Required<Web>;
|
|
45
|
+
onInit(ctx: Context): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
declare const ToolWeb_base: import("@morlay/zephyr/compat").AdaptedClass<import("@morlay/zephyr").TokenClass<unknown>, typeof ToolWebPlugin>;
|
|
48
|
+
declare class ToolWeb extends ToolWeb_base {
|
|
49
|
+
tools: ToolRegistry & import("@morlay/zephyr").Required<ToolRegistry>;
|
|
50
|
+
web: Web & import("@morlay/zephyr").Required<Web>;
|
|
51
|
+
systemPrompt: SystemPrompt & import("@morlay/zephyr").Required<SystemPrompt>;
|
|
52
|
+
onInit(ctx: Context): Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
/** 行配置(`configure(WebSearchOllama, {...})` 叠的值)。 */
|
|
55
|
+
interface WebSearchOllamaConfig {
|
|
56
|
+
readonly apiKey?: string;
|
|
57
|
+
readonly apiKeyEnv?: string;
|
|
58
|
+
readonly baseURL?: string;
|
|
59
|
+
readonly maxResults?: number;
|
|
60
|
+
}
|
|
61
|
+
declare class WebSearchOllama {
|
|
62
|
+
private readonly web;
|
|
63
|
+
/** 行配置:`configure(...)` 的 patch 由基类构造接住。 */
|
|
64
|
+
private readonly config;
|
|
65
|
+
constructor(config?: WebSearchOllamaConfig);
|
|
66
|
+
onInit(ctx: Context): void;
|
|
67
|
+
}
|
|
68
|
+
export { WebCovered as _, WebSearchDeepseek as a, WebFetchProvider as c, WebRuntime as d, WebSearchProvider as f, Web as g, WebSearchSource as h, WebFetchHttp as i, WebFetchRequest as l, WebSearchResult as m, WebSearchOllamaConfig as n, WebDefault as o, WebSearchRequest as p, ToolWeb as r, WebError as s, WebSearchOllama as t, WebFetchResult as u };
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@morlay/dsh-web-access",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.2.0-alpha.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "联网访问:搜索与抓取两个后端、一个 `Web` 契约,以及给模型的 web 工具行。",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist",
|
|
8
|
+
"src",
|
|
9
|
+
"!**/__tests__"
|
|
10
|
+
],
|
|
11
|
+
"type": "module",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.mts",
|
|
15
|
+
"default": "./dist/index.mjs"
|
|
16
|
+
},
|
|
17
|
+
"./server": {
|
|
18
|
+
"types": "./dist/server.d.mts",
|
|
19
|
+
"default": "./dist/server.mjs"
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@morlay/dsh-agent": "^0.2.0-alpha.0",
|
|
25
|
+
"@morlay/dsh-auth": "^0.2.0-alpha.0",
|
|
26
|
+
"@morlay/zephyr": "^0.2.0-alpha.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@morlay/zephyr-app": "^0.2.0-alpha.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@deepseek-ai/dsh-tool-web": "^0.2.3-alpha.3",
|
|
33
|
+
"@deepseek-ai/dsh-web": "^0.2.3-alpha.3",
|
|
34
|
+
"@deepseek-ai/dsh-web-fetch-http": "^0.2.3-alpha.3",
|
|
35
|
+
"@deepseek-ai/dsh-web-search-deepseek": "^0.2.3-alpha.3"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"dsh": ">= 0.2.3-alpha.3 < 0.2.4"
|
|
39
|
+
},
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "https://github.com/morlay/zephyr.git",
|
|
43
|
+
"directory": "packages/agent/dsh-web-access"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {}
|
|
6
46
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// web 运行时的契约:令牌按服务语义命名(上游注册名 `web`)。
|
|
2
|
+
import type WebRuntimeService from "@deepseek-ai/dsh-web";
|
|
3
|
+
import { Injectable } from "@morlay/zephyr";
|
|
4
|
+
import type { AssertCoveredStrict, AssertTrue } from "@morlay/zephyr-app/client";
|
|
5
|
+
|
|
6
|
+
@Injectable({ name: "web" })
|
|
7
|
+
export abstract class Web {
|
|
8
|
+
abstract readonly registerSearchProvider: WebRuntimeService["registerSearchProvider"];
|
|
9
|
+
|
|
10
|
+
abstract readonly registerFetchProvider: WebRuntimeService["registerFetchProvider"];
|
|
11
|
+
|
|
12
|
+
abstract readonly search: WebRuntimeService["search"];
|
|
13
|
+
|
|
14
|
+
abstract readonly fetch: WebRuntimeService["fetch"];
|
|
15
|
+
|
|
16
|
+
abstract readonly fetchReady: WebRuntimeService["fetchReady"];
|
|
17
|
+
|
|
18
|
+
abstract readonly searchReady: WebRuntimeService["searchReady"];
|
|
19
|
+
|
|
20
|
+
/** 当前可用的搜索 / 抓取 provider(诊断与选择器用)。 */
|
|
21
|
+
abstract readonly listProviders: WebRuntimeService["listProviders"];
|
|
22
|
+
|
|
23
|
+
/** 上游基类挂的 remote 绑定(gateway 靠它发现端点)。 */
|
|
24
|
+
abstract readonly typertRemote: WebRuntimeService["typertRemote"];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 覆盖守卫(严格):上游 `WebRuntimeService` 的每个成员都要有同名、同签名的对应项。
|
|
29
|
+
*
|
|
30
|
+
* 为什么不是 `implements`:上游那份是 cordis `Service` **类**(带私有成员),`implements` 会报
|
|
31
|
+
* TS2720("Did you mean to extend … and inherit its members as a subclass?")。签名守卫在这里等价:
|
|
32
|
+
* 漏成员或签名对不上,编译期都会报出成员名(诊断的第二行)。
|
|
33
|
+
*/
|
|
34
|
+
export type WebCovered = AssertTrue<AssertCoveredStrict<WebRuntimeService, Web>>;
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// web-access:`Web` 契约 + 两个实现(搜索、抓取)+ 装配模块 + 工具行。
|
|
2
|
+
export * from "./contract/index.ts";
|
|
3
|
+
export * from "./web.service.ts";
|
|
4
|
+
export * from "./web-search-deepseek.service.ts";
|
|
5
|
+
export * from "./web-fetch-http.service.ts";
|
|
6
|
+
// 工具行(`ToolWeb`):装配层从这里拿,`./server` 那个子出口零消费方,已删。
|
|
7
|
+
export { ToolWeb } from "./server/tool-web.service.ts";
|
|
8
|
+
export * from "./web-search-ollama.service.ts";
|
|
9
|
+
export * from "./web-search-ollama.provider.ts";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { provide } from "@morlay/zephyr";
|
|
2
|
+
import { ToolWeb } from "./tool-web.service.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 给 agent 的 `web_fetch` / `web_search` 工具行。
|
|
6
|
+
*
|
|
7
|
+
* 与 `provideWebAccess()` 分开:工具行要 `ToolRegistry` / `SystemPrompt`,那是 agent 栈的东西,
|
|
8
|
+
* 而 `provideWebAccess()` 只是「搜索 + 抓取两个后端」,装它的人(含测试)不该被拽进 agent 栈。
|
|
9
|
+
*/
|
|
10
|
+
export const provideToolWeb = provide([ToolWeb]);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// ToolWeb(工具/策略实现行)。
|
|
2
|
+
import { Injectable, inject, type Context } from "@morlay/zephyr";
|
|
3
|
+
import { fromCordis } from "@morlay/zephyr/compat";
|
|
4
|
+
import * as ToolWebPlugin from "@deepseek-ai/dsh-tool-web";
|
|
5
|
+
import { ToolRegistry, SystemPrompt as SystemPromptContract } from "@morlay/dsh-agent";
|
|
6
|
+
import { Web } from "../contract/web.contract.ts";
|
|
7
|
+
|
|
8
|
+
@Injectable()
|
|
9
|
+
export class ToolWeb extends fromCordis(ToolWebPlugin) {
|
|
10
|
+
tools = inject(ToolRegistry);
|
|
11
|
+
|
|
12
|
+
web = inject(Web);
|
|
13
|
+
|
|
14
|
+
systemPrompt = inject(SystemPromptContract);
|
|
15
|
+
|
|
16
|
+
override async onInit(ctx: Context): Promise<void> {
|
|
17
|
+
await this.mount(ctx, undefined, {
|
|
18
|
+
tools: this.tools,
|
|
19
|
+
web: this.web,
|
|
20
|
+
systemPrompt: this.systemPrompt,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { provide } from "@morlay/zephyr";
|
|
2
|
+
import { WebDefault } from "../web.service.ts";
|
|
3
|
+
import { WebSearchDeepseek } from "../web-search-deepseek.service.ts";
|
|
4
|
+
import { WebFetchHttp } from "../web-fetch-http.service.ts";
|
|
5
|
+
import { WebSearchOllama } from "../web-search-ollama.service.ts";
|
|
6
|
+
|
|
7
|
+
// 两个搜索后端都装:`searchProvider` 只在**调用时**解析(上游 `WebRuntime` 的选择语义是
|
|
8
|
+
// "resolved at execution time, never order-dependent"),所以清单顺序不影响"默认选谁"。
|
|
9
|
+
export const provideWebAccess = provide([
|
|
10
|
+
// 默认走 ollama(`dsh-plugin-main` 的 ollama-provider-profile 就是这套);deepseek 那条仍可用。
|
|
11
|
+
{ provide: WebDefault, config: { searchProvider: "ollama", fetchProvider: "http" } },
|
|
12
|
+
{ provide: WebSearchDeepseek, config: { apiKeyEnv: "DEEPSEEK_API_KEY" } },
|
|
13
|
+
{ provide: WebSearchOllama, config: { apiKeyEnv: "OLLAMA_API_KEY" } },
|
|
14
|
+
WebFetchHttp,
|
|
15
|
+
]);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// HTTP 抓取后端:上游 `WebFetchHttpPlugin` 经 `fromCordis` 接管。
|
|
2
|
+
import * as WebFetchHttpPlugin from "@deepseek-ai/dsh-web-fetch-http";
|
|
3
|
+
import { Injectable, inject, type Context } from "@morlay/zephyr";
|
|
4
|
+
import { fromCordis } from "@morlay/zephyr/compat";
|
|
5
|
+
import { Web } from "./contract/web.contract.ts";
|
|
6
|
+
|
|
7
|
+
@Injectable()
|
|
8
|
+
export class WebFetchHttp extends fromCordis(WebFetchHttpPlugin) {
|
|
9
|
+
web = inject(Web);
|
|
10
|
+
|
|
11
|
+
override async onInit(ctx: Context): Promise<void> {
|
|
12
|
+
// 上游 0.2.2 的 `apply(ctx, config)` 直接读 `ResolvedConfig` 的必填字段(schemastery 的默认值只在
|
|
13
|
+
// 走它自己的 `Config` 解析时才填),本行不走那一步,所以显式给同一组默认值。
|
|
14
|
+
await this.mount(
|
|
15
|
+
ctx,
|
|
16
|
+
{
|
|
17
|
+
maxResponseBytes: 5_000_000,
|
|
18
|
+
maxBodyChars: 100_000,
|
|
19
|
+
timeoutMs: 30_000,
|
|
20
|
+
maxRedirects: 5,
|
|
21
|
+
},
|
|
22
|
+
{ web: this.web },
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// DeepSeek 搜索后端:上游 `WebSearchDeepseekPlugin` 经 `fromCordis` 接管。
|
|
2
|
+
import * as WebSearchDeepseekPlugin from "@deepseek-ai/dsh-web-search-deepseek";
|
|
3
|
+
import { Injectable, inject, type Context } from "@morlay/zephyr";
|
|
4
|
+
import { fromCordis } from "@morlay/zephyr/compat";
|
|
5
|
+
import { DeepSeekAuthToken } from "@morlay/dsh-auth";
|
|
6
|
+
import { Web } from "./contract/web.contract.ts";
|
|
7
|
+
|
|
8
|
+
@Injectable()
|
|
9
|
+
export class WebSearchDeepseek extends fromCordis(WebSearchDeepseekPlugin) {
|
|
10
|
+
web = inject(Web);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 上游 0.2.3 起这条搜索后端也从 `ctx.deepseekAuth` 取凭据(`inject` 声明里有它):显式交给它,
|
|
14
|
+
* 装配顺序由这条依赖边定住(`provideAuth()` 要在 `provideWebAccess()` 之前)。
|
|
15
|
+
*/
|
|
16
|
+
private readonly deepseekAuth = inject(DeepSeekAuthToken);
|
|
17
|
+
|
|
18
|
+
override async onInit(ctx: Context): Promise<void> {
|
|
19
|
+
await this.mount(ctx, undefined, { web: this.web, deepseekAuth: this.deepseekAuth });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// Ollama 的搜索后端(`POST https://ollama.com/api/web_search`):纯逻辑 + `fetch`,不碰 cordis。
|
|
2
|
+
//
|
|
3
|
+
// 与上游 `dsh-plugin-main/packages/web/dsh-web-search-ollama` 的实现同形;我们的仓库没有那个包,
|
|
4
|
+
// 这里按 `WebSearchProvider` 契约直接写一份,接线在 `web-search-ollama.service.ts`。
|
|
5
|
+
import {
|
|
6
|
+
WebError,
|
|
7
|
+
type WebSearchProvider,
|
|
8
|
+
type WebSearchRequest,
|
|
9
|
+
type WebSearchResult,
|
|
10
|
+
type WebSearchSource,
|
|
11
|
+
} from "./web.service.ts";
|
|
12
|
+
|
|
13
|
+
/** 注册进 `ctx.web` 的 id;与 llm route 同名,配置里看到的就是同一个 "ollama"。 */
|
|
14
|
+
export const OLLAMA_PROVIDER_ID = "ollama";
|
|
15
|
+
|
|
16
|
+
/** 默认端点;`/api/web_search` 是操作。 */
|
|
17
|
+
export const OLLAMA_DEFAULT_BASE_URL = "https://ollama.com";
|
|
18
|
+
|
|
19
|
+
/** Ollama `max_results` 的硬上限;超过它的值不发给服务端。 */
|
|
20
|
+
export const OLLAMA_MAX_RESULTS_LIMIT = 10;
|
|
21
|
+
|
|
22
|
+
/** 每次请求带的归属头。 */
|
|
23
|
+
const USER_AGENT = "morlay-dsh-plugin/0.0.1";
|
|
24
|
+
|
|
25
|
+
/** `POST /api/web_search` 的一条结果;字段都可能缺失或为空串。 */
|
|
26
|
+
interface OllamaSearchResult {
|
|
27
|
+
readonly title?: string | null;
|
|
28
|
+
readonly url?: string | null;
|
|
29
|
+
readonly content?: string | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 成功信封。 */
|
|
33
|
+
interface OllamaSearchResponse {
|
|
34
|
+
readonly results?: readonly OllamaSearchResult[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 失败信封(Ollama 给 `{ "error": "…" }`)。 */
|
|
38
|
+
interface OllamaError {
|
|
39
|
+
readonly error?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 构造参数。 */
|
|
43
|
+
export interface OllamaSearchProviderOptions {
|
|
44
|
+
/** 字面 key;给了就压过 `apiKeyEnv`。 */
|
|
45
|
+
readonly apiKey?: string | undefined;
|
|
46
|
+
/** 取不到 key 时报出来的变量名,便于用户知道去哪配。 */
|
|
47
|
+
readonly apiKeyEnv: string;
|
|
48
|
+
/** 端点根。 */
|
|
49
|
+
readonly baseURL: string;
|
|
50
|
+
/** 请求没带 `maxResults` 时的默认值;省略表示让 Ollama 用自己的默认。 */
|
|
51
|
+
readonly maxResults?: number | undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 一条 Ollama 结果 → 一个 source;没有 url 就丢掉(seam 的 source 必须有 url)。
|
|
56
|
+
* @param result - Ollama 的一条结果。
|
|
57
|
+
* @returns 归一化的 source,或 `undefined`。
|
|
58
|
+
*/
|
|
59
|
+
export function mapOllamaResult(result: OllamaSearchResult): WebSearchSource | undefined {
|
|
60
|
+
const url = result.url;
|
|
61
|
+
if (typeof url !== "string" || url.length === 0) return undefined;
|
|
62
|
+
const title =
|
|
63
|
+
typeof result.title === "string" && result.title.length > 0 ? result.title : undefined;
|
|
64
|
+
const snippet =
|
|
65
|
+
typeof result.content === "string" && result.content.length > 0 ? result.content : undefined;
|
|
66
|
+
return {
|
|
67
|
+
url,
|
|
68
|
+
...(title === undefined ? {} : { title }),
|
|
69
|
+
...(snippet === undefined ? {} : { snippet }),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 响应信封 → 归一化结果;形状不对就抛(由调用方包成 `WEB_PROVIDER_ERROR`)。
|
|
75
|
+
* @param response - Ollama 的响应体。
|
|
76
|
+
* @returns 归一化结果。
|
|
77
|
+
*/
|
|
78
|
+
export function mapOllamaResponse(response: OllamaSearchResponse): WebSearchResult {
|
|
79
|
+
const results = response.results;
|
|
80
|
+
if (results !== undefined && !Array.isArray(results)) {
|
|
81
|
+
throw new TypeError("Ollama returned a non-array `results` field");
|
|
82
|
+
}
|
|
83
|
+
const sources = (results ?? [])
|
|
84
|
+
.map((result) => mapOllamaResult(result))
|
|
85
|
+
.filter((source): source is WebSearchSource => source !== undefined);
|
|
86
|
+
// Ollama 不返回生成式答案(`content` 是每条结果的网页片段),所以没有 `result.content`;
|
|
87
|
+
// 截断由 seam 负责,这里照实报 false。
|
|
88
|
+
return { sources, truncated: false };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Ollama 的搜索后端。 */
|
|
92
|
+
export class OllamaSearchProvider implements WebSearchProvider {
|
|
93
|
+
readonly id = OLLAMA_PROVIDER_ID;
|
|
94
|
+
|
|
95
|
+
constructor(private readonly options: OllamaSearchProviderOptions) {}
|
|
96
|
+
|
|
97
|
+
available(): boolean {
|
|
98
|
+
return (
|
|
99
|
+
this.apiKeyOf() !== undefined &&
|
|
100
|
+
URL.canParse(this.options.baseURL) &&
|
|
101
|
+
(this.options.maxResults === undefined || isPositiveInteger(this.options.maxResults))
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult> {
|
|
106
|
+
const apiKey = this.apiKey();
|
|
107
|
+
const maxResults = clampMaxResults(request.maxResults ?? this.options.maxResults);
|
|
108
|
+
let response: Response;
|
|
109
|
+
try {
|
|
110
|
+
response = await fetch(`${this.options.baseURL}/api/web_search`, {
|
|
111
|
+
method: "POST",
|
|
112
|
+
redirect: "error",
|
|
113
|
+
headers: {
|
|
114
|
+
authorization: `Bearer ${apiKey}`,
|
|
115
|
+
"content-type": "application/json",
|
|
116
|
+
accept: "application/json",
|
|
117
|
+
"user-agent": USER_AGENT,
|
|
118
|
+
},
|
|
119
|
+
body: JSON.stringify({
|
|
120
|
+
query: request.query,
|
|
121
|
+
...(maxResults === undefined ? {} : { max_results: maxResults }),
|
|
122
|
+
}),
|
|
123
|
+
...(signal === undefined ? {} : { signal }),
|
|
124
|
+
});
|
|
125
|
+
} catch (error: unknown) {
|
|
126
|
+
if (isAbortError(error)) throw searchAborted(error);
|
|
127
|
+
throw new WebError(`Ollama search request failed: ${String(error)}`, "WEB_PROVIDER_ERROR", {
|
|
128
|
+
cause: error,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (!response.ok) {
|
|
133
|
+
let message = `Ollama API error (HTTP ${String(response.status)})`;
|
|
134
|
+
try {
|
|
135
|
+
const parsed = (await response.json()) as OllamaError;
|
|
136
|
+
const detail = parsed.error;
|
|
137
|
+
if (typeof detail === "string" && detail.length > 0) message = detail;
|
|
138
|
+
} catch (error: unknown) {
|
|
139
|
+
// 取消不能吞成"HTTP 错误":取消是 seam 的取消契约,不是 provider 故障。
|
|
140
|
+
if (isAbortError(error)) throw searchAborted(error);
|
|
141
|
+
}
|
|
142
|
+
throw new WebError(message, "WEB_PROVIDER_ERROR");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
try {
|
|
146
|
+
return mapOllamaResponse((await response.json()) as OllamaSearchResponse);
|
|
147
|
+
} catch (error: unknown) {
|
|
148
|
+
if (isAbortError(error)) throw searchAborted(error);
|
|
149
|
+
throw new WebError(
|
|
150
|
+
`Ollama returned an unprocessable response body: ${String(error)}`,
|
|
151
|
+
"WEB_PROVIDER_ERROR",
|
|
152
|
+
{
|
|
153
|
+
cause: error,
|
|
154
|
+
},
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* 这次的 key:字面值优先,其次按 `apiKeyEnv` 读环境。
|
|
161
|
+
* @returns key,取不到就是 `undefined`。
|
|
162
|
+
*/
|
|
163
|
+
private apiKeyOf(): string | undefined {
|
|
164
|
+
const literal = this.options.apiKey;
|
|
165
|
+
if (literal !== undefined && literal.length > 0) return literal;
|
|
166
|
+
const fromEnv = process.env[this.options.apiKeyEnv];
|
|
167
|
+
return fromEnv === undefined || fromEnv.length === 0 ? undefined : fromEnv;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 取 key;取不到就点名变量,而不是发一个无授权请求。
|
|
172
|
+
* @returns key。
|
|
173
|
+
* @throws `WEB_PROVIDER_CREDENTIAL_MISSING`。
|
|
174
|
+
*/
|
|
175
|
+
private apiKey(): string {
|
|
176
|
+
const key = this.apiKeyOf();
|
|
177
|
+
if (key === undefined) {
|
|
178
|
+
throw new WebError(
|
|
179
|
+
`Ollama search has no API key for "${this.options.apiKeyEnv}"; export it in the launching environment` +
|
|
180
|
+
' or set a literal "apiKey" in the web-search-ollama config',
|
|
181
|
+
"WEB_PROVIDER_CREDENTIAL_MISSING",
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
return key;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 把结果数夹到服务端上限。
|
|
190
|
+
* @param maxResults - 请求或配置给的值。
|
|
191
|
+
* @returns 夹过之后的值。
|
|
192
|
+
*/
|
|
193
|
+
function clampMaxResults(maxResults: number | undefined): number | undefined {
|
|
194
|
+
return maxResults === undefined ? undefined : Math.min(maxResults, OLLAMA_MAX_RESULTS_LIMIT);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** @returns 是不是正整数。 */
|
|
198
|
+
function isPositiveInteger(value: number): boolean {
|
|
199
|
+
return Number.isInteger(value) && value > 0;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** @returns 是不是取消。 */
|
|
203
|
+
function isAbortError(error: unknown): boolean {
|
|
204
|
+
return error instanceof DOMException && error.name === "AbortError";
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** @returns 取消语义的错误(seam 按 code 分流)。 */
|
|
208
|
+
function searchAborted(cause: unknown): WebError {
|
|
209
|
+
return new WebError("Ollama search aborted", "WEB_ABORTED", { cause });
|
|
210
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Ollama 搜索后端的**行**:把 provider 注册进 `ctx.web`,配置来自装配面。
|
|
2
|
+
//
|
|
3
|
+
// 与 `WebSearchDeepseek` 的区别:那一行是上游插件的适配行(它自己读凭证服务),这一份是纯实现行
|
|
4
|
+
// (上游没有对应的包,见 `web-search-ollama.provider.ts` 的头注释)。
|
|
5
|
+
import { inject, Injectable, type Context } from "@morlay/zephyr";
|
|
6
|
+
import { Web } from "./contract/web.contract.ts";
|
|
7
|
+
import {
|
|
8
|
+
OLLAMA_DEFAULT_BASE_URL,
|
|
9
|
+
OllamaSearchProvider,
|
|
10
|
+
type OllamaSearchProviderOptions,
|
|
11
|
+
} from "./web-search-ollama.provider.ts";
|
|
12
|
+
|
|
13
|
+
/** 行配置(`configure(WebSearchOllama, {...})` 叠的值)。 */
|
|
14
|
+
export interface WebSearchOllamaConfig {
|
|
15
|
+
readonly apiKey?: string;
|
|
16
|
+
readonly apiKeyEnv?: string;
|
|
17
|
+
readonly baseURL?: string;
|
|
18
|
+
readonly maxResults?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
@Injectable()
|
|
22
|
+
export class WebSearchOllama {
|
|
23
|
+
private readonly web = inject(Web);
|
|
24
|
+
|
|
25
|
+
/** 行配置:`configure(...)` 的 patch 由基类构造接住。 */
|
|
26
|
+
private readonly config: WebSearchOllamaConfig;
|
|
27
|
+
|
|
28
|
+
constructor(config: WebSearchOllamaConfig = {}) {
|
|
29
|
+
this.config = config;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
onInit(ctx: Context): void {
|
|
33
|
+
const options: OllamaSearchProviderOptions = {
|
|
34
|
+
apiKeyEnv: this.config.apiKeyEnv ?? "OLLAMA_API_KEY",
|
|
35
|
+
baseURL: this.config.baseURL ?? OLLAMA_DEFAULT_BASE_URL,
|
|
36
|
+
...(this.config.apiKey === undefined ? {} : { apiKey: this.config.apiKey }),
|
|
37
|
+
...(this.config.maxResults === undefined ? {} : { maxResults: this.config.maxResults }),
|
|
38
|
+
};
|
|
39
|
+
const dispose = this.web.registerSearchProvider(new OllamaSearchProvider(options));
|
|
40
|
+
ctx.effect(() => dispose);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import WebRuntime from "@deepseek-ai/dsh-web";
|
|
2
|
+
export { WebRuntime };
|
|
3
|
+
import { Injectable, type Context } from "@morlay/zephyr";
|
|
4
|
+
import { fromCordis } from "@morlay/zephyr/compat";
|
|
5
|
+
import { Web } from "./contract/web.contract.ts";
|
|
6
|
+
|
|
7
|
+
// `web` seam 的契约(provider 接口、请求/结果形状、错误类型)只在这里透出:
|
|
8
|
+
// 能力包依赖它写后端,不再直接 import 上游包。
|
|
9
|
+
export { WebError } from "@deepseek-ai/dsh-web";
|
|
10
|
+
export { Web } from "./contract/web.contract.ts";
|
|
11
|
+
export type {
|
|
12
|
+
WebFetchProvider,
|
|
13
|
+
WebFetchRequest,
|
|
14
|
+
WebFetchResult,
|
|
15
|
+
WebSearchProvider,
|
|
16
|
+
WebSearchRequest,
|
|
17
|
+
WebSearchResult,
|
|
18
|
+
WebSearchSource,
|
|
19
|
+
} from "@deepseek-ai/dsh-web";
|
|
20
|
+
|
|
21
|
+
@Injectable()
|
|
22
|
+
export class WebDefault extends fromCordis(Web, WebRuntime) {
|
|
23
|
+
override async onInit(ctx: Context): Promise<void> {
|
|
24
|
+
await this.mount(ctx);
|
|
25
|
+
}
|
|
26
|
+
}
|