@astack-tech/integrations 0.1.1-beta.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.
@@ -0,0 +1,178 @@
1
+ // src/model-provider/deepseek/index.ts
2
+ import { Component } from "@astack-tech/core";
3
+ import OpenAI from "openai";
4
+ var Deepseek = class extends Component {
5
+ constructor(config) {
6
+ super({});
7
+ this.client = new OpenAI({
8
+ apiKey: config.apiKey,
9
+ baseURL: config.baseURL || "https://api.deepseek.com/v1"
10
+ });
11
+ this.model = config.model || "deepseek-chat";
12
+ this.temperature = config.temperature ?? 0.7;
13
+ this.maxTokens = config.maxTokens;
14
+ this.topP = config.topP;
15
+ this.systemPrompt = config.systemPrompt;
16
+ if (config.rawTools && config.rawTools.length > 0) {
17
+ this.tools = config.rawTools.map((tool) => ({
18
+ type: "function",
19
+ function: {
20
+ name: tool.name,
21
+ description: tool.description,
22
+ parameters: tool.parameters || {}
23
+ }
24
+ }));
25
+ } else {
26
+ this.tools = config.tools;
27
+ }
28
+ Component.Port.I("prompt").attach(this);
29
+ Component.Port.I("messages").attach(this);
30
+ Component.Port.O("completion").attach(this);
31
+ Component.Port.O("message").attach(this);
32
+ }
33
+ /**
34
+ * 生成文本完成
35
+ * @param prompt 提示文本
36
+ * @returns 生成的文本
37
+ */
38
+ async generateCompletion(prompt) {
39
+ const messages = [];
40
+ if (this.systemPrompt) {
41
+ messages.push({
42
+ role: "system",
43
+ content: this.systemPrompt
44
+ });
45
+ }
46
+ messages.push({
47
+ role: "user",
48
+ content: prompt
49
+ });
50
+ const requestParams = {
51
+ model: this.model,
52
+ messages,
53
+ temperature: this.temperature,
54
+ max_tokens: this.maxTokens,
55
+ top_p: this.topP
56
+ };
57
+ if (this.tools && this.tools.length > 0) {
58
+ requestParams.tools = this.tools;
59
+ }
60
+ const response = await this.client.chat.completions.create(requestParams);
61
+ if (response.choices[0].message.tool_calls && response.choices[0].message.tool_calls.length > 0) {
62
+ return JSON.stringify(response.choices[0].message);
63
+ }
64
+ return response.choices[0].message.content || "";
65
+ }
66
+ /**
67
+ * 处理对话消息
68
+ * @param messages 对话消息数组
69
+ * @param options 可选的调用选项,包含临时工具列表
70
+ * @returns 生成的响应消息
71
+ */
72
+ async chatCompletion(messages, options) {
73
+ const formattedMessages = [];
74
+ if (this.systemPrompt) {
75
+ formattedMessages.push({
76
+ role: "system",
77
+ content: this.systemPrompt
78
+ });
79
+ }
80
+ formattedMessages.push(
81
+ ...messages.map((msg) => {
82
+ const formattedMsg = {
83
+ role: msg.role,
84
+ content: msg.content
85
+ };
86
+ if (msg.role === "tool" && msg.tool_call_id) {
87
+ formattedMsg.tool_call_id = msg.tool_call_id;
88
+ }
89
+ return formattedMsg;
90
+ })
91
+ );
92
+ const requestParams = {
93
+ model: this.model,
94
+ messages: formattedMessages,
95
+ temperature: this.temperature,
96
+ max_tokens: this.maxTokens,
97
+ top_p: this.topP
98
+ };
99
+ const toolsToUse = options?.temporaryTools || this.tools;
100
+ if (toolsToUse && toolsToUse.length > 0) {
101
+ const formattedTools = toolsToUse.map((tool) => {
102
+ const typedTool = tool;
103
+ if (typedTool.type === "function") {
104
+ return tool;
105
+ }
106
+ return {
107
+ type: "function",
108
+ function: {
109
+ name: typedTool.name,
110
+ description: typedTool.description,
111
+ parameters: typedTool.parameters || {}
112
+ }
113
+ };
114
+ });
115
+ requestParams.tools = formattedTools;
116
+ }
117
+ const response = await this.client.chat.completions.create(requestParams);
118
+ const responseMessage = response.choices[0].message;
119
+ const result = {
120
+ role: "assistant",
121
+ content: responseMessage.content || ""
122
+ };
123
+ if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {
124
+ result.tool_calls = responseMessage.tool_calls.map((toolCall) => ({
125
+ id: toolCall.id,
126
+ tool_name: toolCall.function.name,
127
+ arguments: JSON.parse(toolCall.function.arguments || "{}")
128
+ }));
129
+ }
130
+ return result;
131
+ }
132
+ /**
133
+ * 在独立模式下运行组件
134
+ * @param input 输入参数,可以是提示文本或对话消息数组
135
+ * @returns 生成的文本或响应消息
136
+ */
137
+ async run(input) {
138
+ if (typeof input === "string") {
139
+ return this.generateCompletion(input);
140
+ } else {
141
+ return this.chatCompletion(input);
142
+ }
143
+ }
144
+ /**
145
+ * 在流水线中运行组件
146
+ * @param $i 输入端口
147
+ * @param $o 输出端口
148
+ */
149
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
150
+ _transform($i, $o) {
151
+ $i("prompt").receive(async (prompt) => {
152
+ try {
153
+ const completion = await this.generateCompletion(prompt);
154
+ $o("completion").send(completion);
155
+ } catch (error) {
156
+ console.error("Deepseek API \u8C03\u7528\u9519\u8BEF:", error);
157
+ $o("completion").send("API \u8C03\u7528\u9519\u8BEF");
158
+ }
159
+ });
160
+ $i("messages").receive(async (messages) => {
161
+ try {
162
+ const responseMessage = await this.chatCompletion(messages);
163
+ $o("message").send(responseMessage);
164
+ } catch (error) {
165
+ console.error("Deepseek API \u8C03\u7528\u9519\u8BEF:", error);
166
+ $o("message").send({
167
+ role: "assistant",
168
+ content: "API \u8C03\u7528\u9519\u8BEF"
169
+ });
170
+ }
171
+ });
172
+ }
173
+ };
174
+ var deepseek_default = Deepseek;
175
+ export {
176
+ deepseek_default as Deepseek
177
+ };
178
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/model-provider/deepseek/index.ts"],"sourcesContent":["import { Component } from '@astack-tech/core';\nimport OpenAI from 'openai';\n\n/**\n * Deepseek 模型提供者配置\n */\nexport interface DeepseekConfig {\n /**\n * API 密钥\n */\n apiKey: string;\n\n /**\n * 使用的模型名称\n * 默认为 'deepseek-chat'\n */\n model?: string;\n\n /**\n * 自定义 API 基础 URL\n * 默认为 Deepseek 官方 API 地址\n */\n baseURL?: string;\n\n /**\n * 温度参数,控制输出的随机性\n */\n temperature?: number;\n\n /**\n * 最大生成的 token 数\n */\n maxTokens?: number;\n\n /**\n * 采样概率\n */\n topP?: number;\n\n /**\n * 系统提示消息\n */\n systemPrompt?: string;\n\n /**\n * 工具实例数组,直接传递工具实例\n * 每个工具应具有 name、description 和 parameters 属性\n */\n rawTools?: Array<{\n name: string;\n description: string;\n parameters?: Record<string, unknown>;\n }>;\n\n /**\n * API 格式的工具定义数组,与 rawTools 二选一\n * 使用 OpenAI 兼容的工具定义格式\n */\n tools?: unknown[];\n}\n\n/**\n * 消息角色类型\n */\nexport type MessageRole = 'system' | 'user' | 'assistant' | 'tool';\n\n/**\n * 工具调用\n */\nexport interface ToolCall {\n /**\n * 工具调用 ID\n */\n id?: string;\n\n /**\n * 工具名称\n */\n tool_name: string;\n\n /**\n * 工具调用参数\n */\n arguments: Record<string, unknown>;\n}\n\n/**\n * 对话消息类型\n */\nexport interface Message {\n /**\n * 消息角色\n */\n role: MessageRole;\n\n /**\n * 消息内容\n */\n content?: string;\n\n /**\n * 工具调用\n */\n tool_calls?: ToolCall[];\n\n /**\n * 工具调用 ID,用于工具响应消息\n */\n tool_call_id?: string;\n}\n\n/**\n * Deepseek 组件\n *\n * 使用 OpenAI 兼容接口调用 Deepseek 模型\n *\n * 输入:\n * - prompt: 文本提示\n * - messages: 对话消息数组\n *\n * 输出:\n * - completion: 生成的文本完成\n * - message: 生成的响应消息\n */\nclass Deepseek extends Component {\n // OpenAI 客户端实例\n private client: OpenAI;\n\n // 配置选项\n private model: string;\n private temperature: number;\n private maxTokens?: number;\n private topP?: number;\n private systemPrompt?: string;\n private tools?: unknown[];\n\n constructor(config: DeepseekConfig) {\n super({});\n\n // 配置客户端\n this.client = new OpenAI({\n apiKey: config.apiKey,\n baseURL: config.baseURL || 'https://api.deepseek.com/v1',\n });\n\n // 保存基本配置\n this.model = config.model || 'deepseek-chat';\n this.temperature = config.temperature ?? 0.7;\n this.maxTokens = config.maxTokens;\n this.topP = config.topP;\n this.systemPrompt = config.systemPrompt;\n\n // 处理工具配置,优先使用 rawTools\n if (config.rawTools && config.rawTools.length > 0) {\n // 将工具实例转换为 API 格式\n this.tools = config.rawTools.map(tool => ({\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters || {},\n },\n }));\n } else {\n // 使用直接提供的 API 格式工具\n this.tools = config.tools;\n }\n\n // 重命名端口\n Component.Port.I('prompt').attach(this);\n Component.Port.I('messages').attach(this);\n Component.Port.O('completion').attach(this);\n Component.Port.O('message').attach(this);\n }\n\n /**\n * 生成文本完成\n * @param prompt 提示文本\n * @returns 生成的文本\n */\n async generateCompletion(prompt: string): Promise<string> {\n const messages: Array<OpenAI.Chat.ChatCompletionMessageParam> = [];\n\n // 添加系统提示\n if (this.systemPrompt) {\n messages.push({\n role: 'system',\n content: this.systemPrompt,\n });\n }\n\n // 添加用户提示\n messages.push({\n role: 'user',\n content: prompt,\n });\n\n // 创建请求参数\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const requestParams: any = {\n model: this.model,\n messages,\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n top_p: this.topP,\n };\n\n // 如果有工具定义,添加到请求中\n if (this.tools && this.tools.length > 0) {\n requestParams.tools = this.tools;\n }\n\n // 调用 API\n const response = await this.client.chat.completions.create(requestParams);\n\n // 处理工具调用结果\n if (\n response.choices[0].message.tool_calls &&\n response.choices[0].message.tool_calls.length > 0\n ) {\n return JSON.stringify(response.choices[0].message);\n }\n\n return response.choices[0].message.content || '';\n }\n\n /**\n * 处理对话消息\n * @param messages 对话消息数组\n * @param options 可选的调用选项,包含临时工具列表\n * @returns 生成的响应消息\n */\n async chatCompletion(\n messages: Message[],\n options?: { temporaryTools?: unknown[] }\n ): Promise<Message> {\n // 转换消息格式\n const formattedMessages: Array<OpenAI.Chat.ChatCompletionMessageParam> = [];\n\n // 添加系统提示\n if (this.systemPrompt) {\n formattedMessages.push({\n role: 'system',\n content: this.systemPrompt,\n });\n }\n\n // 添加用户提供的消息\n formattedMessages.push(\n ...messages.map(msg => {\n // 基本消息结构\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const formattedMsg: any = {\n role: msg.role,\n content: msg.content,\n };\n\n // 如果有工具调用 ID,添加到消息中\n if (msg.role === 'tool' && msg.tool_call_id) {\n formattedMsg.tool_call_id = msg.tool_call_id;\n }\n\n return formattedMsg;\n })\n );\n\n // 创建请求参数\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const requestParams: any = {\n model: this.model,\n messages: formattedMessages,\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n top_p: this.topP,\n };\n\n // 决定使用哪些工具\n // 如果提供了临时工具,优先使用临时工具\n const toolsToUse = options?.temporaryTools || this.tools;\n\n // 如果有工具定义,添加到请求中\n if (toolsToUse && toolsToUse.length > 0) {\n // 检查工具格式并转换,确保符合 Deepseek API 要求\n const formattedTools = toolsToUse.map(tool => {\n // 使用类型断言来处理 unknown 类型\n type ToolType = {\n type?: string;\n name?: string;\n description?: string;\n parameters?: Record<string, unknown>;\n };\n\n const typedTool = tool as ToolType;\n\n // 如果工具已经是 API 格式,直接返回\n if (typedTool.type === 'function') {\n return tool;\n }\n\n // 如果是简单工具实例,转换为 API 格式\n return {\n type: 'function',\n function: {\n name: typedTool.name,\n description: typedTool.description,\n parameters: typedTool.parameters || {},\n },\n };\n });\n\n requestParams.tools = formattedTools;\n }\n\n // 调用 API\n const response = await this.client.chat.completions.create(requestParams);\n\n // 解析响应\n const responseMessage = response.choices[0].message;\n\n // 转换为内部消息格式\n const result: Message = {\n role: 'assistant',\n content: responseMessage.content || '',\n };\n\n // 如果有工具调用,添加到结果中\n if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {\n result.tool_calls = responseMessage.tool_calls.map(toolCall => ({\n id: toolCall.id,\n tool_name: toolCall.function.name,\n arguments: JSON.parse(toolCall.function.arguments || '{}'),\n }));\n }\n\n return result;\n }\n\n /**\n * 在独立模式下运行组件\n * @param input 输入参数,可以是提示文本或对话消息数组\n * @returns 生成的文本或响应消息\n */\n async run(input: string | Message[]): Promise<string | Message> {\n if (typeof input === 'string') {\n return this.generateCompletion(input);\n } else {\n return this.chatCompletion(input);\n }\n }\n\n /**\n * 在流水线中运行组件\n * @param $i 输入端口\n * @param $o 输出端口\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _transform($i: any, $o: any) {\n // 处理文本提示输入\n $i('prompt').receive(async (prompt: string) => {\n try {\n const completion = await this.generateCompletion(prompt);\n $o('completion').send(completion);\n } catch (error) {\n console.error('Deepseek API 调用错误:', error);\n $o('completion').send('API 调用错误');\n }\n });\n\n // 处理对话消息输入\n $i('messages').receive(async (messages: Message[]) => {\n try {\n const responseMessage = await this.chatCompletion(messages);\n $o('message').send(responseMessage);\n } catch (error) {\n console.error('Deepseek API 调用错误:', error);\n $o('message').send({\n role: 'assistant',\n content: 'API 调用错误',\n });\n }\n });\n }\n}\n\n// 默认导出组件\nexport default Deepseek;\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,OAAO,YAAY;AA2HnB,IAAM,WAAN,cAAuB,UAAU;AAAA,EAY/B,YAAY,QAAwB;AAClC,UAAM,CAAC,CAAC;AAGR,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,QAAQ,OAAO;AAAA,MACf,SAAS,OAAO,WAAW;AAAA,IAC7B,CAAC;AAGD,SAAK,QAAQ,OAAO,SAAS;AAC7B,SAAK,cAAc,OAAO,eAAe;AACzC,SAAK,YAAY,OAAO;AACxB,SAAK,OAAO,OAAO;AACnB,SAAK,eAAe,OAAO;AAG3B,QAAI,OAAO,YAAY,OAAO,SAAS,SAAS,GAAG;AAEjD,WAAK,QAAQ,OAAO,SAAS,IAAI,WAAS;AAAA,QACxC,MAAM;AAAA,QACN,UAAU;AAAA,UACR,MAAM,KAAK;AAAA,UACX,aAAa,KAAK;AAAA,UAClB,YAAY,KAAK,cAAc,CAAC;AAAA,QAClC;AAAA,MACF,EAAE;AAAA,IACJ,OAAO;AAEL,WAAK,QAAQ,OAAO;AAAA,IACtB;AAGA,cAAU,KAAK,EAAE,QAAQ,EAAE,OAAO,IAAI;AACtC,cAAU,KAAK,EAAE,UAAU,EA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O,KAAK,mBAAmB,KAAK;AAAA,IACtC,OAAO;AACL,aAAO,KAAK,eAAe,KAAK;AAAA,IAClC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,WAAW,IAAS,IAAS;AAE3B,OAAG,QAAQ,EAAE,QAAQ,OAAO,WAAmB;AAC7C,UAAI;AACF,cAAM,aAAa,MAAM,KAAK,mBAAmB,MAAM;AACvD,WAAG,YAAY,EAAE,KAAK,UAAU;AAAA,MAClC,SAAS,OAAO;AACd,gBAAQ,MAAM,0CAAsB,KAAK;AACzC,WAAG,YAAY,EAAE,KAAK,8BAAU;AAAA,MAClC;AAAA,IACF,CAAC;AAGD,OAAG,UAAU,EAAE,QAAQ,OAAO,aAAwB;AACpD,UAAI;AACF,cAAM,kBAAkB,MAAM,KAAK,eAAe,QAAQ;AAC1D,WAAG,SAAS,EAAE,KAAK,eAAe;AAAA,MACpC,SAAS,OAAO;AACd,gBAAQ,MAAM,0CAAsB,KAAK;AACzC,WAAG,SAAS,EAAE,KAAK;AAAA,UACjB,MAAM;AAAA,UACN,SAAS;AAAA,QACX,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAGA,IAAO,mBAAQ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@astack-tech/integrations",
3
+ "version": "0.1.1-beta.0",
4
+ "description": "Integrations for the Astack AI Framework.",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "types": {
12
+ "import": "./dist/index.d.ts",
13
+ "require": "./dist/index.d.cts"
14
+ },
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.cjs"
17
+ },
18
+ "./model-provider": {
19
+ "types": {
20
+ "import": "./dist/model-provider/index.d.ts",
21
+ "require": "./dist/model-provider/index.d.cts"
22
+ },
23
+ "import": "./dist/model-provider/index.js",
24
+ "require": "./dist/model-provider/index.cjs"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "src",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "keywords": [
34
+ "ai-framework",
35
+ "ai-agent",
36
+ "ai"
37
+ ],
38
+ "author": "xiaoa",
39
+ "license": "MIT",
40
+ "devDependencies": {
41
+ "@types/node": "^20.11.5",
42
+ "eslint": "^8.56.0",
43
+ "rimraf": "^5.0.5",
44
+ "tsup": "^8.4.0",
45
+ "typescript": "^5.8.3",
46
+ "vitest": "^1.2.1"
47
+ },
48
+ "engines": {
49
+ "node": ">=18.0.0"
50
+ },
51
+ "dependencies": {
52
+ "openai": "^4.98.0",
53
+ "@astack-tech/core": "0.1.1-beta.0"
54
+ },
55
+ "scripts": {
56
+ "dev": "tsup --watch",
57
+ "build": "tsup",
58
+ "lint": "eslint src --ext .ts,.tsx",
59
+ "check-types": "tsc --noEmit",
60
+ "test": "vitest run",
61
+ "clean": "rimraf dist"
62
+ }
63
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Astack 集成包
3
+ *
4
+ * 提供与各种外部服务和平台的集成组件
5
+ */
6
+
7
+ // 导出模型提供者组件
8
+ export * as ModelProvider from './model-provider';
@@ -0,0 +1,386 @@
1
+ import { Component } from '@astack-tech/core';
2
+ import OpenAI from 'openai';
3
+
4
+ /**
5
+ * Deepseek 模型提供者配置
6
+ */
7
+ export interface DeepseekConfig {
8
+ /**
9
+ * API 密钥
10
+ */
11
+ apiKey: string;
12
+
13
+ /**
14
+ * 使用的模型名称
15
+ * 默认为 'deepseek-chat'
16
+ */
17
+ model?: string;
18
+
19
+ /**
20
+ * 自定义 API 基础 URL
21
+ * 默认为 Deepseek 官方 API 地址
22
+ */
23
+ baseURL?: string;
24
+
25
+ /**
26
+ * 温度参数,控制输出的随机性
27
+ */
28
+ temperature?: number;
29
+
30
+ /**
31
+ * 最大生成的 token 数
32
+ */
33
+ maxTokens?: number;
34
+
35
+ /**
36
+ * 采样概率
37
+ */
38
+ topP?: number;
39
+
40
+ /**
41
+ * 系统提示消息
42
+ */
43
+ systemPrompt?: string;
44
+
45
+ /**
46
+ * 工具实例数组,直接传递工具实例
47
+ * 每个工具应具有 name、description 和 parameters 属性
48
+ */
49
+ rawTools?: Array<{
50
+ name: string;
51
+ description: string;
52
+ parameters?: Record<string, unknown>;
53
+ }>;
54
+
55
+ /**
56
+ * API 格式的工具定义数组,与 rawTools 二选一
57
+ * 使用 OpenAI 兼容的工具定义格式
58
+ */
59
+ tools?: unknown[];
60
+ }
61
+
62
+ /**
63
+ * 消息角色类型
64
+ */
65
+ export type MessageRole = 'system' | 'user' | 'assistant' | 'tool';
66
+
67
+ /**
68
+ * 工具调用
69
+ */
70
+ export interface ToolCall {
71
+ /**
72
+ * 工具调用 ID
73
+ */
74
+ id?: string;
75
+
76
+ /**
77
+ * 工具名称
78
+ */
79
+ tool_name: string;
80
+
81
+ /**
82
+ * 工具调用参数
83
+ */
84
+ arguments: Record<string, unknown>;
85
+ }
86
+
87
+ /**
88
+ * 对话消息类型
89
+ */
90
+ export interface Message {
91
+ /**
92
+ * 消息角色
93
+ */
94
+ role: MessageRole;
95
+
96
+ /**
97
+ * 消息内容
98
+ */
99
+ content?: string;
100
+
101
+ /**
102
+ * 工具调用
103
+ */
104
+ tool_calls?: ToolCall[];
105
+
106
+ /**
107
+ * 工具调用 ID,用于工具响应消息
108
+ */
109
+ tool_call_id?: string;
110
+ }
111
+
112
+ /**
113
+ * Deepseek 组件
114
+ *
115
+ * 使用 OpenAI 兼容接口调用 Deepseek 模型
116
+ *
117
+ * 输入:
118
+ * - prompt: 文本提示
119
+ * - messages: 对话消息数组
120
+ *
121
+ * 输出:
122
+ * - completion: 生成的文本完成
123
+ * - message: 生成的响应消息
124
+ */
125
+ class Deepseek extends Component {
126
+ // OpenAI 客户端实例
127
+ private client: OpenAI;
128
+
129
+ // 配置选项
130
+ private model: string;
131
+ private temperature: number;
132
+ private maxTokens?: number;
133
+ private topP?: number;
134
+ private systemPrompt?: string;
135
+ private tools?: unknown[];
136
+
137
+ constructor(config: DeepseekConfig) {
138
+ super({});
139
+
140
+ // 配置客户端
141
+ this.client = new OpenAI({
142
+ apiKey: config.apiKey,
143
+ baseURL: config.baseURL || 'https://api.deepseek.com/v1',
144
+ });
145
+
146
+ // 保存基本配置
147
+ this.model = config.model || 'deepseek-chat';
148
+ this.temperature = config.temperature ?? 0.7;
149
+ this.maxTokens = config.maxTokens;
150
+ this.topP = config.topP;
151
+ this.systemPrompt = config.systemPrompt;
152
+
153
+ // 处理工具配置,优先使用 rawTools
154
+ if (config.rawTools && config.rawTools.length > 0) {
155
+ // 将工具实例转换为 API 格式
156
+ this.tools = config.rawTools.map(tool => ({
157
+ type: 'function',
158
+ function: {
159
+ name: tool.name,
160
+ description: tool.description,
161
+ parameters: tool.parameters || {},
162
+ },
163
+ }));
164
+ } else {
165
+ // 使用直接提供的 API 格式工具
166
+ this.tools = config.tools;
167
+ }
168
+
169
+ // 重命名端口
170
+ Component.Port.I('prompt').attach(this);
171
+ Component.Port.I('messages').attach(this);
172
+ Component.Port.O('completion').attach(this);
173
+ Component.Port.O('message').attach(this);
174
+ }
175
+
176
+ /**
177
+ * 生成文本完成
178
+ * @param prompt 提示文本
179
+ * @returns 生成的文本
180
+ */
181
+ async generateCompletion(prompt: string): Promise<string> {
182
+ const messages: Array<OpenAI.Chat.ChatCompletionMessageParam> = [];
183
+
184
+ // 添加系统提示
185
+ if (this.systemPrompt) {
186
+ messages.push({
187
+ role: 'system',
188
+ content: this.systemPrompt,
189
+ });
190
+ }
191
+
192
+ // 添加用户提示
193
+ messages.push({
194
+ role: 'user',
195
+ content: prompt,
196
+ });
197
+
198
+ // 创建请求参数
199
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
200
+ const requestParams: any = {
201
+ model: this.model,
202
+ messages,
203
+ temperature: this.temperature,
204
+ max_tokens: this.maxTokens,
205
+ top_p: this.topP,
206
+ };
207
+
208
+ // 如果有工具定义,添加到请求中
209
+ if (this.tools && this.tools.length > 0) {
210
+ requestParams.tools = this.tools;
211
+ }
212
+
213
+ // 调用 API
214
+ const response = await this.client.chat.completions.create(requestParams);
215
+
216
+ // 处理工具调用结果
217
+ if (
218
+ response.choices[0].message.tool_calls &&
219
+ response.choices[0].message.tool_calls.length > 0
220
+ ) {
221
+ return JSON.stringify(response.choices[0].message);
222
+ }
223
+
224
+ return response.choices[0].message.content || '';
225
+ }
226
+
227
+ /**
228
+ * 处理对话消息
229
+ * @param messages 对话消息数组
230
+ * @param options 可选的调用选项,包含临时工具列表
231
+ * @returns 生成的响应消息
232
+ */
233
+ async chatCompletion(
234
+ messages: Message[],
235
+ options?: { temporaryTools?: unknown[] }
236
+ ): Promise<Message> {
237
+ // 转换消息格式
238
+ const formattedMessages: Array<OpenAI.Chat.ChatCompletionMessageParam> = [];
239
+
240
+ // 添加系统提示
241
+ if (this.systemPrompt) {
242
+ formattedMessages.push({
243
+ role: 'system',
244
+ content: this.systemPrompt,
245
+ });
246
+ }
247
+
248
+ // 添加用户提供的消息
249
+ formattedMessages.push(
250
+ ...messages.map(msg => {
251
+ // 基本消息结构
252
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
253
+ const formattedMsg: any = {
254
+ role: msg.role,
255
+ content: msg.content,
256
+ };
257
+
258
+ // 如果有工具调用 ID,添加到消息中
259
+ if (msg.role === 'tool' && msg.tool_call_id) {
260
+ formattedMsg.tool_call_id = msg.tool_call_id;
261
+ }
262
+
263
+ return formattedMsg;
264
+ })
265
+ );
266
+
267
+ // 创建请求参数
268
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
269
+ const requestParams: any = {
270
+ model: this.model,
271
+ messages: formattedMessages,
272
+ temperature: this.temperature,
273
+ max_tokens: this.maxTokens,
274
+ top_p: this.topP,
275
+ };
276
+
277
+ // 决定使用哪些工具
278
+ // 如果提供了临时工具,优先使用临时工具
279
+ const toolsToUse = options?.temporaryTools || this.tools;
280
+
281
+ // 如果有工具定义,添加到请求中
282
+ if (toolsToUse && toolsToUse.length > 0) {
283
+ // 检查工具格式并转换,确保符合 Deepseek API 要求
284
+ const formattedTools = toolsToUse.map(tool => {
285
+ // 使用类型断言来处理 unknown 类型
286
+ type ToolType = {
287
+ type?: string;
288
+ name?: string;
289
+ description?: string;
290
+ parameters?: Record<string, unknown>;
291
+ };
292
+
293
+ const typedTool = tool as ToolType;
294
+
295
+ // 如果工具已经是 API 格式,直接返回
296
+ if (typedTool.type === 'function') {
297
+ return tool;
298
+ }
299
+
300
+ // 如果是简单工具实例,转换为 API 格式
301
+ return {
302
+ type: 'function',
303
+ function: {
304
+ name: typedTool.name,
305
+ description: typedTool.description,
306
+ parameters: typedTool.parameters || {},
307
+ },
308
+ };
309
+ });
310
+
311
+ requestParams.tools = formattedTools;
312
+ }
313
+
314
+ // 调用 API
315
+ const response = await this.client.chat.completions.create(requestParams);
316
+
317
+ // 解析响应
318
+ const responseMessage = response.choices[0].message;
319
+
320
+ // 转换为内部消息格式
321
+ const result: Message = {
322
+ role: 'assistant',
323
+ content: responseMessage.content || '',
324
+ };
325
+
326
+ // 如果有工具调用,添加到结果中
327
+ if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {
328
+ result.tool_calls = responseMessage.tool_calls.map(toolCall => ({
329
+ id: toolCall.id,
330
+ tool_name: toolCall.function.name,
331
+ arguments: JSON.parse(toolCall.function.arguments || '{}'),
332
+ }));
333
+ }
334
+
335
+ return result;
336
+ }
337
+
338
+ /**
339
+ * 在独立模式下运行组件
340
+ * @param input 输入参数,可以是提示文本或对话消息数组
341
+ * @returns 生成的文本或响应消息
342
+ */
343
+ async run(input: string | Message[]): Promise<string | Message> {
344
+ if (typeof input === 'string') {
345
+ return this.generateCompletion(input);
346
+ } else {
347
+ return this.chatCompletion(input);
348
+ }
349
+ }
350
+
351
+ /**
352
+ * 在流水线中运行组件
353
+ * @param $i 输入端口
354
+ * @param $o 输出端口
355
+ */
356
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
357
+ _transform($i: any, $o: any) {
358
+ // 处理文本提示输入
359
+ $i('prompt').receive(async (prompt: string) => {
360
+ try {
361
+ const completion = await this.generateCompletion(prompt);
362
+ $o('completion').send(completion);
363
+ } catch (error) {
364
+ console.error('Deepseek API 调用错误:', error);
365
+ $o('completion').send('API 调用错误');
366
+ }
367
+ });
368
+
369
+ // 处理对话消息输入
370
+ $i('messages').receive(async (messages: Message[]) => {
371
+ try {
372
+ const responseMessage = await this.chatCompletion(messages);
373
+ $o('message').send(responseMessage);
374
+ } catch (error) {
375
+ console.error('Deepseek API 调用错误:', error);
376
+ $o('message').send({
377
+ role: 'assistant',
378
+ content: 'API 调用错误',
379
+ });
380
+ }
381
+ });
382
+ }
383
+ }
384
+
385
+ // 默认导出组件
386
+ export default Deepseek;
@@ -0,0 +1,7 @@
1
+ export {
2
+ default as Deepseek,
3
+ type Message as DeepseekMessage,
4
+ type ToolCall as DeepseekToolCall,
5
+ type DeepseekConfig,
6
+ type MessageRole as DeepseekMessageRole,
7
+ } from './deepseek';