-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathopenai-client.ts
More file actions
950 lines (836 loc) · 28.9 KB
/
openai-client.ts
File metadata and controls
950 lines (836 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
import OpenAI from "@openai/openai";
import {
type AiModel,
type ExecutionContext,
logger,
type ModelCapability,
} from "@runtimed/agent-core";
import { AI_TOOL_CALL_MIME_TYPE, AI_TOOL_RESULT_MIME_TYPE } from "@runt/schema";
import { getAllTools } from "./tool-registry.ts";
import type { NotebookTool } from "./tool-registry.ts";
// Define message types inline to avoid import issues
type ChatMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
export interface OpenAIConfig {
apiKey?: string;
baseURL?: string;
organization?: string;
defaultHeaders?: Record<string, string>;
provider?: string;
}
interface ToolCall {
id: string;
name: string;
arguments: Record<string, unknown>;
}
interface ToolCallOutput {
tool_call_id: string;
tool_name: string;
arguments: Record<string, unknown>;
status: "success" | "error";
timestamp: string;
result?: string;
}
interface OutputData {
type: "display_data" | "execute_result" | "error";
data: Record<string, unknown>;
metadata?: Record<string, unknown>;
}
interface AgenticOptions {
maxIterations?: number;
onIteration?: (
iteration: number,
messages: ChatMessage[],
) => Promise<boolean>;
interruptSignal?: AbortSignal;
}
interface AnodeCellMetadata {
role?: "assistant" | "user" | "function_call" | "tool";
ai_provider?: string;
ai_model?: string;
iteration?: number;
tool_call?: boolean;
tool_name?: string;
tool_args?: Record<string, unknown>;
tool_error?: boolean;
tool_call_id?: string;
}
export class RuntOpenAIClient {
private client: OpenAI | null = null;
private isConfigured = false;
private notebookTools: NotebookTool[];
provider: string = "openai";
protected envPrefix: string | null = null;
protected defaultConfig: OpenAIConfig = {};
constructor(config?: OpenAIConfig, notebookTools: NotebookTool[] = []) {
if (config) {
this.configure(config);
}
this.notebookTools = [...notebookTools];
}
configure(config?: OpenAIConfig) {
this.provider = config?.provider ?? this.provider;
const envPrefix = this.envPrefix?.toUpperCase() ||
this.provider.toUpperCase();
const apiKey = config?.apiKey || Deno.env.get(`${envPrefix}_API_KEY`);
const baseURL = config?.baseURL || Deno.env.get(`${envPrefix}_BASE_URL`);
if (!apiKey) {
// Don't log warning at startup - only when actually trying to use OpenAI
this.isConfigured = false;
return;
}
try {
this.client = new OpenAI({
apiKey,
baseURL: baseURL,
organization: config?.organization,
defaultHeaders: config?.defaultHeaders,
...this.defaultConfig,
});
this.isConfigured = true;
logger.info(`${this.provider} client configured successfully`);
} catch (error) {
logger.error(`Failed to configure ${this.provider} client`, error);
this.isConfigured = false;
}
}
getConfigMessage(): string {
const configMessage = `# AI Configuration Required
AI has not been configured for this runtime yet. To use AI Cells, you need to set an \`OPENAI_API_KEY\` before starting your runtime agent.
## Setup Instructions
Set your API key as an environment variable:
\`\`\`bash
OPENAI_API_KEY=your-api-key-here deno run --allow-all your-script.ts
\`\`\`
Or add it to your \`.env\` file:
\`\`\`
OPENAI_API_KEY=your-api-key-here
\`\`\`
## Get an API Key
1. Visit [OpenAI's website](https://platform.openai.com/api-keys)
2. Create an account or sign in
3. Generate a new API key
4. Copy the key and use it in your environment
Once configured, your AI cells will work with real OpenAI models!`;
return configMessage;
}
isReady(): boolean {
// Try to configure if not already configured and not already failed
if (!this.isConfigured && this.client === null) {
this.configure();
}
return this.isConfigured && this.client !== null;
}
/**
* Set notebookTools for use in the agentic loop
*/
setNotebookTools(notebookTools: NotebookTool[]) {
this.notebookTools = [...notebookTools];
}
/**
* Get hardcoded OpenAI model capabilities
* (OpenAI doesn't expose capabilities via API)
*/
private getModelCapabilities(modelName: string): ModelCapability[] {
const capabilities: ModelCapability[] = ["completion"];
// All current OpenAI models support tools
capabilities.push("tools");
// Vision models
if (
modelName.includes("gpt-4o") ||
modelName.includes("gpt-4.1") ||
modelName.includes("o3") ||
modelName.includes("o4")
) {
capabilities.push("vision");
}
// Reasoning models
if (
modelName.includes("o1") ||
modelName.includes("o3") ||
modelName.includes("o4")
) {
capabilities.push("thinking");
}
return capabilities;
}
/**
* OpenAI Reasoning Models Compatibility Guide
*
* Reasoning models (o1, o3, o4 series) have specific parameter restrictions:
*
* 1. **Token Parameters**: Use max_completion_tokens instead of max_tokens
* 2. **Temperature**: Fixed at 1 (no custom values supported)
* 3. **System Messages**:
* - o1 family: Not supported (convert to user messages)
* - o3/o4 family: Converted to developer messages by API
* 4. **Other Fixed Parameters**: top_p=1, presence_penalty=0, frequency_penalty=0
* 5. **Reasoning Effort**: Some models support low/medium/high effort levels
*
* Models affected: o1-preview, o1-mini, o1-pro, o3, o3-mini, o3-pro, o4-mini, etc.
*/
/**
* Check if model is a reasoning model (starts with 'o')
*/
private isReasoningModel(modelName: string): boolean {
return modelName.startsWith("o1") ||
modelName.startsWith("o3") ||
modelName.startsWith("o4");
}
/**
* Check if model uses max_completion_tokens instead of max_tokens
*/
private usesMaxCompletionTokens(modelName: string): boolean {
return modelName.startsWith("o1") ||
modelName.startsWith("o3") ||
modelName.startsWith("o4");
}
/**
* Check if model supports system messages
*/
private supportsSystemMessages(modelName: string): boolean {
// o1 family models don't support system messages at all
// o3/o4 models convert system messages to developer messages (handled by API)
return !modelName.startsWith("o1");
}
/**
* Filter messages based on model capabilities
*/
private filterMessagesForModel(
messages: ChatMessage[],
modelName: string,
): ChatMessage[] {
if (this.supportsSystemMessages(modelName)) {
return messages;
}
// For models that don't support system messages, convert system message to user message
return messages.map((msg) => {
if (msg.role === "system") {
return {
role: "user" as const,
content: `System instructions: ${msg.content}`,
};
}
return msg;
});
}
/**
* Check if model supports custom temperature values
*/
private supportsCustomTemperature(modelName: string): boolean {
// All reasoning models (o1, o3, o4) have temperature fixed at 1
return !(modelName.startsWith("o1") ||
modelName.startsWith("o3") ||
modelName.startsWith("o4"));
}
/**
* Get available OpenAI models (hardcoded for now)
*/
private getModels(): Array<{
name: string;
displayName: string;
contextLength: number;
deprecated?: boolean;
}> {
return [
// Latest flagship models
{
name: "o4-mini",
displayName: "o4-mini",
contextLength: 200000,
},
{
name: "o3",
displayName: "o3",
contextLength: 200000,
},
{
name: "gpt-4.1",
displayName: "GPT-4.1",
contextLength: 1047552,
},
// Current stable models
{
name: "gpt-4o",
displayName: "GPT-4o",
contextLength: 128000,
},
{
name: "gpt-4o-mini",
displayName: "GPT-4o Mini",
contextLength: 128000,
},
{
name: "o1",
displayName: "o1",
contextLength: 128000,
},
{
name: "o1-mini",
displayName: "o1 Mini",
contextLength: 128000,
},
];
}
/**
* Discover available AI models with their capabilities
*/
discoverAiModels(): Promise<AiModel[]> {
if (!this.isReady()) {
logger.warn(
`${this.provider} client not ready, returning empty models list`,
);
return Promise.resolve([]);
}
try {
const models = this.getModels();
const aiModels: AiModel[] = [];
for (const model of models) {
const capabilities = this.getModelCapabilities(model.name);
aiModels.push({
name: model.name,
displayName: model.displayName,
provider: this.provider,
capabilities,
});
}
return Promise.resolve(aiModels);
} catch (error) {
logger.error(`Failed to discover ${this.provider} models`, error);
return Promise.resolve([]);
}
}
async generateAgenticResponse(
messages: ChatMessage[],
context: ExecutionContext,
options: {
model?: string;
provider?: string;
maxTokens?: number;
temperature?: number;
enableTools?: boolean;
onToolCall?: (toolCall: ToolCall) => Promise<string>;
} & AgenticOptions = {},
): Promise<void> {
const {
model = "gpt-4o-mini",
maxTokens = 2000,
temperature = 0.7,
enableTools = true,
onToolCall,
maxIterations = 10,
onIteration,
interruptSignal,
} = options;
if (!this.isReady()) {
const configOutputs = this.createConfigHelpOutput();
for (const output of configOutputs) {
if (output.type === "display_data") {
context.display(output.data, output.metadata || {});
}
}
return;
}
const conversationMessages: ChatMessage[] = [...messages];
let iteration = 0;
try {
while (iteration < maxIterations) {
// Check for interruption
if (interruptSignal?.aborted) {
logger.info("Agentic conversation interrupted");
break;
}
// Call iteration callback if provided
if (onIteration) {
const shouldContinue = await onIteration(
iteration,
conversationMessages,
);
if (!shouldContinue) {
logger.info(
"Agentic conversation stopped by iteration callback",
);
break;
}
}
logger.info(`Agentic iteration ${iteration + 1}/${maxIterations}`);
// Prepare tools if enabled
let all_tools: NotebookTool[] = [];
if (enableTools) {
// Get all available tools (notebook + MCP)
all_tools = await getAllTools();
// Add any notebook-specific tools from constructor
if (this.notebookTools.length > 0) {
all_tools = [...this.notebookTools, ...all_tools];
}
}
const tools = enableTools && all_tools.length > 0
? all_tools.map((tool) => ({
type: "function" as const,
function: {
name: tool.name,
description: tool.description,
parameters: tool.parameters,
},
}))
: undefined;
// Filter messages based on model capabilities
const filteredMessages = this.filterMessagesForModel(
conversationMessages,
model,
);
// Prepare request parameters with model-specific compatibility
const baseParams = {
model,
messages: filteredMessages,
...(this.supportsCustomTemperature(model) ? { temperature } : {}),
stream: true,
user: "me",
...(tools ? { tools } : {}),
...(enableTools && tools ? { tool_choice: "auto" as const } : {}),
};
// Use appropriate token limit parameter based on model
const requestParams = this.usesMaxCompletionTokens(model)
? { ...baseParams, max_completion_tokens: maxTokens }
: { ...baseParams, max_tokens: maxTokens };
const response = await this.client!.chat.completions.create(
requestParams,
);
let content = "";
const toolCalls: Array<{
id: string;
type: "function";
function: { name: string; arguments: string };
}> = [];
let markdownOutputId: string | null = null;
let sequenceNumber = 0;
// Stream the response
for await (
const chunk of response as AsyncIterable<
OpenAI.Chat.Completions.ChatCompletionChunk
>
) {
const delta = chunk.choices[0]?.delta;
if (delta?.content) {
// Handle content streaming
if (!markdownOutputId) {
// Start new markdown output
const metadata: AnodeCellMetadata = {
role: "assistant",
ai_provider: this.provider,
ai_model: model,
iteration: iteration + 1,
};
markdownOutputId = context.markdown(delta.content, {
anode: metadata,
});
} else {
// Append to existing markdown output
context.appendMarkdown(
markdownOutputId,
delta.content,
sequenceNumber++,
);
}
content += delta.content;
}
if (delta?.tool_calls) {
// Handle tool calls
for (const toolCallDelta of delta.tool_calls) {
const index = toolCallDelta.index ?? 0;
// Initialize tool call if needed
if (!toolCalls[index]) {
toolCalls[index] = {
id: "",
type: "function",
function: { name: "", arguments: "" },
};
}
if (toolCallDelta.id) {
toolCalls[index].id = toolCallDelta.id;
}
if (toolCallDelta.function?.name) {
toolCalls[index].function.name = toolCallDelta.function.name;
}
if (toolCallDelta.function?.arguments) {
toolCalls[index].function.arguments +=
toolCallDelta.function.arguments;
}
}
}
}
// Add assistant message to conversation (with tool_calls if present)
const assistantMessage: ChatMessage = {
role: "assistant",
content: content || "",
...(toolCalls && toolCalls.length > 0
? { tool_calls: toolCalls }
: {}),
};
conversationMessages.push(assistantMessage);
// Handle tool calls if present
if (toolCalls && toolCalls.length > 0 && onToolCall) {
logger.info(
`Processing ${toolCalls.length} tool calls in iteration ${
iteration + 1
}`,
);
let _hasToolErrors = false;
const toolResults: string[] = [];
for (const toolCall of toolCalls) {
if (toolCall.type === "function") {
let args: Record<string, unknown> = {};
let parseError: Error | null = null;
let validationError: Error | null = null;
try {
args = JSON.parse(toolCall.function.arguments);
} catch (error) {
parseError = error instanceof Error
? error
: new Error(String(error));
logger.error(
`Error parsing tool arguments for ${toolCall.function.name}`,
error,
);
}
// Validate tool parameters against schema if parsing succeeded
if (!parseError) {
try {
const toolDef = all_tools.find((tool) =>
tool.name === toolCall.function.name
);
if (toolDef && toolDef.parameters?.required) {
const missingParams = toolDef.parameters.required.filter(
(param: string) => !(param in args),
);
if (missingParams.length > 0) {
validationError = new Error(
`Missing required parameters: ${
missingParams.join(", ")
}`,
);
}
}
} catch (error) {
validationError = error instanceof Error
? error
: new Error(String(error));
logger.error(
`Error validating tool parameters for ${toolCall.function.name}`,
error,
);
}
}
if (parseError || validationError) {
_hasToolErrors = true;
const error = parseError || validationError!;
const errorType = parseError ? "parsing" : "validation";
const errorMessage =
`Error ${errorType} arguments: ${error.message}`;
toolResults.push(
`Tool ${toolCall.function.name} failed: ${errorMessage}`,
);
const toolCallData: ToolCallOutput = {
tool_call_id: toolCall.id,
tool_name: toolCall.function.name,
arguments: parseError
? { raw_arguments: toolCall.function.arguments }
: args,
status: "error",
timestamp: new Date().toISOString(),
result: errorMessage,
};
const errorMetadata: AnodeCellMetadata = {
role: "function_call",
tool_call: true,
tool_name: toolCall.function.name,
tool_error: true,
iteration: iteration + 1,
};
const errorOutput: OutputData = {
type: "display_data",
data: {
[AI_TOOL_CALL_MIME_TYPE]: toolCallData,
"text/markdown":
`❌ **Tool failed**: \`${toolCall.function.name}\`\n\nError ${errorType} arguments: ${error.message}`,
"text/plain":
`Tool failed: ${toolCall.function.name} - Error ${errorType} arguments: ${error.message}`,
},
metadata: {
anode: errorMetadata,
},
};
// Emit immediately via execution context
context.display(errorOutput.data, errorOutput.metadata);
// Add tool error to conversation
conversationMessages.push({
role: "tool",
content: `Error: ${errorMessage}`,
tool_call_id: toolCall.id,
});
continue;
}
try {
logger.info(`Calling tool: ${toolCall.function.name}`, {
args,
iteration: iteration + 1,
});
// Execute the tool call and get result
const toolResult = await onToolCall({
id: toolCall.id,
name: toolCall.function.name,
arguments: args,
});
toolResults.push(
`Tool ${toolCall.function.name} executed successfully${
toolResult ? `: ${toolResult}` : ""
}`,
);
// Add confirmation output with custom media type
const toolCallData: ToolCallOutput = {
tool_call_id: toolCall.id,
tool_name: toolCall.function.name,
arguments: args,
status: "success",
timestamp: new Date().toISOString(),
result: toolResult,
};
const successMetadata: AnodeCellMetadata = {
role: "function_call",
tool_call: true,
tool_name: toolCall.function.name,
tool_args: args,
iteration: iteration + 1,
};
const successOutput: OutputData = {
type: "display_data",
data: {
[AI_TOOL_CALL_MIME_TYPE]: toolCallData,
"text/markdown":
`🔧 **Tool executed**: \`${toolCall.function.name}\`\n\n${
this.formatToolCall(toolCall.function.name, args)
}${toolResult ? `\n\n**Result**: ${toolResult}` : ""}`,
"text/plain": `Tool executed: ${toolCall.function.name}${
toolResult ? ` - ${toolResult}` : ""
}`,
},
metadata: {
anode: successMetadata,
},
};
// Emit immediately via execution context
context.display(successOutput.data, successOutput.metadata);
// Add tool result to conversation
conversationMessages.push({
role: "tool",
content: toolResult || "Success",
tool_call_id: toolCall.id,
});
// Emit tool result with role metadata
const toolResultMetadata: AnodeCellMetadata = {
role: "tool",
tool_call_id: toolCall.id,
tool_name: toolCall.function.name,
iteration: iteration + 1,
};
context.display({
[AI_TOOL_RESULT_MIME_TYPE]: {
tool_call_id: toolCall.id,
result: toolResult,
status: "success",
},
}, {
anode: toolResultMetadata,
});
} catch (error) {
_hasToolErrors = true;
const errorMessage = error instanceof Error
? error.message
: String(error);
toolResults.push(
`Tool ${toolCall.function.name} failed: ${errorMessage}`,
);
logger.error(
`Error executing tool ${toolCall.function.name}`,
error,
);
const errorToolCallData: ToolCallOutput = {
tool_call_id: toolCall.id,
tool_name: toolCall.function.name,
arguments: args,
status: "error",
timestamp: new Date().toISOString(),
result: errorMessage,
};
const toolErrorMetadata: AnodeCellMetadata = {
role: "function_call",
tool_call: true,
tool_name: toolCall.function.name,
tool_error: true,
iteration: iteration + 1,
};
const errorOutput: OutputData = {
type: "display_data",
data: {
[AI_TOOL_CALL_MIME_TYPE]: errorToolCallData,
"text/markdown":
`❌ **Tool failed**: \`${toolCall.function.name}\`\n\nError: ${errorMessage}`,
"text/plain":
`Tool failed: ${toolCall.function.name} - ${errorMessage}`,
},
metadata: {
anode: toolErrorMetadata,
},
};
// Emit immediately via execution context
context.display(errorOutput.data, errorOutput.metadata);
// Add tool error to conversation
conversationMessages.push({
role: "tool",
content: `Error: ${errorMessage}`,
tool_call_id: toolCall.id,
});
}
}
}
// Content was already emitted above with role metadata
// Continue to next iteration to let AI respond to tool results
iteration++;
continue;
}
// Content was already emitted above with role metadata
// No more tool calls, conversation is complete
logger.info(
`Agentic conversation completed after ${iteration + 1} iterations`,
);
break;
}
if (iteration >= maxIterations) {
logger.warn(
`Agentic conversation reached max iterations (${maxIterations})`,
);
context.display({
"text/markdown":
"⚠️ **Reached maximum iterations** - The AI assistant has reached the maximum number of conversation iterations. The conversation may be incomplete.",
"text/plain":
"Reached maximum iterations - conversation may be incomplete",
}, {
"anode/ai_response": true,
"anode/ai_provider": this.provider,
"anode/ai_model": model,
"anode/max_iterations_reached": true,
});
}
} catch (error: unknown) {
logger.error(`${this.provider} API error in agentic conversation`, error);
let errorMessage = "Unknown error occurred";
if (error && typeof error === "object") {
const err = error as { status?: number; message?: string };
if (err.status === 401) {
errorMessage =
"Invalid API key. Please check your API key environment variable.";
} else if (err.status === 429) {
errorMessage = "Rate limit exceeded. Please try again later.";
} else if (err.status === 500) {
errorMessage =
`${this.provider} server error. Please try again later.`;
} else if (err.message) {
errorMessage = err.message;
}
}
const errorOutputs = this.createErrorOutput(
`${this.provider} API Error: ${errorMessage}`,
);
for (const output of errorOutputs) {
if (output.type === "display_data") {
context.display(output.data, output.metadata || {});
} else if (output.type === "error" && output.data) {
const errorData = output.data as {
ename?: string;
evalue?: string;
traceback?: string[];
};
context.error(
errorData.ename || "OpenAIError",
errorData.evalue || "Unknown error",
errorData.traceback || ["Unknown error"],
);
}
}
}
}
private createErrorOutput(message: string): OutputData[] {
return [{
type: "error",
data: {
ename: "OpenAIError",
evalue: message,
traceback: [message],
},
}];
}
private createConfigHelpOutput(): OutputData[] {
const configMessage = `# AI Configuration Required
AI has not been configured for this runtime yet. To use AI Cells, you need to set an \`OPENAI_API_KEY\` before starting your runtime agent.
## Setup Instructions
Set your API key as an environment variable:
\`\`\`bash
OPENAI_API_KEY=your-api-key-here deno run --allow-all your-script.ts
\`\`\`
Or add it to your \`.env\` file:
\`\`\`
OPENAI_API_KEY=your-api-key-here
\`\`\`
## Get an API Key
1. Visit [OpenAI's website](https://platform.openai.com/api-keys)
2. Create an account or sign in
3. Generate a new API key
4. Copy the key and use it in your environment
Once configured, your AI cells will work with real OpenAI models!`;
return [{
type: "display_data",
data: {
"text/markdown": configMessage,
"text/plain": configMessage.replace(/[#*`]/g, "").replace(/\n+/g, "\n")
.trim(),
},
metadata: {
"anode/ai_config_help": true,
},
}];
}
private formatToolCall(
toolName: string,
args: Record<string, unknown>,
): string {
switch (toolName) {
case "create_cell": {
const cellType = String(args.cellType || "code");
const afterId = String(args.after_id || "");
const content = String(args.content || "");
return `Created **${cellType}** cell after **${afterId}**\n\n` +
`Content preview:\n\`\`\`${
cellType === "code" ? "python" : cellType
}\n${content.slice(0, 200)}${
content.length > 200 ? "..." : ""
}\n\`\`\``;
}
case "modify_cell": {
const cellId = String(args.cellId || "");
const content = String(args.content || "");
return `Modified cell **${cellId}**\n\n` +
`New content preview:\n\`\`\`python\n${content.slice(0, 200)}${
content.length > 200 ? "..." : ""
}\n\`\`\``;
}
case "execute_cell": {
const cellId = String(args.cellId || "");
return `Executed cell **${cellId}**`;
}
default: {
return `Arguments: ${JSON.stringify(args, null, 2)}`;
}
}
}
}
// Export class for testing
export { RuntOpenAIClient as OpenAIClient };