@mastra/openai 1.0.1-alpha.8 → 1.0.3

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.
package/dist/index.js ADDED
@@ -0,0 +1,1175 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { ReadableStream, TransformStream } from 'stream/web';
3
+ import { Agent } from '@mastra/core/agent';
4
+ import { RequestContext } from '@mastra/core/request-context';
5
+ import { ChunkFrom, MastraModelOutput } from '@mastra/core/stream';
6
+ import { Agent as Agent$1, run } from '@openai/agents';
7
+ import { MessageList } from '@mastra/core/agent/message-list';
8
+ import { getOrCreateSpan, EntityType, SpanType, executeWithContext } from '@mastra/core/observability';
9
+ import { toStandardSchema, standardSchemaToJSONSchema } from '@mastra/core/schema';
10
+
11
+ // src/index.ts
12
+ function createNoopModel({ modelId, provider }) {
13
+ return {
14
+ modelId,
15
+ provider,
16
+ specificationVersion: "v3",
17
+ supportedUrls: {},
18
+ doGenerate: async () => createNoopStreamResult(),
19
+ doStream: async () => createNoopStreamResult()
20
+ };
21
+ }
22
+ function createNoopStreamResult() {
23
+ return {
24
+ stream: new ReadableStream({
25
+ start: (controller) => controller.close()
26
+ })
27
+ };
28
+ }
29
+ function createCompletedMastraStream({
30
+ runId,
31
+ prompt,
32
+ text,
33
+ responseId,
34
+ modelId,
35
+ usage,
36
+ providerMetadata,
37
+ costContext,
38
+ object
39
+ }) {
40
+ return new ReadableStream({
41
+ start(controller) {
42
+ const textId = randomUUID();
43
+ enqueueStartChunks(controller, {
44
+ runId,
45
+ prompt,
46
+ textId,
47
+ responseId,
48
+ modelId,
49
+ providerMetadata
50
+ });
51
+ if (text) {
52
+ enqueueTextDelta(controller, runId, textId, text);
53
+ }
54
+ enqueueFinishChunks(controller, {
55
+ runId,
56
+ prompt,
57
+ textId,
58
+ text,
59
+ responseId,
60
+ modelId,
61
+ usage,
62
+ providerMetadata,
63
+ costContext,
64
+ object
65
+ });
66
+ controller.close();
67
+ }
68
+ });
69
+ }
70
+ function createMastraOutput({
71
+ messages,
72
+ runId,
73
+ modelId,
74
+ provider,
75
+ stream,
76
+ options
77
+ }) {
78
+ const messageList = new MessageList();
79
+ messageList.add(messages, "input");
80
+ messageList.add([{ role: "assistant", content: "" }], "response");
81
+ return new MastraModelOutput({
82
+ model: {
83
+ modelId,
84
+ provider,
85
+ version: "v3"
86
+ },
87
+ stream,
88
+ messageList,
89
+ messageId: randomUUID(),
90
+ options: {
91
+ ...options,
92
+ runId
93
+ }
94
+ });
95
+ }
96
+ function toFullOutput({
97
+ messages,
98
+ runId,
99
+ provider,
100
+ result,
101
+ options
102
+ }) {
103
+ const text = result.content.map((part) => part.text).join("");
104
+ const stream = createCompletedMastraStream({
105
+ runId,
106
+ prompt: promptToText(messages),
107
+ text,
108
+ responseId: result.response.id,
109
+ modelId: result.response.modelId,
110
+ usage: toLanguageModelUsage(result.usage),
111
+ providerMetadata: result.providerMetadata,
112
+ costContext: result.costContext,
113
+ object: result.object
114
+ });
115
+ return createMastraOutput({
116
+ messages,
117
+ runId,
118
+ modelId: result.response.modelId,
119
+ provider,
120
+ stream,
121
+ options
122
+ }).getFullOutput();
123
+ }
124
+ function createSDKAgentTelemetry({
125
+ agentId,
126
+ agentName,
127
+ provider,
128
+ modelId,
129
+ messages,
130
+ prompt,
131
+ runId,
132
+ streaming,
133
+ method,
134
+ requestContext,
135
+ instructions,
136
+ maxSteps,
137
+ tracingOptions,
138
+ tracingContext,
139
+ onFinish,
140
+ onStepFinish,
141
+ mastra
142
+ }) {
143
+ const agentSpan = getOrCreateSpan({
144
+ type: SpanType.AGENT_RUN,
145
+ name: `agent run: '${agentId}'`,
146
+ entityType: EntityType.AGENT,
147
+ entityId: agentId,
148
+ entityName: agentName,
149
+ input: messages,
150
+ attributes: {
151
+ prompt,
152
+ instructions,
153
+ maxSteps
154
+ },
155
+ metadata: {
156
+ runId,
157
+ sdkAgent: true,
158
+ sdkProvider: provider,
159
+ sdkMethod: method
160
+ },
161
+ tracingOptions,
162
+ tracingContext,
163
+ requestContext,
164
+ mastra
165
+ });
166
+ const modelSpan = agentSpan?.createChildSpan({
167
+ type: SpanType.MODEL_GENERATION,
168
+ name: `llm: '${modelId}'`,
169
+ input: {
170
+ messages
171
+ },
172
+ attributes: {
173
+ model: modelId,
174
+ provider,
175
+ streaming
176
+ },
177
+ metadata: {
178
+ runId,
179
+ sdkAgent: true,
180
+ sdkProvider: provider,
181
+ sdkMethod: method
182
+ },
183
+ requestContext
184
+ });
185
+ const modelSpanTracker = getModelSpanTracker(modelSpan);
186
+ const toolSpans = /* @__PURE__ */ new Map();
187
+ let ended = false;
188
+ const startToolCall = ({ toolCallId, toolName, input }) => {
189
+ if (toolSpans.has(toolCallId)) {
190
+ return;
191
+ }
192
+ const parentSpan = agentSpan ?? modelSpan;
193
+ if (!parentSpan) {
194
+ return;
195
+ }
196
+ const mcp = parseMcpToolName(toolName);
197
+ const span = mcp ? parentSpan.createChildSpan({
198
+ type: SpanType.MCP_TOOL_CALL,
199
+ name: `mcp_tool: '${toolName}' on '${mcp.serverName}'`,
200
+ input,
201
+ entityType: EntityType.TOOL,
202
+ entityId: toolName,
203
+ entityName: toolName,
204
+ attributes: {
205
+ mcpServer: mcp.serverName
206
+ },
207
+ metadata: {
208
+ runId,
209
+ sdkAgent: true,
210
+ sdkProvider: provider,
211
+ sdkMethod: method,
212
+ toolCallId
213
+ },
214
+ requestContext
215
+ }) : parentSpan.createChildSpan({
216
+ type: SpanType.TOOL_CALL,
217
+ name: `tool: '${toolName}'`,
218
+ input,
219
+ entityType: EntityType.TOOL,
220
+ entityId: toolName,
221
+ entityName: toolName,
222
+ attributes: {
223
+ toolType: "tool"
224
+ },
225
+ metadata: {
226
+ runId,
227
+ sdkAgent: true,
228
+ sdkProvider: provider,
229
+ sdkMethod: method,
230
+ toolCallId
231
+ },
232
+ requestContext
233
+ });
234
+ toolSpans.set(toolCallId, span);
235
+ };
236
+ const endToolCall = ({ toolCallId, output, isError }) => {
237
+ const span = toolSpans.get(toolCallId);
238
+ if (!span) {
239
+ return;
240
+ }
241
+ toolSpans.delete(toolCallId);
242
+ if (isError) {
243
+ span.error({
244
+ error: output instanceof Error ? output : new Error(typeof output === "string" ? output : "SDK tool call failed"),
245
+ attributes: { success: false }
246
+ });
247
+ return;
248
+ }
249
+ span.end({
250
+ output,
251
+ attributes: { success: true }
252
+ });
253
+ };
254
+ const closeOpenToolSpans = (success, error) => {
255
+ for (const [toolCallId, span] of toolSpans) {
256
+ toolSpans.delete(toolCallId);
257
+ if (success) {
258
+ span.end({ attributes: { success: true } });
259
+ continue;
260
+ }
261
+ const normalized = error instanceof Error ? error : new Error(String(error ?? "SDK agent run failed"));
262
+ span.error({ error: normalized, attributes: { success: false } });
263
+ }
264
+ };
265
+ const endModel = ({
266
+ text,
267
+ usage,
268
+ providerMetadata,
269
+ finishReason = "stop",
270
+ responseId,
271
+ responseModel,
272
+ costContext
273
+ }) => {
274
+ if (modelSpanTracker) {
275
+ modelSpanTracker.endGeneration({
276
+ output: {
277
+ text
278
+ },
279
+ attributes: {
280
+ finishReason,
281
+ responseId,
282
+ responseModel,
283
+ costContext
284
+ },
285
+ usage,
286
+ providerMetadata
287
+ });
288
+ return;
289
+ }
290
+ modelSpan?.end({
291
+ output: {
292
+ text
293
+ },
294
+ attributes: {
295
+ finishReason,
296
+ responseId,
297
+ responseModel,
298
+ usage: usage ? toUsageStats(usage) : void 0,
299
+ costContext
300
+ }
301
+ });
302
+ };
303
+ const end = (result) => {
304
+ if (ended) {
305
+ return;
306
+ }
307
+ ended = true;
308
+ closeOpenToolSpans(true);
309
+ endModel(result);
310
+ agentSpan?.end({
311
+ output: {
312
+ text: result.text
313
+ }
314
+ });
315
+ };
316
+ const fail = (error) => {
317
+ if (ended) {
318
+ return;
319
+ }
320
+ ended = true;
321
+ const normalized = error instanceof Error ? error : new Error(String(error));
322
+ closeOpenToolSpans(false, normalized);
323
+ if (modelSpanTracker) {
324
+ modelSpanTracker.reportGenerationError({ error: normalized });
325
+ } else {
326
+ modelSpan?.error({ error: normalized });
327
+ }
328
+ agentSpan?.error({ error: normalized });
329
+ };
330
+ return {
331
+ execute: (fn) => executeWithContext({ span: modelSpan ?? agentSpan, fn }),
332
+ endGenerate(result) {
333
+ end({
334
+ text: result.content.map((part) => part.text).join(""),
335
+ usage: toLanguageModelUsage(result.usage),
336
+ providerMetadata: result.providerMetadata,
337
+ finishReason: result.finishReason.unified,
338
+ responseId: result.response.id,
339
+ responseModel: result.response.modelId,
340
+ costContext: result.costContext
341
+ });
342
+ },
343
+ fail,
344
+ startToolCall,
345
+ endToolCall,
346
+ wrapStream(stream) {
347
+ const trackedStream = modelSpanTracker?.wrapStream(stream) ?? stream;
348
+ return wrapStreamForAgentSpan(trackedStream, {
349
+ end,
350
+ fail
351
+ });
352
+ },
353
+ outputOptions() {
354
+ return {
355
+ onFinish,
356
+ onStepFinish,
357
+ requestContext,
358
+ tracingContext: agentSpan ? { currentSpan: agentSpan } : tracingContext
359
+ };
360
+ }
361
+ };
362
+ }
363
+ function parseMcpToolName(toolName) {
364
+ const match = /^mcp__([^_].*?)__(.+)$/.exec(toolName);
365
+ if (!match?.[1] || !match[2]) {
366
+ return void 0;
367
+ }
368
+ return {
369
+ serverName: match[1],
370
+ toolName: match[2]
371
+ };
372
+ }
373
+ function getModelSpanTracker(modelSpan) {
374
+ if (!modelSpan || !("createTracker" in modelSpan)) {
375
+ return void 0;
376
+ }
377
+ return modelSpan.createTracker();
378
+ }
379
+ function wrapStreamForAgentSpan(stream, telemetry) {
380
+ let text = "";
381
+ return stream.pipeThrough(
382
+ new TransformStream({
383
+ transform(chunk, controller) {
384
+ if (chunk.type === "text-delta") {
385
+ text += chunk.payload.text;
386
+ }
387
+ if (chunk.type === "finish") {
388
+ telemetry.end({
389
+ text,
390
+ usage: chunk.payload.output.usage,
391
+ providerMetadata: chunk.payload.providerMetadata,
392
+ finishReason: chunk.payload.stepResult.reason,
393
+ responseId: chunk.payload.response?.id,
394
+ responseModel: chunk.payload.response?.modelId,
395
+ costContext: getCostContext(chunk.payload.metadata?.costContext)
396
+ });
397
+ }
398
+ if (chunk.type === "error") {
399
+ telemetry.fail(chunk.payload.error);
400
+ }
401
+ controller.enqueue(chunk);
402
+ },
403
+ flush() {
404
+ telemetry.end({ text });
405
+ }
406
+ })
407
+ );
408
+ }
409
+ function toUsageStats(usage) {
410
+ return {
411
+ inputTokens: usage.inputTokens,
412
+ outputTokens: usage.outputTokens,
413
+ inputDetails: {
414
+ cacheRead: usage.cachedInputTokens,
415
+ cacheWrite: usage.cacheCreationInputTokens
416
+ },
417
+ outputDetails: {
418
+ text: usage.outputTokens,
419
+ reasoning: usage.reasoningTokens
420
+ }
421
+ };
422
+ }
423
+ function getCostContext(value) {
424
+ if (!value || typeof value !== "object") {
425
+ return void 0;
426
+ }
427
+ return value;
428
+ }
429
+ function enqueueStartChunks(controller, {
430
+ runId,
431
+ prompt,
432
+ textId,
433
+ responseId,
434
+ modelId,
435
+ providerMetadata
436
+ }) {
437
+ controller.enqueue({
438
+ type: "start",
439
+ runId,
440
+ from: ChunkFrom.AGENT,
441
+ payload: {}
442
+ });
443
+ controller.enqueue({
444
+ type: "step-start",
445
+ runId,
446
+ from: ChunkFrom.AGENT,
447
+ payload: {
448
+ request: { body: prompt }
449
+ }
450
+ });
451
+ controller.enqueue({
452
+ type: "response-metadata",
453
+ runId,
454
+ from: ChunkFrom.AGENT,
455
+ payload: {
456
+ ...responseId ? { id: responseId } : {},
457
+ modelId,
458
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
459
+ }
460
+ });
461
+ controller.enqueue({
462
+ type: "text-start",
463
+ runId,
464
+ from: ChunkFrom.AGENT,
465
+ payload: {
466
+ id: textId,
467
+ providerMetadata
468
+ }
469
+ });
470
+ }
471
+ function enqueueTextDelta(controller, runId, textId, text) {
472
+ controller.enqueue({
473
+ type: "text-delta",
474
+ runId,
475
+ from: ChunkFrom.AGENT,
476
+ payload: {
477
+ id: textId,
478
+ text
479
+ }
480
+ });
481
+ }
482
+ function enqueueFinishChunks(controller, {
483
+ runId,
484
+ prompt,
485
+ textId,
486
+ text,
487
+ responseId,
488
+ modelId,
489
+ usage,
490
+ providerMetadata,
491
+ costContext,
492
+ object
493
+ }) {
494
+ const timestamp = /* @__PURE__ */ new Date();
495
+ const response = {
496
+ ...responseId ? { id: responseId } : {},
497
+ modelId,
498
+ timestamp
499
+ };
500
+ const metadata = {
501
+ providerMetadata,
502
+ costContext,
503
+ request: { body: prompt },
504
+ modelId,
505
+ timestamp
506
+ };
507
+ controller.enqueue({
508
+ type: "text-end",
509
+ runId,
510
+ from: ChunkFrom.AGENT,
511
+ payload: {
512
+ id: textId,
513
+ providerMetadata
514
+ }
515
+ });
516
+ if (object !== void 0) {
517
+ controller.enqueue({
518
+ type: "object-result",
519
+ runId,
520
+ from: ChunkFrom.AGENT,
521
+ object
522
+ });
523
+ }
524
+ controller.enqueue({
525
+ type: "step-finish",
526
+ runId,
527
+ from: ChunkFrom.AGENT,
528
+ payload: {
529
+ ...responseId ? { id: responseId } : {},
530
+ providerMetadata,
531
+ totalUsage: usage,
532
+ response,
533
+ stepResult: {
534
+ reason: "stop",
535
+ warnings: []
536
+ },
537
+ output: {
538
+ text,
539
+ usage,
540
+ steps: []
541
+ },
542
+ metadata
543
+ }
544
+ });
545
+ controller.enqueue({
546
+ type: "finish",
547
+ runId,
548
+ from: ChunkFrom.AGENT,
549
+ payload: {
550
+ stepResult: {
551
+ reason: "stop",
552
+ warnings: []
553
+ },
554
+ output: {
555
+ usage,
556
+ steps: []
557
+ },
558
+ metadata,
559
+ providerMetadata,
560
+ messages: {
561
+ all: [],
562
+ user: [],
563
+ nonUser: []
564
+ },
565
+ response
566
+ }
567
+ });
568
+ }
569
+ function toLanguageModelUsage(usage) {
570
+ const inputTokens = usage.inputTokens.total ?? 0;
571
+ const outputTokens = usage.outputTokens.total ?? 0;
572
+ return {
573
+ inputTokens,
574
+ outputTokens,
575
+ totalTokens: inputTokens + outputTokens,
576
+ cachedInputTokens: usage.inputTokens.cacheRead,
577
+ cacheCreationInputTokens: usage.inputTokens.cacheWrite,
578
+ reasoningTokens: usage.outputTokens.reasoning,
579
+ raw: usage
580
+ };
581
+ }
582
+ function createProviderMetadata(provider, metadata) {
583
+ return {
584
+ [provider]: toJsonRecord(metadata)
585
+ };
586
+ }
587
+ function toJsonRecord(record) {
588
+ return Object.fromEntries(
589
+ Object.entries(record).filter((entry) => entry[1] !== void 0).map(([key, value]) => [key, toJsonValue(value)])
590
+ );
591
+ }
592
+ function toJsonValue(value) {
593
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
594
+ return value;
595
+ }
596
+ if (Array.isArray(value)) {
597
+ return value.filter((item) => item !== void 0).map(toJsonValue);
598
+ }
599
+ if (value instanceof Date) {
600
+ return value.toISOString();
601
+ }
602
+ if (typeof value === "object") {
603
+ return toJsonRecord(value);
604
+ }
605
+ return String(value);
606
+ }
607
+ function promptToText(prompt) {
608
+ if (typeof prompt === "string") {
609
+ return prompt;
610
+ }
611
+ if (Array.isArray(prompt)) {
612
+ return prompt.map(promptToText).filter(Boolean).join("\n");
613
+ }
614
+ if (!prompt || typeof prompt !== "object") {
615
+ return "";
616
+ }
617
+ const record = prompt;
618
+ if (typeof record.text === "string") {
619
+ return record.text;
620
+ }
621
+ if (typeof record.content === "string") {
622
+ return record.content;
623
+ }
624
+ if (record.content) {
625
+ return promptToText(record.content);
626
+ }
627
+ return "";
628
+ }
629
+ function getStructuredOutputSchema(structuredOutput) {
630
+ if (!structuredOutput?.schema) {
631
+ return void 0;
632
+ }
633
+ return {
634
+ type: "json_schema",
635
+ name: "mastra_output",
636
+ strict: false,
637
+ schema: standardSchemaToJSONSchema(toStandardSchema(structuredOutput.schema))
638
+ };
639
+ }
640
+ async function getStructuredOutputFromValue(value, structuredOutput) {
641
+ if (!structuredOutput?.schema) {
642
+ return void 0;
643
+ }
644
+ let parsed;
645
+ if (typeof value === "string") {
646
+ try {
647
+ parsed = JSON.parse(value);
648
+ } catch (error) {
649
+ return handleStructuredOutputError(
650
+ new Error("Structured output must be valid JSON.", { cause: error }),
651
+ structuredOutput
652
+ );
653
+ }
654
+ } else {
655
+ parsed = value;
656
+ }
657
+ const schema = toStandardSchema(structuredOutput.schema);
658
+ const result = await schema["~standard"].validate(parsed);
659
+ if (!result.issues) {
660
+ return result.value;
661
+ }
662
+ const message = result.issues.map((issue) => `- ${issue.path?.join(".") || "root"}: ${issue.message}`).join("\n");
663
+ return handleStructuredOutputError(new Error(`Structured output validation failed:
664
+ ${message}`), structuredOutput);
665
+ }
666
+ function handleStructuredOutputError(error, structuredOutput) {
667
+ if (structuredOutput.errorStrategy === "fallback") {
668
+ return structuredOutput.fallbackValue;
669
+ }
670
+ if (structuredOutput.errorStrategy === "warn") {
671
+ structuredOutput.logger?.warn(error.message);
672
+ return void 0;
673
+ }
674
+ throw error;
675
+ }
676
+ function sumDefined(...values) {
677
+ const defined = values.filter((value) => typeof value === "number");
678
+ if (defined.length === 0) {
679
+ return void 0;
680
+ }
681
+ return defined.reduce((sum, value) => sum + value, 0);
682
+ }
683
+
684
+ // src/index.ts
685
+ var PROVIDER = "@openai/agents";
686
+ var MODEL_ID = "openai-agents-sdk";
687
+ var OpenAISDKAgent = class extends Agent {
688
+ options;
689
+ #mastra;
690
+ #createdAgent;
691
+ constructor(options) {
692
+ super({
693
+ id: options.id,
694
+ name: options.name ?? options.id,
695
+ description: options.description,
696
+ instructions: "",
697
+ model: createNoopModel({
698
+ modelId: getModelId(options),
699
+ provider: PROVIDER
700
+ })
701
+ });
702
+ this.options = options;
703
+ }
704
+ __registerMastra(mastra) {
705
+ super.__registerMastra(mastra);
706
+ this.#mastra = mastra;
707
+ }
708
+ supportsMemory() {
709
+ return false;
710
+ }
711
+ async generate(messages, options) {
712
+ const prompt = promptToText(messages);
713
+ const runId = options?.runId ?? randomUUID();
714
+ const sdkAgent = getRunOpenAIAgent(this.resolveOpenAIAgent(), options);
715
+ const modelId = getModelId(this.options, sdkAgent);
716
+ const requestContext = options?.requestContext ?? new RequestContext();
717
+ const instructions = options?.instructions ? promptToText(options.instructions) : void 0;
718
+ const telemetry = createSDKAgentTelemetry({
719
+ agentId: this.id,
720
+ agentName: this.name,
721
+ provider: PROVIDER,
722
+ modelId,
723
+ messages,
724
+ prompt,
725
+ runId,
726
+ streaming: false,
727
+ method: "generate",
728
+ requestContext,
729
+ instructions,
730
+ maxSteps: options?.maxSteps,
731
+ tracingOptions: options?.tracingOptions,
732
+ tracingContext: options?.tracingContext,
733
+ onFinish: options?.onFinish,
734
+ onStepFinish: options?.onStepFinish,
735
+ mastra: this.#mastra
736
+ });
737
+ let result;
738
+ try {
739
+ result = await telemetry.execute(() => runOpenAIGenerate(prompt, sdkAgent, runId, telemetry, options));
740
+ telemetry.endGenerate(result);
741
+ } catch (error) {
742
+ telemetry.fail(error);
743
+ throw error;
744
+ }
745
+ return toFullOutput({
746
+ messages,
747
+ runId,
748
+ provider: PROVIDER,
749
+ result,
750
+ options: { ...telemetry.outputOptions(), structuredOutput: getStructuredOutputOption(options) }
751
+ });
752
+ }
753
+ async stream(messages, options) {
754
+ const prompt = promptToText(messages);
755
+ const runId = options?.runId ?? randomUUID();
756
+ const sdkAgent = getRunOpenAIAgent(this.resolveOpenAIAgent(), options);
757
+ const modelId = getModelId(this.options, sdkAgent);
758
+ const requestContext = options?.requestContext ?? new RequestContext();
759
+ const instructions = options?.instructions ? promptToText(options.instructions) : void 0;
760
+ const telemetry = createSDKAgentTelemetry({
761
+ agentId: this.id,
762
+ agentName: this.name,
763
+ provider: PROVIDER,
764
+ modelId,
765
+ messages,
766
+ prompt,
767
+ runId,
768
+ streaming: true,
769
+ method: "stream",
770
+ requestContext,
771
+ instructions,
772
+ maxSteps: options?.maxSteps,
773
+ tracingOptions: options?.tracingOptions,
774
+ tracingContext: options?.tracingContext,
775
+ onFinish: options?.onFinish,
776
+ onStepFinish: options?.onStepFinish,
777
+ mastra: this.#mastra
778
+ });
779
+ return createMastraOutput({
780
+ messages,
781
+ runId,
782
+ modelId,
783
+ provider: PROVIDER,
784
+ stream: telemetry.wrapStream(runOpenAIAsMastraStream(prompt, sdkAgent, runId, modelId, telemetry, options)),
785
+ options: { ...telemetry.outputOptions(), structuredOutput: getStructuredOutputOption(options) }
786
+ });
787
+ }
788
+ async resumeGenerate(resumeData, options) {
789
+ const data = validateOpenAIResumeData(resumeData);
790
+ return this.generate(data.message, createOpenAIResumeRunOptions(data, options));
791
+ }
792
+ async resumeStream(resumeData, options) {
793
+ const data = validateOpenAIResumeData(resumeData);
794
+ return this.stream(data.message, createOpenAIResumeRunOptions(data, options));
795
+ }
796
+ resolveOpenAIAgent() {
797
+ this.#createdAgent ??= this.options.agent ?? new Agent$1(toOpenAIAgentOptions(this.options));
798
+ return this.#createdAgent;
799
+ }
800
+ };
801
+ function getStructuredOutputOption(options) {
802
+ return options?.structuredOutput;
803
+ }
804
+ function validateOpenAIResumeData(resumeData) {
805
+ const record = toRecord(resumeData);
806
+ if (!record || !("message" in record)) {
807
+ throw new Error("OpenAISDKAgent resumeData must include a message.");
808
+ }
809
+ if (typeof resumeData.previousResponseId === "string" || typeof resumeData.conversationId === "string" || resumeData.session !== void 0) {
810
+ return resumeData;
811
+ }
812
+ throw new Error("OpenAISDKAgent resumeData must include previousResponseId, conversationId, or session.");
813
+ }
814
+ function createOpenAIResumeRunOptions(resumeData, options) {
815
+ return {
816
+ ...options,
817
+ previousResponseId: resumeData.previousResponseId ?? options?.previousResponseId,
818
+ conversationId: resumeData.conversationId ?? options?.conversationId,
819
+ session: resumeData.session ?? options?.session
820
+ };
821
+ }
822
+ async function runOpenAIGenerate(prompt, agent, runId, telemetry, options) {
823
+ const result = await run(agent, prompt, createOpenAIRunOptions(options, false));
824
+ recordOpenAIToolTelemetry(result.newItems, telemetry);
825
+ const text = getTextFromFinalOutput(result.finalOutput);
826
+ const responseId = result.lastResponseId;
827
+ const modelId = getModelId(void 0, result.lastAgent ?? agent, result.rawResponses.at(-1));
828
+ const usage = createOpenAIUsageTotals(result.state.usage);
829
+ const providerMetadata = getOpenAIProviderMetadata({
830
+ modelId,
831
+ responseId,
832
+ lastResponseId: result.lastResponseId,
833
+ rawResponseCount: result.rawResponses.length,
834
+ itemCount: result.newItems.length,
835
+ usage
836
+ });
837
+ return {
838
+ content: [{ type: "text", text }],
839
+ finishReason: { unified: "stop", raw: "stop" },
840
+ usage: toV3Usage(usage),
841
+ response: {
842
+ id: responseId,
843
+ modelId,
844
+ timestamp: /* @__PURE__ */ new Date()
845
+ },
846
+ providerMetadata,
847
+ object: await getStructuredOutputFromValue(result.finalOutput, options?.structuredOutput)
848
+ };
849
+ }
850
+ function runOpenAIAsMastraStream(prompt, agent, runId, requestedModelId, telemetry, options) {
851
+ return new ReadableStream({
852
+ start: async (controller) => {
853
+ const textId = randomUUID();
854
+ let text = "";
855
+ let responseId;
856
+ let modelId = requestedModelId;
857
+ try {
858
+ const result = await run(agent, prompt, createOpenAIRunOptions(options, true));
859
+ enqueueStartChunks(controller, {
860
+ runId,
861
+ prompt,
862
+ textId,
863
+ responseId,
864
+ modelId
865
+ });
866
+ for await (const event of result) {
867
+ const delta = getTextDelta(event);
868
+ if (delta) {
869
+ text += delta;
870
+ enqueueTextDelta(controller, runId, textId, delta);
871
+ }
872
+ recordOpenAIStreamToolTelemetry(event, telemetry);
873
+ }
874
+ await result.completed;
875
+ responseId = result.lastResponseId ?? responseId;
876
+ modelId = getModelId(void 0, result.lastAgent ?? agent, result.rawResponses.at(-1));
877
+ if (!text) {
878
+ text = getTextFromFinalOutput(result.finalOutput);
879
+ if (text) {
880
+ enqueueTextDelta(controller, runId, textId, text);
881
+ }
882
+ }
883
+ const usage = createOpenAIUsageTotals(result.state.usage);
884
+ const providerMetadata = getOpenAIProviderMetadata({
885
+ modelId,
886
+ responseId,
887
+ lastResponseId: result.lastResponseId,
888
+ rawResponseCount: result.rawResponses.length,
889
+ itemCount: result.newItems.length,
890
+ usage
891
+ });
892
+ enqueueFinishChunks(controller, {
893
+ runId,
894
+ prompt,
895
+ textId,
896
+ text,
897
+ responseId,
898
+ modelId,
899
+ usage: toLanguageModelUsage(toV3Usage(usage)),
900
+ providerMetadata,
901
+ object: await getStructuredOutputFromValue(result.finalOutput, options?.structuredOutput)
902
+ });
903
+ controller.close();
904
+ } catch (error) {
905
+ controller.enqueue({
906
+ type: "error",
907
+ runId,
908
+ from: ChunkFrom.AGENT,
909
+ payload: { error }
910
+ });
911
+ controller.close();
912
+ }
913
+ }
914
+ });
915
+ }
916
+ function toOpenAIAgentOptions(options) {
917
+ return {
918
+ name: options.name ?? options.id,
919
+ ...options.sdkOptions
920
+ };
921
+ }
922
+ function getRunOpenAIAgent(agent, options) {
923
+ const outputType = getStructuredOutputSchema(options?.structuredOutput);
924
+ if (!outputType) {
925
+ return agent;
926
+ }
927
+ return agent.clone({ outputType });
928
+ }
929
+ function createOpenAIRunOptions(options, stream) {
930
+ const runOptions = { stream };
931
+ addDefined(runOptions, "maxTurns", options?.maxSteps);
932
+ addDefined(runOptions, "signal", options?.abortSignal ?? options?.signal);
933
+ addDefined(runOptions, "conversationId", options?.conversationId);
934
+ addDefined(runOptions, "previousResponseId", options?.previousResponseId);
935
+ addDefined(runOptions, "session", options?.session);
936
+ return runOptions;
937
+ }
938
+ function addDefined(target, key, value) {
939
+ if (value !== void 0) {
940
+ target[key] = value;
941
+ }
942
+ }
943
+ function getModelId(options, agent, rawResponse) {
944
+ return getModelNameFromUnknown(rawResponse) ?? getModelNameFromUnknown(agent?.model) ?? getModelNameFromUnknown(options?.sdkOptions?.model) ?? MODEL_ID;
945
+ }
946
+ function getModelNameFromUnknown(value) {
947
+ if (typeof value === "string") {
948
+ return value;
949
+ }
950
+ const record = toRecord(value);
951
+ return getString(record, "model") ?? getString(record, "modelId") ?? getString(record, "modelName") ?? getString(toRecord(record?.providerData), "model");
952
+ }
953
+ function getTextFromFinalOutput(output) {
954
+ if (typeof output === "string") {
955
+ return output;
956
+ }
957
+ if (output === void 0 || output === null) {
958
+ return "";
959
+ }
960
+ return JSON.stringify(output);
961
+ }
962
+ function createOpenAIUsageTotals(usage) {
963
+ const record = toRecord(usage);
964
+ if (!record) {
965
+ return {};
966
+ }
967
+ const inputDetails = getDetailRecords(record.inputTokensDetails);
968
+ const outputDetails = getDetailRecords(record.outputTokensDetails);
969
+ const requestUsageEntries = Array.isArray(record.requestUsageEntries) ? record.requestUsageEntries : void 0;
970
+ return {
971
+ inputTokens: getNumber(record.inputTokens),
972
+ outputTokens: getNumber(record.outputTokens),
973
+ cacheReadInputTokens: sumDetails(inputDetails, "cachedTokens", "cached_tokens", "cacheReadInputTokens"),
974
+ cacheCreationInputTokens: sumDetails(inputDetails, "cacheCreationInputTokens", "cache_creation_input_tokens"),
975
+ reasoningTokens: sumDetails(outputDetails, "reasoningTokens", "reasoning_tokens"),
976
+ requests: getNumber(record.requests),
977
+ requestUsageEntries
978
+ };
979
+ }
980
+ function getDetailRecords(value) {
981
+ if (Array.isArray(value)) {
982
+ return value.filter(isRecord);
983
+ }
984
+ const record = toRecord(value);
985
+ return record ? [record] : [];
986
+ }
987
+ function sumDetails(records, ...keys) {
988
+ let total = 0;
989
+ let found = false;
990
+ for (const record of records) {
991
+ for (const key of keys) {
992
+ const value = getNumber(record[key]);
993
+ if (value !== void 0) {
994
+ total += value;
995
+ found = true;
996
+ }
997
+ }
998
+ }
999
+ return found ? total : void 0;
1000
+ }
1001
+ function toV3Usage(usage) {
1002
+ const totalInputTokens = usage.inputTokens;
1003
+ const cacheRead = usage.cacheReadInputTokens;
1004
+ const cacheWrite = usage.cacheCreationInputTokens;
1005
+ const noCache = totalInputTokens === void 0 ? void 0 : Math.max(totalInputTokens - (sumDefined(cacheRead, cacheWrite) ?? 0), 0);
1006
+ const outputTokens = usage.outputTokens;
1007
+ const reasoningTokens = usage.reasoningTokens;
1008
+ return {
1009
+ inputTokens: {
1010
+ total: totalInputTokens,
1011
+ noCache,
1012
+ cacheRead,
1013
+ cacheWrite
1014
+ },
1015
+ outputTokens: {
1016
+ total: outputTokens,
1017
+ text: outputTokens,
1018
+ reasoning: reasoningTokens
1019
+ }
1020
+ };
1021
+ }
1022
+ function getOpenAIProviderMetadata({
1023
+ modelId,
1024
+ responseId,
1025
+ lastResponseId,
1026
+ rawResponseCount,
1027
+ itemCount,
1028
+ usage
1029
+ }) {
1030
+ return createProviderMetadata("openai", {
1031
+ model: modelId,
1032
+ responseId,
1033
+ lastResponseId,
1034
+ rawResponseCount,
1035
+ itemCount,
1036
+ usage
1037
+ });
1038
+ }
1039
+ function recordOpenAIToolTelemetry(items, telemetry) {
1040
+ for (const item of items) {
1041
+ if (item.type === "tool_call_item") {
1042
+ const toolCall = getOpenAIToolCall(item.rawItem);
1043
+ if (toolCall) {
1044
+ telemetry.startToolCall(toolCall);
1045
+ }
1046
+ continue;
1047
+ }
1048
+ if (item.type === "tool_call_output_item") {
1049
+ const toolOutput = getOpenAIToolOutput(item.rawItem, item.output);
1050
+ if (toolOutput) {
1051
+ telemetry.endToolCall(toolOutput);
1052
+ }
1053
+ }
1054
+ }
1055
+ }
1056
+ function recordOpenAIStreamToolTelemetry(event, telemetry) {
1057
+ if (event.type !== "run_item_stream_event") {
1058
+ return;
1059
+ }
1060
+ if (event.name === "tool_called") {
1061
+ const toolCall = getOpenAIToolCall(event.item.rawItem);
1062
+ if (toolCall) {
1063
+ telemetry.startToolCall(toolCall);
1064
+ }
1065
+ return;
1066
+ }
1067
+ if (event.name === "tool_output") {
1068
+ const toolOutput = getOpenAIToolOutput(event.item.rawItem, getObjectValue(event.item, "output"));
1069
+ if (toolOutput) {
1070
+ telemetry.endToolCall(toolOutput);
1071
+ }
1072
+ }
1073
+ }
1074
+ function getOpenAIToolCall(rawItem) {
1075
+ const record = toRecord(rawItem);
1076
+ if (!record) {
1077
+ return void 0;
1078
+ }
1079
+ if (record.type === "function_call") {
1080
+ const toolCallId = getString(record, "callId") ?? getString(record, "id");
1081
+ const toolName = getNamespacedToolName(record);
1082
+ if (!toolCallId || !toolName) {
1083
+ return void 0;
1084
+ }
1085
+ return {
1086
+ toolCallId,
1087
+ toolName,
1088
+ input: parseJsonString(record.arguments)
1089
+ };
1090
+ }
1091
+ if (record.type === "hosted_tool_call") {
1092
+ const toolCallId = getString(record, "id") ?? getString(record, "name");
1093
+ const toolName = getString(record, "name");
1094
+ if (!toolCallId || !toolName) {
1095
+ return void 0;
1096
+ }
1097
+ return {
1098
+ toolCallId,
1099
+ toolName,
1100
+ input: parseJsonString(record.arguments)
1101
+ };
1102
+ }
1103
+ if (record.type === "shell_call" || record.type === "apply_patch_call") {
1104
+ const toolCallId = getString(record, "callId");
1105
+ if (!toolCallId) {
1106
+ return void 0;
1107
+ }
1108
+ return {
1109
+ toolCallId,
1110
+ toolName: String(record.type),
1111
+ input: record.action ?? record.operation
1112
+ };
1113
+ }
1114
+ return void 0;
1115
+ }
1116
+ function getOpenAIToolOutput(rawItem, fallbackOutput) {
1117
+ const record = toRecord(rawItem);
1118
+ if (!record) {
1119
+ return void 0;
1120
+ }
1121
+ const toolCallId = getString(record, "callId") ?? getString(record, "id");
1122
+ if (!toolCallId) {
1123
+ return void 0;
1124
+ }
1125
+ return {
1126
+ toolCallId,
1127
+ output: record.output ?? fallbackOutput,
1128
+ isError: record.status === "failed" || record.status === "incomplete"
1129
+ };
1130
+ }
1131
+ function getNamespacedToolName(record) {
1132
+ const name = getString(record, "name");
1133
+ const namespace = getString(record, "namespace");
1134
+ if (!name) {
1135
+ return void 0;
1136
+ }
1137
+ return namespace ? `${namespace}.${name}` : name;
1138
+ }
1139
+ function getTextDelta(event) {
1140
+ if (event.type !== "raw_model_stream_event") {
1141
+ return "";
1142
+ }
1143
+ const data = toRecord(event.data);
1144
+ return data?.type === "output_text_delta" && typeof data.delta === "string" ? data.delta : "";
1145
+ }
1146
+ function parseJsonString(value) {
1147
+ if (typeof value !== "string") {
1148
+ return value;
1149
+ }
1150
+ try {
1151
+ return JSON.parse(value);
1152
+ } catch {
1153
+ return value;
1154
+ }
1155
+ }
1156
+ function getNumber(value) {
1157
+ return typeof value === "number" ? value : void 0;
1158
+ }
1159
+ function getString(record, key) {
1160
+ const value = record?.[key];
1161
+ return typeof value === "string" ? value : void 0;
1162
+ }
1163
+ function getObjectValue(value, key) {
1164
+ return toRecord(value)?.[key];
1165
+ }
1166
+ function toRecord(value) {
1167
+ return isRecord(value) ? value : void 0;
1168
+ }
1169
+ function isRecord(value) {
1170
+ return value !== null && typeof value === "object";
1171
+ }
1172
+
1173
+ export { OpenAISDKAgent };
1174
+ //# sourceMappingURL=index.js.map
1175
+ //# sourceMappingURL=index.js.map