| 142 | * 生成 TypeScript 代码 |
| 143 | */ |
| 144 | export function generateTypeScriptCode(nodes: Node[], edges: Edge[]): string { |
| 145 | let code = `/** |
| 146 | * Generated Workflow Code |
| 147 | * |
| 148 | * This code was automatically generated from a workflow. |
| 149 | */ |
| 150 | |
| 151 | type Context = Record<string, any>; |
| 152 | |
| 153 | `; |
| 154 | |
| 155 | // 为每个节点生成函数 |
| 156 | nodes.forEach((node) => { |
| 157 | switch (node.type) { |
| 158 | case 'start': |
| 159 | code += `async function node_${node.id}_start(context: Context): Promise<any> { |
| 160 | console.log("Starting workflow..."); |
| 161 | return context.initial_input || {}; |
| 162 | } |
| 163 | |
| 164 | `; |
| 165 | break; |
| 166 | |
| 167 | case 'httpRequest': |
| 168 | code += `async function node_${node.id}_httpRequest(context: Context): Promise<any> { |
| 169 | const url = "${node.data.url || 'https://api.example.com'}"; |
| 170 | const method = "${node.data.method || 'GET'}"; |
| 171 | |
| 172 | const response = await fetch(url, { method }); |
| 173 | return await response.json(); |
| 174 | } |
| 175 | |
| 176 | `; |
| 177 | break; |
| 178 | |
| 179 | case 'textModel': |
| 180 | code += `async function node_${node.id}_textModel(context: Context): Promise<any> { |
| 181 | const response = await fetch("https://api.openai.com/v1/chat/completions", { |
| 182 | method: "POST", |
| 183 | headers: { |
| 184 | "Content-Type": "application/json", |
| 185 | "Authorization": "Bearer YOUR_API_KEY" |
| 186 | }, |
| 187 | body: JSON.stringify({ |
| 188 | model: "${node.data.model || 'gpt-4'}", |
| 189 | messages: [ |
| 190 | { role: "user", content: context.prompt || "" } |
| 191 | ], |
| 192 | temperature: ${node.data.temperature || 0.7}, |
| 193 | max_tokens: ${node.data.maxTokens || 2000} |
| 194 | }) |
| 195 | }); |
| 196 | |
| 197 | const data = await response.json(); |
| 198 | return data.choices[0].message.content; |
| 199 | } |
| 200 | |
| 201 | `; |