@astack-tech/integrations 0.1.1-beta.6 → 0.2.0-beta.11

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/dist/index.cjs CHANGED
@@ -37,310 +37,317 @@ module.exports = __toCommonJS(src_exports);
37
37
  // src/model-provider/index.ts
38
38
  var model_provider_exports = {};
39
39
  __export(model_provider_exports, {
40
- Deepseek: () => deepseek_default
40
+ Deepseek: () => deepseek_default,
41
+ OpenAICompatible: () => openai_compatible_default
41
42
  });
42
43
 
43
- // src/model-provider/deepseek/index.ts
44
+ // src/model-provider/openai-compatible/index.ts
44
45
  var import_core = require("@astack-tech/core");
45
46
  var import_openai = __toESM(require("openai"), 1);
46
- var Deepseek = class extends import_core.Component {
47
+ var DEFAULT_BASE_URL = "https://api.openai.com/v1";
48
+ var DEFAULT_NAME = "The model API";
49
+ var DEFAULT_TEMPERATURE = 0.7;
50
+ var FALLBACK_TEXT = "API call failed";
51
+ function isRecord(value) {
52
+ return typeof value === "object" && value !== null && !Array.isArray(value);
53
+ }
54
+ function isOptionalString(value) {
55
+ return value === void 0 || typeof value === "string";
56
+ }
57
+ function isCount(value) {
58
+ return typeof value === "number" && Number.isFinite(value);
59
+ }
60
+ function isTokenUsage(value) {
61
+ return isRecord(value) && isCount(value["completion_tokens"]) && isCount(value["prompt_tokens"]) && isCount(value["total_tokens"]) && (value["prompt_cache_hit_tokens"] === void 0 || isCount(value["prompt_cache_hit_tokens"])) && (value["prompt_cache_miss_tokens"] === void 0 || isCount(value["prompt_cache_miss_tokens"]));
62
+ }
63
+ function isMessage(value) {
64
+ return isRecord(value) && typeof value["role"] === "string" && isOptionalString(value["content"]) && (value["tool_calls"] === void 0 || Array.isArray(value["tool_calls"])) && isOptionalString(value["tool_call_id"]) && (value["usage"] === void 0 || isTokenUsage(value["usage"]));
65
+ }
66
+ function isMessageList(value) {
67
+ return Array.isArray(value) && value.every((item) => isMessage(item));
68
+ }
69
+ function toApiTool(tool) {
70
+ const raw = isRecord(tool) ? tool : {};
71
+ const definition = raw["function"];
72
+ if (raw["type"] === "function" && isRecord(definition)) {
73
+ const { name: name2, description: description2, parameters: parameters2, strict } = definition;
74
+ return {
75
+ type: "function",
76
+ function: {
77
+ name: typeof name2 === "string" ? name2 : "",
78
+ ...typeof description2 === "string" ? { description: description2 } : {},
79
+ ...isRecord(parameters2) ? { parameters: parameters2 } : {},
80
+ ...typeof strict === "boolean" ? { strict } : {}
81
+ }
82
+ };
83
+ }
84
+ const { name, description, parameters } = raw;
85
+ return {
86
+ type: "function",
87
+ function: {
88
+ name: typeof name === "string" ? name : "",
89
+ description: typeof description === "string" ? description : "",
90
+ parameters: isRecord(parameters) ? parameters : {}
91
+ }
92
+ };
93
+ }
94
+ function parseArguments(raw) {
95
+ if (raw.trim().length === 0) {
96
+ return {};
97
+ }
98
+ try {
99
+ const parsed = JSON.parse(raw);
100
+ return isRecord(parsed) ? parsed : {};
101
+ } catch {
102
+ return {};
103
+ }
104
+ }
105
+ function mapUsage(usage) {
106
+ return {
107
+ completion_tokens: usage.completion_tokens ?? 0,
108
+ prompt_tokens: usage.prompt_tokens ?? 0,
109
+ total_tokens: usage.total_tokens ?? 0,
110
+ ...usage.prompt_cache_hit_tokens === void 0 ? {} : { prompt_cache_hit_tokens: usage.prompt_cache_hit_tokens },
111
+ ...usage.prompt_cache_miss_tokens === void 0 ? {} : { prompt_cache_miss_tokens: usage.prompt_cache_miss_tokens }
112
+ };
113
+ }
114
+ var OpenAICompatible = class extends import_core.Component {
115
+ client;
116
+ model;
117
+ temperature;
118
+ maxTokens;
119
+ topP;
120
+ systemPrompt;
121
+ tools;
122
+ verbose;
123
+ name;
47
124
  constructor(config) {
48
125
  super({});
49
126
  this.client = new import_openai.default({
50
127
  apiKey: config.apiKey,
51
- baseURL: config.baseURL || "https://api.deepseek.com/v1",
128
+ baseURL: config.baseURL ?? DEFAULT_BASE_URL,
52
129
  dangerouslyAllowBrowser: config.dangerouslyAllowBrowser ?? false
53
130
  });
54
- this.model = config.model || "deepseek-chat";
55
- this.temperature = config.temperature ?? 0.7;
131
+ this.model = config.model;
132
+ this.name = config.name ?? DEFAULT_NAME;
133
+ this.temperature = config.temperature ?? DEFAULT_TEMPERATURE;
56
134
  this.maxTokens = config.maxTokens;
57
135
  this.topP = config.topP;
58
136
  this.systemPrompt = config.systemPrompt;
59
- if (config.rawTools && config.rawTools.length > 0) {
60
- this.tools = config.rawTools.map((tool) => ({
61
- type: "function",
62
- function: {
63
- name: tool.name,
64
- description: tool.description,
65
- parameters: tool.parameters || {}
66
- }
67
- }));
68
- } else {
69
- this.tools = config.tools;
70
- }
137
+ this.verbose = config.verbose ?? false;
138
+ this.tools = config.rawTools !== void 0 && config.rawTools.length > 0 ? config.rawTools.map(toApiTool) : config.tools;
71
139
  import_core.Component.Port.I("prompt").attach(this);
72
140
  import_core.Component.Port.I("messages").attach(this);
73
141
  import_core.Component.Port.O("completion").attach(this);
74
142
  import_core.Component.Port.O("message").attach(this);
75
143
  }
76
144
  /**
77
- * 生成文本完成
78
- * @param prompt 提示文本
79
- * @returns 生成的文本
145
+ * Generates a completion for a single prompt.
146
+ *
147
+ * @returns The text answer, or the JSON-encoded assistant message when it contains tool calls.
80
148
  */
81
149
  async generateCompletion(prompt) {
82
- const messages = [];
83
- if (this.systemPrompt) {
84
- messages.push({
85
- role: "system",
86
- content: this.systemPrompt
87
- });
88
- }
89
- messages.push({
90
- role: "user",
91
- content: prompt
150
+ const response = await this.client.chat.completions.create({
151
+ ...this.baseRequest(),
152
+ messages: [...this.systemMessages(), { role: "user", content: prompt }],
153
+ ...this.toolsParam(this.tools)
92
154
  });
93
- const requestParams = {
94
- model: this.model,
95
- messages,
96
- temperature: this.temperature,
97
- max_tokens: this.maxTokens,
98
- top_p: this.topP
99
- };
100
- if (this.tools && this.tools.length > 0) {
101
- requestParams.tools = this.tools;
102
- }
103
- const response = await this.client.chat.completions.create(requestParams);
104
- if (response.choices[0].message.tool_calls && response.choices[0].message.tool_calls.length > 0) {
105
- return JSON.stringify(response.choices[0].message);
155
+ const message = this.firstMessage(response);
156
+ if (message.tool_calls !== void 0 && message.tool_calls.length > 0) {
157
+ return JSON.stringify(message);
106
158
  }
107
- return response.choices[0].message.content || "";
159
+ return message.content ?? "";
108
160
  }
109
161
  /**
110
- * 流式处理对话消息
111
- * @param messages 对话消息数组
112
- * @param options 可选的调用选项,包含临时工具列表
113
- * @returns 生成的流式响应消息异步生成器
162
+ * Sends a conversation and returns the assistant reply.
114
163
  */
115
- async *streamChatCompletion(messages, options) {
116
- const formattedMessages = [];
117
- if (this.systemPrompt) {
118
- formattedMessages.push({
119
- role: "system",
120
- content: this.systemPrompt
121
- });
164
+ async chatCompletion(messages, options) {
165
+ const response = await this.client.chat.completions.create({
166
+ ...this.baseRequest(),
167
+ messages: this.formatMessages(messages),
168
+ ...this.toolsParam(options?.temporaryTools ?? this.tools)
169
+ });
170
+ const message = this.firstMessage(response);
171
+ const result = { role: "assistant", content: message.content ?? "" };
172
+ if (response.usage !== void 0) {
173
+ result.usage = mapUsage(response.usage);
122
174
  }
123
- formattedMessages.push(
124
- ...messages.map((msg) => {
125
- const formattedMsg = {
126
- role: msg.role,
127
- content: msg.content
128
- };
129
- if (msg.role === "tool" && msg.tool_call_id) {
130
- formattedMsg.tool_call_id = msg.tool_call_id;
131
- }
132
- return formattedMsg;
133
- })
134
- );
135
- const requestParams = {
136
- model: this.model,
137
- messages: formattedMessages,
138
- temperature: this.temperature,
139
- max_tokens: this.maxTokens,
140
- top_p: this.topP,
141
- stream: true
142
- // 开启流式模式
143
- };
144
- const toolsToUse = options?.temporaryTools || this.tools;
145
- if (toolsToUse && toolsToUse.length > 0) {
146
- const formattedTools = toolsToUse.map((tool) => {
147
- const typedTool = tool;
148
- if (typedTool.type === "function") {
149
- return tool;
175
+ if (message.tool_calls !== void 0 && message.tool_calls.length > 0) {
176
+ result.tool_calls = message.tool_calls.map((toolCall) => {
177
+ if (toolCall.type !== "function") {
178
+ throw new Error(`Unsupported tool call type: ${toolCall.type}`);
150
179
  }
180
+ const rawArguments = toolCall.function.arguments;
151
181
  return {
182
+ id: toolCall.id,
152
183
  type: "function",
153
184
  function: {
154
- name: typedTool.name,
155
- description: typedTool.description,
156
- parameters: typedTool.parameters || {}
157
- }
185
+ name: toolCall.function.name,
186
+ arguments: rawArguments.length > 0 ? rawArguments : "{}"
187
+ },
188
+ tool_name: toolCall.function.name,
189
+ arguments: parseArguments(rawArguments)
158
190
  };
159
191
  });
160
- requestParams.tools = formattedTools;
161
192
  }
162
- const stream = await this.client.chat.completions.create(requestParams);
193
+ return result;
194
+ }
195
+ /**
196
+ * Streams the assistant reply. Each chunk holds a text delta, tool-call deltas, or usage.
197
+ */
198
+ async *streamChatCompletion(messages, options) {
199
+ const stream = await this.client.chat.completions.create({
200
+ ...this.baseRequest(),
201
+ messages: this.formatMessages(messages),
202
+ ...this.toolsParam(options?.temporaryTools ?? this.tools),
203
+ stream: true
204
+ });
163
205
  for await (const chunk of stream) {
164
206
  const delta = chunk.choices[0]?.delta;
165
- if (delta?.content) {
166
- yield {
167
- role: "assistant",
168
- content: delta.content
169
- };
207
+ const text = delta?.content ?? "";
208
+ if (text !== "") {
209
+ yield { role: "assistant", content: text };
170
210
  }
171
211
  if (delta?.tool_calls) {
172
212
  yield {
173
213
  role: "assistant",
174
214
  content: "",
175
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
176
- tool_calls: delta.tool_calls.map((toolCall) => ({
177
- id: toolCall.id || "",
178
- function: {
179
- name: toolCall.function?.name || "",
180
- arguments: toolCall.function?.arguments || ""
181
- },
182
- type: "function",
183
- tool_name: toolCall.function?.name || "",
184
- arguments: toolCall.function?.arguments || ""
185
- }))
215
+ tool_calls: delta.tool_calls.map((toolCall) => {
216
+ const name = toolCall.function?.name ?? "";
217
+ const args = toolCall.function?.arguments ?? "";
218
+ return {
219
+ id: toolCall.id ?? "",
220
+ type: "function",
221
+ function: { name, arguments: args },
222
+ tool_name: name,
223
+ arguments: args
224
+ };
225
+ })
186
226
  };
187
227
  }
188
228
  if (chunk.usage) {
189
- yield {
190
- role: "assistant",
191
- content: "",
192
- usage: {
193
- completion_tokens: chunk.usage.completion_tokens || 0,
194
- prompt_tokens: chunk.usage.prompt_tokens || 0,
195
- prompt_cache_hit_tokens: chunk.usage.prompt_cache_hit_tokens,
196
- prompt_cache_miss_tokens: chunk.usage.prompt_cache_miss_tokens,
197
- total_tokens: chunk.usage.total_tokens || 0
198
- }
199
- };
229
+ yield { role: "assistant", content: "", usage: mapUsage(chunk.usage) };
200
230
  }
201
231
  }
202
232
  }
203
233
  /**
204
- * 处理对话消息
205
- * @param messages 对话消息数组
206
- * @param options 可选的调用选项,包含临时工具列表
207
- * @returns 生成的响应消息
234
+ * Runs the model outside a pipeline.
235
+ *
236
+ * @param input - A prompt string or a list of messages.
208
237
  */
209
- async chatCompletion(messages, options) {
210
- const formattedMessages = [];
211
- if (this.systemPrompt) {
212
- formattedMessages.push({
213
- role: "system",
214
- content: this.systemPrompt
215
- });
216
- }
217
- formattedMessages.push(
218
- ...messages.map((msg) => {
219
- const formattedMsg = {
220
- role: msg.role,
221
- content: msg.content
222
- };
223
- if (msg.role === "tool" && msg.tool_call_id) {
224
- formattedMsg.tool_call_id = msg.tool_call_id;
238
+ run(input) {
239
+ return typeof input === "string" ? this.generateCompletion(input) : this.chatCompletion(input);
240
+ }
241
+ /**
242
+ * Connects the `prompt` and `messages` input ports to the model.
243
+ * API errors produce a fallback value so the pipeline keeps flowing. Input of the wrong
244
+ * type fails the pipeline run with a `TypeError` before the API is called.
245
+ */
246
+ _transform($i, $o) {
247
+ $i("prompt").receive((prompt) => {
248
+ if (typeof prompt !== "string") {
249
+ throw new TypeError(`${this.name}: the prompt port expects a string.`);
250
+ }
251
+ return this.generateCompletion(prompt).then(
252
+ (completion) => {
253
+ $o("completion").send(completion);
254
+ },
255
+ (error) => {
256
+ this.logError(error);
257
+ $o("completion").send(FALLBACK_TEXT);
225
258
  }
226
- return formattedMsg;
227
- })
228
- );
229
- const requestParams = {
259
+ );
260
+ });
261
+ $i("messages").receive((messages) => {
262
+ if (!isMessageList(messages)) {
263
+ throw new TypeError(`${this.name}: the messages port expects an array of messages.`);
264
+ }
265
+ return this.chatCompletion(messages).then(
266
+ (message) => {
267
+ $o("message").send(message);
268
+ },
269
+ (error) => {
270
+ this.logError(error);
271
+ $o("message").send({ role: "assistant", content: FALLBACK_TEXT });
272
+ }
273
+ );
274
+ });
275
+ }
276
+ baseRequest() {
277
+ return {
230
278
  model: this.model,
231
- messages: formattedMessages,
232
279
  temperature: this.temperature,
233
- max_tokens: this.maxTokens,
234
- top_p: this.topP
280
+ ...this.maxTokens === void 0 ? {} : { max_tokens: this.maxTokens },
281
+ ...this.topP === void 0 ? {} : { top_p: this.topP }
235
282
  };
236
- const toolsToUse = options?.temporaryTools || this.tools;
237
- if (toolsToUse && toolsToUse.length > 0) {
238
- const formattedTools = toolsToUse.map((tool) => {
239
- const typedTool = tool;
240
- if (typedTool.type === "function") {
241
- return tool;
242
- }
243
- return {
244
- type: "function",
245
- function: {
246
- name: typedTool.name,
247
- description: typedTool.description,
248
- parameters: typedTool.parameters || {}
249
- }
250
- };
251
- });
252
- requestParams.tools = formattedTools;
253
- }
254
- const response = await this.client.chat.completions.create(requestParams);
255
- const responseMessage = response.choices[0].message;
256
- const result = {
257
- role: "assistant",
258
- content: responseMessage.content || ""
259
- };
260
- if (response.usage) {
261
- const usage = response.usage;
262
- result.usage = {
263
- completion_tokens: usage.completion_tokens || 0,
264
- prompt_tokens: usage.prompt_tokens || 0,
265
- prompt_cache_hit_tokens: usage.prompt_cache_hit_tokens,
266
- prompt_cache_miss_tokens: usage.prompt_cache_miss_tokens,
267
- total_tokens: usage.total_tokens || 0
268
- };
269
- }
270
- if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {
271
- result.tool_calls = responseMessage.tool_calls.map((toolCall) => {
272
- if (toolCall.type !== "function" || !("function" in toolCall)) {
273
- throw new Error(`Unsupported tool call type: ${toolCall.type}`);
274
- }
275
- let args;
276
- const rawArgs = toolCall.function.arguments;
277
- if (typeof rawArgs === "string") {
278
- const raw = rawArgs;
279
- try {
280
- args = raw && raw.trim().length > 0 ? JSON.parse(raw) : {};
281
- } catch {
282
- args = {};
283
- }
284
- } else if (rawArgs && typeof rawArgs === "object") {
285
- args = rawArgs;
286
- } else {
287
- args = {};
288
- }
289
- return {
290
- id: toolCall.id,
291
- // 满足 Agent 组件期望的格式
292
- function: {
293
- name: toolCall.function.name,
294
- arguments: toolCall.function.arguments || "{}"
295
- },
296
- type: "function",
297
- // 满足内部 ToolCall 接口
298
- tool_name: toolCall.function.name,
299
- arguments: args
300
- };
301
- });
302
- }
303
- return result;
283
+ }
284
+ toolsParam(tools) {
285
+ return tools !== void 0 && tools.length > 0 ? { tools: tools.map(toApiTool) } : {};
286
+ }
287
+ systemMessages() {
288
+ return this.systemPrompt === void 0 || this.systemPrompt === "" ? [] : [{ role: "system", content: this.systemPrompt }];
304
289
  }
305
290
  /**
306
- * 在独立模式下运行组件
307
- * @param input 输入参数,可以是提示文本或对话消息数组
308
- * @returns 生成的文本或响应消息
291
+ * Converts input messages to API messages. Assistant `tool_calls` are not forwarded:
292
+ * agents send tool results back as user messages, and the API rejects assistant tool
293
+ * calls that are not followed by tool messages.
309
294
  */
310
- async run(input) {
311
- if (typeof input === "string") {
312
- return this.generateCompletion(input);
313
- } else {
314
- return this.chatCompletion(input);
315
- }
295
+ formatMessages(messages) {
296
+ return [...this.systemMessages(), ...messages.map((message) => this.toApiMessage(message))];
316
297
  }
317
298
  /**
318
- * 在流水线中运行组件
319
- * @param $i 输入端口
320
- * @param $o 输出端口
299
+ * Converts one input message to its API shape.
300
+ *
301
+ * @throws Error when the role is not one of `MessageRole`, or a `tool` message has no
302
+ * `tool_call_id`. The API would reject both.
321
303
  */
322
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
323
- _transform($i, $o) {
324
- $i("prompt").receive(async (prompt) => {
325
- try {
326
- const completion = await this.generateCompletion(prompt);
327
- $o("completion").send(completion);
328
- } catch (error) {
329
- console.error("Deepseek API \u8C03\u7528\u9519\u8BEF:", error);
330
- $o("completion").send("API \u8C03\u7528\u9519\u8BEF");
331
- }
332
- });
333
- $i("messages").receive(async (messages) => {
334
- try {
335
- const responseMessage = await this.chatCompletion(messages);
336
- $o("message").send(responseMessage);
337
- } catch (error) {
338
- console.error("Deepseek API \u8C03\u7528\u9519\u8BEF:", error);
339
- $o("message").send({
340
- role: "assistant",
341
- content: "API \u8C03\u7528\u9519\u8BEF"
342
- });
343
- }
304
+ toApiMessage(message) {
305
+ const content = message.content ?? "";
306
+ switch (message.role) {
307
+ case "system":
308
+ return { role: "system", content };
309
+ case "user":
310
+ return { role: "user", content };
311
+ case "assistant":
312
+ return message.content === void 0 ? { role: "assistant" } : { role: "assistant", content: message.content };
313
+ case "tool":
314
+ if (message.tool_call_id === void 0 || message.tool_call_id === "") {
315
+ throw new Error(
316
+ `${this.name}: a tool message needs the tool_call_id of the call it answers.`
317
+ );
318
+ }
319
+ return { role: "tool", content, tool_call_id: message.tool_call_id };
320
+ default:
321
+ throw new Error(
322
+ `${this.name}: unsupported message role '${message.role}'. Use system, user, assistant or tool.`
323
+ );
324
+ }
325
+ }
326
+ firstMessage(response) {
327
+ const choice = response.choices[0];
328
+ if (choice === void 0) {
329
+ throw new Error(`${this.name} returned no choices.`);
330
+ }
331
+ return choice.message;
332
+ }
333
+ logError(error) {
334
+ if (this.verbose) {
335
+ console.error(`[${this.name}] API call failed:`, error);
336
+ }
337
+ }
338
+ };
339
+ var openai_compatible_default = OpenAICompatible;
340
+
341
+ // src/model-provider/deepseek/index.ts
342
+ var DEFAULT_BASE_URL2 = "https://api.deepseek.com/v1";
343
+ var DEFAULT_MODEL = "deepseek-chat";
344
+ var Deepseek = class extends openai_compatible_default {
345
+ constructor(config) {
346
+ super({
347
+ ...config,
348
+ model: config.model ?? DEFAULT_MODEL,
349
+ baseURL: config.baseURL ?? DEFAULT_BASE_URL2,
350
+ name: "DeepSeek"
344
351
  });
345
352
  }
346
353
  };