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

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