opc-agent 1.1.1 → 1.1.3
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/CHANGELOG.md +51 -51
- package/CONTRIBUTING.md +75 -75
- package/README.md +222 -126
- package/README.zh-CN.md +129 -80
- package/dist/channels/web.js +256 -256
- package/dist/deploy/hermes.js +22 -22
- package/dist/deploy/openclaw.js +31 -31
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.js +148 -13
- package/dist/schema/oad.d.ts +3 -3
- package/dist/templates/code-reviewer.js +5 -5
- package/dist/templates/customer-service.js +2 -2
- package/dist/templates/data-analyst.js +5 -5
- package/dist/templates/knowledge-base.js +2 -2
- package/dist/templates/sales-assistant.js +4 -4
- package/dist/templates/teacher.js +6 -6
- package/docs/.vitepress/config.ts +103 -103
- package/docs/api/cli.md +48 -48
- package/docs/api/oad-schema.md +64 -64
- package/docs/api/sdk.md +80 -80
- package/docs/guide/concepts.md +51 -51
- package/docs/guide/configuration.md +79 -79
- package/docs/guide/deployment.md +42 -42
- package/docs/guide/getting-started.md +44 -44
- package/docs/guide/templates.md +28 -28
- package/docs/guide/testing.md +84 -84
- package/docs/index.md +27 -27
- package/docs/zh/api/cli.md +54 -54
- package/docs/zh/api/oad-schema.md +87 -87
- package/docs/zh/api/sdk.md +102 -102
- package/docs/zh/guide/concepts.md +104 -104
- package/docs/zh/guide/configuration.md +135 -135
- package/docs/zh/guide/deployment.md +81 -81
- package/docs/zh/guide/getting-started.md +82 -82
- package/docs/zh/guide/templates.md +84 -84
- package/docs/zh/guide/testing.md +88 -88
- package/docs/zh/index.md +27 -27
- package/examples/customer-service-demo/README.md +90 -90
- package/examples/customer-service-demo/oad.yaml +107 -107
- package/package.json +1 -1
- package/src/analytics/index.ts +66 -66
- package/src/channels/discord.ts +192 -192
- package/src/channels/email.ts +177 -177
- package/src/channels/feishu.ts +236 -236
- package/src/channels/index.ts +15 -15
- package/src/channels/slack.ts +160 -160
- package/src/channels/telegram.ts +90 -90
- package/src/channels/voice.ts +106 -106
- package/src/channels/web.ts +596 -596
- package/src/channels/webhook.ts +199 -199
- package/src/channels/websocket.ts +87 -87
- package/src/channels/wechat.ts +149 -149
- package/src/core/a2a.ts +143 -143
- package/src/core/agent.ts +152 -152
- package/src/core/analytics-engine.ts +186 -186
- package/src/core/auth.ts +57 -57
- package/src/core/cache.ts +141 -141
- package/src/core/compose.ts +77 -77
- package/src/core/config.ts +14 -14
- package/src/core/errors.ts +148 -148
- package/src/core/hitl.ts +138 -138
- package/src/core/knowledge.ts +210 -210
- package/src/core/logger.ts +57 -57
- package/src/core/orchestrator.ts +215 -215
- package/src/core/performance.ts +187 -187
- package/src/core/rate-limiter.ts +128 -128
- package/src/core/room.ts +109 -109
- package/src/core/runtime.ts +152 -152
- package/src/core/sandbox.ts +101 -101
- package/src/core/security.ts +171 -171
- package/src/core/types.ts +68 -68
- package/src/core/versioning.ts +106 -106
- package/src/core/watch.ts +178 -178
- package/src/core/workflow.ts +235 -235
- package/src/deploy/hermes.ts +156 -156
- package/src/deploy/openclaw.ts +200 -200
- package/src/dtv/data.ts +29 -29
- package/src/dtv/trust.ts +43 -43
- package/src/dtv/value.ts +47 -47
- package/src/i18n/index.ts +216 -216
- package/src/index.ts +110 -110
- package/src/marketplace/index.ts +223 -223
- package/src/memory/deepbrain.ts +108 -108
- package/src/memory/index.ts +34 -34
- package/src/plugins/index.ts +208 -208
- package/src/providers/index.ts +322 -183
- package/src/schema/oad.ts +155 -155
- package/src/skills/base.ts +16 -16
- package/src/skills/document.ts +100 -100
- package/src/skills/http.ts +35 -35
- package/src/skills/index.ts +27 -27
- package/src/skills/scheduler.ts +80 -80
- package/src/skills/webhook-trigger.ts +59 -59
- package/src/templates/code-reviewer.ts +34 -34
- package/src/templates/customer-service.ts +80 -80
- package/src/templates/data-analyst.ts +70 -70
- package/src/templates/executive-assistant.ts +71 -71
- package/src/templates/financial-advisor.ts +60 -60
- package/src/templates/knowledge-base.ts +31 -31
- package/src/templates/legal-assistant.ts +71 -71
- package/src/templates/sales-assistant.ts +79 -79
- package/src/templates/teacher.ts +79 -79
- package/src/testing/index.ts +181 -181
- package/src/tools/calculator.ts +73 -73
- package/src/tools/datetime.ts +149 -149
- package/src/tools/json-transform.ts +187 -187
- package/src/tools/mcp.ts +76 -76
- package/src/tools/text-analysis.ts +116 -116
- package/templates/Dockerfile +15 -15
- package/templates/code-reviewer/README.md +27 -27
- package/templates/code-reviewer/oad.yaml +41 -41
- package/templates/customer-service/README.md +22 -22
- package/templates/customer-service/oad.yaml +36 -36
- package/templates/docker-compose.yml +21 -21
- package/templates/knowledge-base/README.md +28 -28
- package/templates/knowledge-base/oad.yaml +38 -38
- package/templates/sales-assistant/README.md +26 -26
- package/templates/sales-assistant/oad.yaml +43 -43
- package/tests/a2a.test.ts +66 -66
- package/tests/agent.test.ts +72 -72
- package/tests/analytics.test.ts +50 -50
- package/tests/channel.test.ts +39 -39
- package/tests/e2e.test.ts +134 -134
- package/tests/errors.test.ts +83 -83
- package/tests/hitl.test.ts +71 -71
- package/tests/i18n.test.ts +41 -41
- package/tests/mcp.test.ts +54 -54
- package/tests/oad.test.ts +68 -68
- package/tests/performance.test.ts +115 -115
- package/tests/plugin.test.ts +74 -74
- package/tests/room.test.ts +106 -106
- package/tests/runtime.test.ts +42 -42
- package/tests/sandbox.test.ts +46 -46
- package/tests/security.test.ts +60 -60
- package/tests/templates.test.ts +77 -77
- package/tests/v070.test.ts +76 -76
- package/tests/versioning.test.ts +75 -75
- package/tests/voice.test.ts +61 -61
- package/tests/webhook.test.ts +29 -29
- package/tests/workflow.test.ts +143 -143
- package/tsconfig.json +19 -19
- package/vitest.config.ts +9 -9
package/src/providers/index.ts
CHANGED
|
@@ -1,183 +1,322 @@
|
|
|
1
|
-
import type { Message } from '../core/types';
|
|
2
|
-
import * as https from 'https';
|
|
3
|
-
import * as http from 'http';
|
|
4
|
-
|
|
5
|
-
export interface LLMProvider {
|
|
6
|
-
name: string;
|
|
7
|
-
chat(messages: Message[], systemPrompt?: string): Promise<string>;
|
|
8
|
-
chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string>;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
interface OpenAIMessage {
|
|
12
|
-
role: 'system' | 'user' | 'assistant';
|
|
13
|
-
content: string;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
function getApiKey(): string {
|
|
17
|
-
return process.env.OPC_LLM_API_KEY || process.env.OPENAI_API_KEY || '';
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function getBaseUrl(): string {
|
|
21
|
-
return process.env.OPC_LLM_BASE_URL || 'https://api.openai.com/v1';
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
class OpenAICompatibleProvider implements LLMProvider {
|
|
25
|
-
name: string;
|
|
26
|
-
private model: string;
|
|
27
|
-
private baseUrl: string;
|
|
28
|
-
private apiKey: string;
|
|
29
|
-
|
|
30
|
-
constructor(name: string, model: string, baseUrl?: string, apiKey?: string) {
|
|
31
|
-
this.name = name;
|
|
32
|
-
this.model = model;
|
|
33
|
-
this.baseUrl = baseUrl || getBaseUrl();
|
|
34
|
-
this.apiKey = apiKey || getApiKey();
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
private formatMessages(messages: Message[], systemPrompt?: string): OpenAIMessage[] {
|
|
38
|
-
const formatted: OpenAIMessage[] = [];
|
|
39
|
-
if (systemPrompt) {
|
|
40
|
-
formatted.push({ role: 'system', content: systemPrompt });
|
|
41
|
-
}
|
|
42
|
-
for (const m of messages) {
|
|
43
|
-
formatted.push({ role: m.role as 'user' | 'assistant', content: m.content });
|
|
44
|
-
}
|
|
45
|
-
return formatted;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
private async request(body: any): Promise<any> {
|
|
49
|
-
if (!this.apiKey) {
|
|
50
|
-
throw new Error('No API key configured. Set OPC_LLM_API_KEY or OPENAI_API_KEY environment variable.');
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const url = new URL(`${this.baseUrl}/chat/completions`);
|
|
54
|
-
const
|
|
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
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
1
|
+
import type { Message } from '../core/types';
|
|
2
|
+
import * as https from 'https';
|
|
3
|
+
import * as http from 'http';
|
|
4
|
+
|
|
5
|
+
export interface LLMProvider {
|
|
6
|
+
name: string;
|
|
7
|
+
chat(messages: Message[], systemPrompt?: string): Promise<string>;
|
|
8
|
+
chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface OpenAIMessage {
|
|
12
|
+
role: 'system' | 'user' | 'assistant';
|
|
13
|
+
content: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function getApiKey(): string {
|
|
17
|
+
return process.env.OPC_LLM_API_KEY || process.env.OPENAI_API_KEY || '';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function getBaseUrl(): string {
|
|
21
|
+
return process.env.OPC_LLM_BASE_URL || 'https://api.openai.com/v1';
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
class OpenAICompatibleProvider implements LLMProvider {
|
|
25
|
+
name: string;
|
|
26
|
+
private model: string;
|
|
27
|
+
private baseUrl: string;
|
|
28
|
+
private apiKey: string;
|
|
29
|
+
|
|
30
|
+
constructor(name: string, model: string, baseUrl?: string, apiKey?: string) {
|
|
31
|
+
this.name = name;
|
|
32
|
+
this.model = model;
|
|
33
|
+
this.baseUrl = baseUrl || getBaseUrl();
|
|
34
|
+
this.apiKey = apiKey || getApiKey();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private formatMessages(messages: Message[], systemPrompt?: string): OpenAIMessage[] {
|
|
38
|
+
const formatted: OpenAIMessage[] = [];
|
|
39
|
+
if (systemPrompt) {
|
|
40
|
+
formatted.push({ role: 'system', content: systemPrompt });
|
|
41
|
+
}
|
|
42
|
+
for (const m of messages) {
|
|
43
|
+
formatted.push({ role: m.role as 'user' | 'assistant', content: m.content });
|
|
44
|
+
}
|
|
45
|
+
return formatted;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
private async request(body: any): Promise<any> {
|
|
49
|
+
if (!this.apiKey) {
|
|
50
|
+
throw new Error('No API key configured. Set OPC_LLM_API_KEY or OPENAI_API_KEY environment variable.');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const url = new URL(`${this.baseUrl}/chat/completions`);
|
|
54
|
+
const isGemini = url.hostname.includes('googleapis.com');
|
|
55
|
+
if (isGemini) {
|
|
56
|
+
url.searchParams.set('key', this.apiKey);
|
|
57
|
+
}
|
|
58
|
+
const isHttps = url.protocol === 'https:';
|
|
59
|
+
const lib = isHttps ? https : http;
|
|
60
|
+
|
|
61
|
+
const postData = JSON.stringify(body);
|
|
62
|
+
|
|
63
|
+
const headers: Record<string, string> = {
|
|
64
|
+
'Content-Type': 'application/json',
|
|
65
|
+
'Content-Length': String(Buffer.byteLength(postData)),
|
|
66
|
+
};
|
|
67
|
+
if (!isGemini) {
|
|
68
|
+
headers['Authorization'] = `Bearer ${this.apiKey}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const req = lib.request(
|
|
73
|
+
{
|
|
74
|
+
hostname: url.hostname,
|
|
75
|
+
port: url.port || (isHttps ? 443 : 80),
|
|
76
|
+
path: url.pathname + url.search,
|
|
77
|
+
method: 'POST',
|
|
78
|
+
headers,
|
|
79
|
+
},
|
|
80
|
+
(res) => {
|
|
81
|
+
let data = '';
|
|
82
|
+
res.on('data', (chunk: Buffer) => (data += chunk.toString()));
|
|
83
|
+
res.on('end', () => {
|
|
84
|
+
if (res.statusCode && res.statusCode >= 400) {
|
|
85
|
+
reject(new Error(`LLM API error ${res.statusCode}: ${data}`));
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
resolve(JSON.parse(data));
|
|
90
|
+
} catch {
|
|
91
|
+
reject(new Error(`Invalid JSON response: ${data.slice(0, 200)}`));
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
);
|
|
96
|
+
req.on('error', reject);
|
|
97
|
+
req.write(postData);
|
|
98
|
+
req.end();
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async chat(messages: Message[], systemPrompt?: string): Promise<string> {
|
|
103
|
+
if (!this.apiKey) {
|
|
104
|
+
// Stub mode when no API key
|
|
105
|
+
const last = messages[messages.length - 1];
|
|
106
|
+
return `[${this.name}/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
|
|
107
|
+
}
|
|
108
|
+
const formatted = this.formatMessages(messages, systemPrompt);
|
|
109
|
+
const result = await this.request({
|
|
110
|
+
model: this.model,
|
|
111
|
+
messages: formatted,
|
|
112
|
+
temperature: 0.7,
|
|
113
|
+
max_tokens: 2048,
|
|
114
|
+
});
|
|
115
|
+
return result.choices?.[0]?.message?.content ?? '';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async *chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string> {
|
|
119
|
+
if (!this.apiKey) {
|
|
120
|
+
const last = messages[messages.length - 1];
|
|
121
|
+
yield `[${this.name}/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const formatted = this.formatMessages(messages, systemPrompt);
|
|
126
|
+
const url = new URL(`${this.baseUrl}/chat/completions`);
|
|
127
|
+
const isGemini = url.hostname.includes('googleapis.com');
|
|
128
|
+
if (isGemini) {
|
|
129
|
+
url.searchParams.set('key', this.apiKey);
|
|
130
|
+
}
|
|
131
|
+
const isHttps = url.protocol === 'https:';
|
|
132
|
+
const lib = isHttps ? https : http;
|
|
133
|
+
const postData = JSON.stringify({
|
|
134
|
+
model: this.model,
|
|
135
|
+
messages: formatted,
|
|
136
|
+
temperature: 0.7,
|
|
137
|
+
max_tokens: 2048,
|
|
138
|
+
stream: true,
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
const streamHeaders: Record<string, string> = {
|
|
142
|
+
'Content-Type': 'application/json',
|
|
143
|
+
'Content-Length': String(Buffer.byteLength(postData)),
|
|
144
|
+
};
|
|
145
|
+
if (!isGemini) {
|
|
146
|
+
streamHeaders['Authorization'] = `Bearer ${this.apiKey}`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const response = await new Promise<http.IncomingMessage>((resolve, reject) => {
|
|
150
|
+
const req = lib.request(
|
|
151
|
+
{
|
|
152
|
+
hostname: url.hostname,
|
|
153
|
+
port: url.port || (isHttps ? 443 : 80),
|
|
154
|
+
path: url.pathname + url.search,
|
|
155
|
+
method: 'POST',
|
|
156
|
+
headers: streamHeaders,
|
|
157
|
+
},
|
|
158
|
+
resolve,
|
|
159
|
+
);
|
|
160
|
+
req.on('error', reject);
|
|
161
|
+
req.write(postData);
|
|
162
|
+
req.end();
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
if (response.statusCode && response.statusCode >= 400) {
|
|
166
|
+
let data = '';
|
|
167
|
+
for await (const chunk of response) data += chunk.toString();
|
|
168
|
+
throw new Error(`LLM API error ${response.statusCode}: ${data}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
let buffer = '';
|
|
172
|
+
for await (const chunk of response) {
|
|
173
|
+
buffer += chunk.toString();
|
|
174
|
+
const lines = buffer.split('\n');
|
|
175
|
+
buffer = lines.pop() ?? '';
|
|
176
|
+
|
|
177
|
+
for (const line of lines) {
|
|
178
|
+
const trimmed = line.trim();
|
|
179
|
+
if (!trimmed || !trimmed.startsWith('data: ')) continue;
|
|
180
|
+
const data = trimmed.slice(6);
|
|
181
|
+
if (data === '[DONE]') return;
|
|
182
|
+
try {
|
|
183
|
+
const parsed = JSON.parse(data);
|
|
184
|
+
const content = parsed.choices?.[0]?.delta?.content;
|
|
185
|
+
if (content) yield content;
|
|
186
|
+
} catch {
|
|
187
|
+
// skip malformed lines
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
class GeminiNativeProvider implements LLMProvider {
|
|
195
|
+
name = 'gemini';
|
|
196
|
+
private model: string;
|
|
197
|
+
private apiKey: string;
|
|
198
|
+
|
|
199
|
+
constructor(model: string, apiKey?: string) {
|
|
200
|
+
this.model = model;
|
|
201
|
+
this.apiKey = apiKey || getApiKey();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private buildUrl(stream: boolean): string {
|
|
205
|
+
const action = stream ? 'streamGenerateContent?alt=sse&' : 'generateContent?';
|
|
206
|
+
return `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:${action}key=${this.apiKey}`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private formatContents(messages: Message[], systemPrompt?: string): { contents: any[]; systemInstruction?: any } {
|
|
210
|
+
const contents: any[] = [];
|
|
211
|
+
for (const m of messages) {
|
|
212
|
+
contents.push({ role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }] });
|
|
213
|
+
}
|
|
214
|
+
const result: any = { contents };
|
|
215
|
+
if (systemPrompt) {
|
|
216
|
+
result.systemInstruction = { parts: [{ text: systemPrompt }] };
|
|
217
|
+
}
|
|
218
|
+
return result;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async chat(messages: Message[], systemPrompt?: string): Promise<string> {
|
|
222
|
+
if (!this.apiKey) {
|
|
223
|
+
const last = messages[messages.length - 1];
|
|
224
|
+
return `[gemini/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
|
|
225
|
+
}
|
|
226
|
+
const body = this.formatContents(messages, systemPrompt);
|
|
227
|
+
const url = this.buildUrl(false);
|
|
228
|
+
const postData = JSON.stringify(body);
|
|
229
|
+
|
|
230
|
+
return new Promise((resolve, reject) => {
|
|
231
|
+
const parsedUrl = new URL(url);
|
|
232
|
+
const req = https.request({
|
|
233
|
+
hostname: parsedUrl.hostname,
|
|
234
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
235
|
+
method: 'POST',
|
|
236
|
+
headers: { 'Content-Type': 'application/json', 'Content-Length': String(Buffer.byteLength(postData)) },
|
|
237
|
+
}, (res) => {
|
|
238
|
+
let data = '';
|
|
239
|
+
res.on('data', (chunk: Buffer) => (data += chunk.toString()));
|
|
240
|
+
res.on('end', () => {
|
|
241
|
+
if (res.statusCode && res.statusCode >= 400) { reject(new Error(`Gemini API error ${res.statusCode}: ${data}`)); return; }
|
|
242
|
+
try {
|
|
243
|
+
const parsed = JSON.parse(data);
|
|
244
|
+
resolve(parsed.candidates?.[0]?.content?.parts?.[0]?.text ?? '');
|
|
245
|
+
} catch { reject(new Error(`Invalid Gemini response: ${data.slice(0, 200)}`)); }
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
req.on('error', reject);
|
|
249
|
+
req.write(postData);
|
|
250
|
+
req.end();
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async *chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string> {
|
|
255
|
+
if (!this.apiKey) {
|
|
256
|
+
const last = messages[messages.length - 1];
|
|
257
|
+
yield `[gemini/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const body = this.formatContents(messages, systemPrompt);
|
|
261
|
+
const url = this.buildUrl(true);
|
|
262
|
+
const postData = JSON.stringify(body);
|
|
263
|
+
const parsedUrl = new URL(url);
|
|
264
|
+
|
|
265
|
+
const response = await new Promise<http.IncomingMessage>((resolve, reject) => {
|
|
266
|
+
const req = https.request({
|
|
267
|
+
hostname: parsedUrl.hostname,
|
|
268
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
269
|
+
method: 'POST',
|
|
270
|
+
headers: { 'Content-Type': 'application/json', 'Content-Length': String(Buffer.byteLength(postData)) },
|
|
271
|
+
}, resolve);
|
|
272
|
+
req.on('error', reject);
|
|
273
|
+
req.write(postData);
|
|
274
|
+
req.end();
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
if (response.statusCode && response.statusCode >= 400) {
|
|
278
|
+
let data = '';
|
|
279
|
+
for await (const chunk of response) data += chunk.toString();
|
|
280
|
+
throw new Error(`Gemini API error ${response.statusCode}: ${data}`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
let buffer = '';
|
|
284
|
+
for await (const chunk of response) {
|
|
285
|
+
buffer += chunk.toString();
|
|
286
|
+
const lines = buffer.split('\n');
|
|
287
|
+
buffer = lines.pop() ?? '';
|
|
288
|
+
for (const line of lines) {
|
|
289
|
+
const trimmed = line.trim();
|
|
290
|
+
if (!trimmed.startsWith('data: ')) continue;
|
|
291
|
+
const data = trimmed.slice(6);
|
|
292
|
+
if (data === '[DONE]') return;
|
|
293
|
+
try {
|
|
294
|
+
const parsed = JSON.parse(data);
|
|
295
|
+
const text = parsed.candidates?.[0]?.content?.parts?.[0]?.text;
|
|
296
|
+
if (text) yield text;
|
|
297
|
+
} catch {}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function isGeminiNative(): boolean {
|
|
304
|
+
const baseUrl = process.env.OPC_LLM_BASE_URL || '';
|
|
305
|
+
const key = getApiKey();
|
|
306
|
+
// Use native Gemini API when: key starts with AQ. (new format) OR base URL points to googleapis
|
|
307
|
+
return key.startsWith('AQ.') || (baseUrl.includes('googleapis.com') && !baseUrl.includes('/openai'));
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export function createProvider(name: string = 'openai', model?: string, baseUrl?: string, apiKey?: string): LLMProvider {
|
|
311
|
+
const finalModel = model || process.env.OPC_LLM_MODEL || 'gpt-4o-mini';
|
|
312
|
+
const finalKey = apiKey || getApiKey();
|
|
313
|
+
|
|
314
|
+
// Auto-detect Gemini native when key is new format
|
|
315
|
+
if (finalKey.startsWith('AQ.') || isGeminiNative()) {
|
|
316
|
+
return new GeminiNativeProvider(finalModel, finalKey);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return new OpenAICompatibleProvider(name, finalModel, baseUrl, apiKey);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export const SUPPORTED_PROVIDERS = ['openai', 'deepseek', 'qwen', 'gemini'] as const;
|