-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemantic-provider.ts
More file actions
166 lines (145 loc) · 4.96 KB
/
Copy pathsemantic-provider.ts
File metadata and controls
166 lines (145 loc) · 4.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import { RuntimeLogger } from "./logger.js";
export interface SemanticRequest {
taskName: string;
prompt: string;
maxTokens: number;
}
export interface SemanticResponse {
text: string;
provider: string;
model: string;
latencyMs: number;
promptTokens?: number;
completionTokens?: number;
fallbackFrom?: string[];
}
export interface SemanticProvider {
readonly name: string;
requestText(request: SemanticRequest): Promise<SemanticResponse | null>;
}
export interface LocalOpenAiProviderOptions {
baseUrl: string;
models: string[];
timeoutMs: number;
temperature: number;
allowNonLoopback: boolean;
}
function isLoopbackUrl(rawUrl: string): boolean {
try {
const hostname = new URL(rawUrl).hostname.toLowerCase();
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
} catch {
return false;
}
}
function getErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export class LocalOpenAiProvider implements SemanticProvider {
readonly name = "local-openai";
private readonly options: LocalOpenAiProviderOptions;
constructor(options: LocalOpenAiProviderOptions) {
if (!options.allowNonLoopback && !isLoopbackUrl(options.baseUrl)) {
throw new Error("Local semantic provider base URL must use a loopback host unless allowNonLoopback is enabled.");
}
this.options = options;
}
async requestText(request: SemanticRequest): Promise<SemanticResponse | null> {
const failedModels: string[] = [];
for (const model of this.options.models) {
const startedAt = Date.now();
try {
const response = await fetch(`${this.options.baseUrl.replace(/\/$/, "")}/chat/completions`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model,
messages: [{ role: "user", content: request.prompt }],
stream: false,
temperature: this.options.temperature,
max_tokens: request.maxTokens,
keep_alive: -1,
}),
signal: AbortSignal.timeout(this.options.timeoutMs),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const payload = await response.json() as {
choices?: Array<{ message?: { content?: unknown } }>;
usage?: { prompt_tokens?: number; completion_tokens?: number };
};
const text = payload.choices?.[0]?.message?.content;
if (typeof text !== "string" || text.trim().length === 0) {
throw new Error("Response did not contain assistant text.");
}
return {
text,
provider: this.name,
model,
latencyMs: Date.now() - startedAt,
promptTokens: payload.usage?.prompt_tokens,
completionTokens: payload.usage?.completion_tokens,
fallbackFrom: failedModels,
};
} catch (error) {
failedModels.push(model);
RuntimeLogger.warn(`${request.taskName} local model attempt failed`, {
provider: this.name,
model,
latencyMs: Date.now() - startedAt,
error: getErrorMessage(error),
});
}
}
return null;
}
}
export class McpSamplingProvider implements SemanticProvider {
readonly name = "mcp-sampling";
private readonly sample: (prompt: string, maxTokens: number) => Promise<string | null>;
constructor(sample: (prompt: string, maxTokens: number) => Promise<string | null>) {
this.sample = sample;
}
async requestText(request: SemanticRequest): Promise<SemanticResponse | null> {
const startedAt = Date.now();
const text = await this.sample(request.prompt, request.maxTokens);
if (!text) {
return null;
}
return {
text,
provider: this.name,
model: "client-selected",
latencyMs: Date.now() - startedAt,
};
}
}
export class SemanticProviderChain {
private readonly providers: SemanticProvider[];
private readonly onSuccess?: (response: SemanticResponse, request: SemanticRequest) => void;
constructor(
providers: SemanticProvider[],
onSuccess?: (response: SemanticResponse, request: SemanticRequest) => void,
) {
this.providers = providers;
this.onSuccess = onSuccess;
}
async requestText(request: SemanticRequest): Promise<string | null> {
const unavailableProviders: string[] = [];
for (const provider of this.providers) {
const response = await provider.requestText(request);
if (response) {
response.fallbackFrom = [
...unavailableProviders.map(name => `provider:${name}`),
...(response.fallbackFrom || []).map(model => `model:${model}`),
];
this.onSuccess?.(response, request);
return response.text;
}
unavailableProviders.push(provider.name);
}
RuntimeLogger.warn(`${request.taskName} exhausted all semantic providers`);
return null;
}
}