|
| 1 | +import { StreamingAgent } from '@astack-tech/components'; |
| 2 | +import { createTool } from '@astack-tech/tools'; |
| 3 | +import { Deepseek } from '@astack-tech/integrations/model-provider'; |
| 4 | +import type { ModelProvider } from '@astack-tech/components'; |
| 5 | + |
| 6 | +// 计算器工具(与原math-agent完全一致) |
| 7 | +const calculatorTool = createTool( |
| 8 | + 'calculator', |
| 9 | + '执行基本的数学计算', |
| 10 | + async (args: Record<string, unknown>) => { |
| 11 | + const { expression } = args as { expression: string }; |
| 12 | + try { |
| 13 | + // 安全的数学计算,只允许基本数学运算 |
| 14 | + const sanitized = expression.replace(/[^0-9+\-*/(). ]/g, ''); |
| 15 | + const result = Function(`"use strict"; return (${sanitized})`)(); |
| 16 | + return `计算结果: ${expression} = ${result}`; |
| 17 | + } catch (error) { |
| 18 | + return `计算错误: ${error instanceof Error ? error.message : String(error)}`; |
| 19 | + } |
| 20 | + }, |
| 21 | + { |
| 22 | + type: 'object', |
| 23 | + properties: { |
| 24 | + expression: { |
| 25 | + type: 'string', |
| 26 | + description: '数学表达式,如 "2 + 3" 或 "10 * 5"', |
| 27 | + }, |
| 28 | + }, |
| 29 | + required: ['expression'], |
| 30 | + } |
| 31 | +); |
| 32 | + |
| 33 | +// 创建流式数学助手 Agent |
| 34 | +export function createStreamingMathAgent(): StreamingAgent { |
| 35 | + const apiKey = process.env.DEEPSEEK_API_KEY || ''; |
| 36 | + if (!apiKey) { |
| 37 | + throw new Error('DEEPSEEK_API_KEY environment variable is required'); |
| 38 | + } |
| 39 | + |
| 40 | + const model = new Deepseek({ |
| 41 | + apiKey, |
| 42 | + model: 'deepseek-chat', |
| 43 | + temperature: 0.3, |
| 44 | + }); |
| 45 | + |
| 46 | + return new StreamingAgent({ |
| 47 | + model: model as ModelProvider, |
| 48 | + tools: [calculatorTool], |
| 49 | + systemPrompt: `你是一个专业的数学助手,专门帮助用户进行数学计算和解答数学问题。 |
| 50 | +
|
| 51 | +你的能力: |
| 52 | +- 执行基本的数学运算(加减乘除) |
| 53 | +- 计算复杂的数学表达式 |
| 54 | +- 解答数学问题和提供解题思路 |
| 55 | +
|
| 56 | +当用户提到需要计算时,请使用 calculator 工具来准确计算结果。 |
| 57 | +计算完成后,请给出清晰的解答和必要的说明。 |
| 58 | +
|
| 59 | +可用工具: |
| 60 | +1. calculator - 执行基本的数学计算 |
| 61 | + 参数: |
| 62 | + - expression: 数学表达式,如 "2 + 3" 或 "10 * 5"`, |
| 63 | + verbose: true, |
| 64 | + maxIterations: 3, |
| 65 | + }); |
| 66 | +} |
0 commit comments