|
| 1 | +import { NodeExecution, NodeType } from "@dafthunk/types"; |
| 2 | + |
| 3 | +import { ExecutableNode } from "../types"; |
| 4 | +import { NodeContext } from "../types"; |
| 5 | + |
| 6 | +/** |
| 7 | + * GPT-OSS-20B node implementation following Cloudflare Workers AI API |
| 8 | + * OpenAI's open-weight models designed for powerful reasoning, agentic tasks, and versatile developer use cases |
| 9 | + * GPT-OSS-20B is for lower latency, and local or specialized use-cases |
| 10 | + */ |
| 11 | +export class GptOss20BNode extends ExecutableNode { |
| 12 | + public static readonly nodeType: NodeType = { |
| 13 | + id: "gpt-oss-20b", |
| 14 | + name: "GPT-OSS-20B", |
| 15 | + type: "gpt-oss-20b", |
| 16 | + description: "OpenAI's open-weight model for lower latency and specialized use cases", |
| 17 | + tags: ["Text", "AI"], |
| 18 | + icon: "sparkles", |
| 19 | + computeCost: 20, |
| 20 | + asTool: true, |
| 21 | + inputs: [ |
| 22 | + { |
| 23 | + name: "instructions", |
| 24 | + type: "string", |
| 25 | + description: "System instructions for the model behavior", |
| 26 | + required: false, |
| 27 | + value: "You are a helpful assistant.", |
| 28 | + }, |
| 29 | + { |
| 30 | + name: "input", |
| 31 | + type: "string", |
| 32 | + description: "The input text or question for the model", |
| 33 | + required: true, |
| 34 | + }, |
| 35 | + ], |
| 36 | + outputs: [ |
| 37 | + { |
| 38 | + name: "response", |
| 39 | + type: "string", |
| 40 | + description: "Generated text response from GPT-OSS-20B", |
| 41 | + }, |
| 42 | + ], |
| 43 | + }; |
| 44 | + |
| 45 | + async execute(context: NodeContext): Promise<NodeExecution> { |
| 46 | + try { |
| 47 | + const { instructions, input } = context.inputs; |
| 48 | + |
| 49 | + if (!context.env?.AI) { |
| 50 | + return this.createErrorResult("AI service is not available"); |
| 51 | + } |
| 52 | + |
| 53 | + if (!input) { |
| 54 | + return this.createErrorResult("Input is required"); |
| 55 | + } |
| 56 | + |
| 57 | + const result = await context.env.AI.run( |
| 58 | + "@cf/openai/gpt-oss-20b" as any, |
| 59 | + { |
| 60 | + instructions: instructions || "You are a helpful assistant.", |
| 61 | + input, |
| 62 | + }, |
| 63 | + context.env.AI_OPTIONS |
| 64 | + ); |
| 65 | + |
| 66 | + // Extract the response text from the output structure |
| 67 | + // The response is in output[1] (the message with type 'message' and role 'assistant') |
| 68 | + const messageOutput = result.output?.find((output: any) => output.type === 'message' && output.role === 'assistant'); |
| 69 | + const responseText = messageOutput?.content?.[0]?.text || ''; |
| 70 | + |
| 71 | + return this.createSuccessResult({ |
| 72 | + response: responseText, |
| 73 | + }); |
| 74 | + } catch (error) { |
| 75 | + console.error(error); |
| 76 | + return this.createErrorResult( |
| 77 | + error instanceof Error ? error.message : "Unknown error" |
| 78 | + ); |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments