UNPKG

@mastra/core

Version:

Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

304 lines • 12.4 kB
import { ReadableStream } from 'node:stream/web'; import type { MessageList, MastraDBMessage } from '../../agent/message-list/index.js'; import { MastraBase } from '../../base.js'; import type { ScorerRunInputForAgent, ScorerRunOutputForAgent } from '../../evals/index.js'; import { ProcessorRunner } from '../../processors/runner.js'; import type { WorkflowRunStatus } from '../../workflows/index.js'; import type { ConsumeStreamOptions } from '../aisdk/v5/compat/index.js'; import type { ChunkType, LanguageModelUsage, LLMStepResult, MastraModelOutputOptions, ProviderMetadata, StreamTransport, StepTripwireData, ToolCallChunk } from '../types.js'; /** * Helper function to create a destructurable version of MastraModelOutput. * This wraps the output to ensure properties maintain their context when destructured. */ export declare function createDestructurableOutput<OUTPUT = undefined>(output: MastraModelOutput<OUTPUT>): MastraModelOutput<OUTPUT>; type PromiseResults<OUTPUT = undefined> = Pick<LLMStepResult<OUTPUT>, 'text' | 'reasoning' | 'sources' | 'files' | 'toolCalls' | 'toolResults' | 'content' | 'usage' | 'warnings' | 'providerMetadata' | 'response' | 'request'> & { suspendPayload: any; resumeSchema: any; object: OUTPUT; reasoningText: string | undefined; totalUsage: LLMStepResult<OUTPUT>['usage']; steps: LLMStepResult<OUTPUT>[]; finishReason: LLMStepResult<OUTPUT>['finishReason']; }; /** * The complete output returned by `getFullOutput()`. */ export type FullOutput<OUTPUT = undefined> = { /** The text output from all steps, excluding rejected responses */ text: string; /** Token usage for the last step */ usage: PromiseResults<OUTPUT>['usage']; /** All LLM steps executed during the stream */ steps: LLMStepResult<OUTPUT>[]; /** The reason the stream finished */ finishReason: PromiseResults<OUTPUT>['finishReason']; /** Any warnings from the model */ warnings: PromiseResults<OUTPUT>['warnings']; /** Provider-specific metadata */ providerMetadata: PromiseResults<OUTPUT>['providerMetadata']; /** The request that was sent to model */ request: PromiseResults<OUTPUT>['request']; /** Reasoning details from the model */ reasoning: PromiseResults<OUTPUT>['reasoning']; /** Combined reasoning text */ reasoningText: string | undefined; /** Tool calls made during execution */ toolCalls: PromiseResults<OUTPUT>['toolCalls']; /** Results from tool executions */ toolResults: PromiseResults<OUTPUT>['toolResults']; /** Sources referenced by model */ sources: PromiseResults<OUTPUT>['sources']; /** Files generated by the model */ files: PromiseResults<OUTPUT>['files']; /** Response metadata from the model */ response: PromiseResults<OUTPUT>['response']; /** Total token usage across all steps */ totalUsage: PromiseResults<OUTPUT>['totalUsage']; /** The structured object output (when using structured output) */ object: OUTPUT; /** Error if the stream failed */ error: Error | undefined; /** Tripwire data if content was blocked */ tripwire: StepTripwireData | undefined; /** Scoring data for evals (when returnScorerData is enabled) */ scoringData?: { input: Omit<ScorerRunInputForAgent, 'runId'>; output: ScorerRunOutputForAgent; }; /** Trace ID for this execution. */ traceId: string | undefined; /** Root span ID for this execution, identifying the top-level span in the trace. */ spanId: string | undefined; /** Run ID for this execution */ runId: string | undefined; /** Payload for resuming suspended tool calls */ suspendPayload: any; /** Resume schema of suspended step if available */ resumeSchema?: any; /** All messages from this execution (input + memory history + response) */ messages: MastraDBMessage[]; /** Only messages loaded from memory (conversation history) */ rememberedMessages: MastraDBMessage[]; }; export declare class MastraModelOutput<OUTPUT = undefined> extends MastraBase { #private; /** * Unique identifier for this execution run. */ runId: string; /** * The processor runner for this stream. */ processorRunner?: ProcessorRunner; /** * The message list for this stream. */ messageList: MessageList; /** * Trace ID for this execution. */ traceId?: string; /** * Root span ID for this execution, identifying the top-level span in the trace. */ spanId?: string; messageId: string; constructor({ model: _model, stream, messageList, options, messageId, initialState, }: { model: { modelId: string | undefined; provider: string | undefined; version: 'v2' | 'v3'; }; stream: ReadableStream<ChunkType<OUTPUT>>; messageList: MessageList; options: MastraModelOutputOptions<OUTPUT>; messageId: string; initialState?: any; }); private resolvePromise; private resolvePromises; /** * Resolves to the complete text response after streaming completes. */ get text(): Promise<string>; /** * Resolves to reasoning parts array for models that support reasoning. */ get reasoning(): Promise<import("..").ReasoningChunk[]>; /** * Resolves to complete reasoning text for models that support reasoning. */ get reasoningText(): Promise<string | undefined>; get sources(): Promise<import("..").SourceChunk[]>; get files(): Promise<import("..").FileChunk[]>; get steps(): Promise<LLMStepResult<OUTPUT>[]>; get suspendPayload(): Promise<any>; get resumeSchema(): Promise<any>; /** * Stream of all chunks. Provides complete control over stream processing. */ get fullStream(): ReadableStream<ChunkType<OUTPUT>>; /** * Resolves to the reason generation finished. */ get finishReason(): Promise<string | undefined>; /** * Resolves to array of all tool calls made during execution. */ get toolCalls(): Promise<ToolCallChunk[]>; /** * Resolves to array of all tool execution results. */ get toolResults(): Promise<import("..").ToolResultChunk[]>; /** * Resolves to token usage statistics including inputTokens, outputTokens, and totalTokens. */ get usage(): Promise<LanguageModelUsage>; /** * Resolves to array of all warnings generated during execution. */ get warnings(): Promise<import("@ai-sdk/provider-v5").LanguageModelV2CallWarning[]>; /** * Resolves to provider metadata generated during execution. */ get providerMetadata(): Promise<ProviderMetadata | undefined>; /** * Resolves to the complete response from the model. */ get response(): Promise<{ [key: string]: unknown; headers?: Record<string, string>; messages?: import("../../_types/@internal_ai-sdk-v5/dist/index.js").StepResult<import("../../_types/@internal_ai-sdk-v5/dist/index.js").ToolSet>["response"]["messages"]; dbMessages?: MastraDBMessage[]; uiMessages?: import("../../_types/@internal_ai-sdk-v5/dist/index.js").UIMessage<[OUTPUT] extends [undefined] ? undefined : { structuredOutput?: OUTPUT | undefined; } & Record<string, unknown>, import("../../_types/@internal_ai-sdk-v5/dist/index.js").UIDataTypes, import("../../_types/@internal_ai-sdk-v5/dist/index.js").UITools>[] | undefined; id?: string; timestamp?: Date; modelId?: string; }>; /** * Resolves to the complete request sent to the model. */ get request(): Promise<{ body?: unknown; }>; /** * Transport handle for the current stream (when available). */ get transport(): StreamTransport | undefined; /** * Resolves to an error if an error occurred during streaming. */ get error(): Error | undefined; updateUsageCount(usage: Partial<LanguageModelUsage>): void; populateUsageCount(usage: Partial<LanguageModelUsage>): void; consumeStream(options?: ConsumeStreamOptions): Promise<void>; /** * Returns complete output including text, usage, tool calls, and all metadata. */ getFullOutput(): Promise<FullOutput<OUTPUT>>; /** * Tripwire data if the stream was aborted due to an output processor blocking the content. * Returns undefined if no tripwire was triggered. */ get tripwire(): StepTripwireData | undefined; /** * The total usage of the stream. */ get totalUsage(): Promise<LanguageModelUsage>; get content(): Promise<LLMStepResult['content']>; /** * Stream of valid JSON chunks. The final JSON result is validated against the output schema when the stream ends. * * @example * ```typescript * const stream = await agent.stream("Extract data", { * structuredOutput: { * schema: z.object({ name: z.string(), age: z.number() }), * model: 'gpt-4o-mini' // optional to use a model for structuring json output * } * }); * // partial json chunks * for await (const data of stream.objectStream) { * console.log(data); // { name: 'John' }, { name: 'John', age: 30 } * } * ``` */ get objectStream(): ReadableStream<Partial<OUTPUT>>; /** * Stream of individual array elements when output schema is an array type. */ get elementStream(): ReadableStream<OUTPUT extends Array<infer T> ? T : never>; /** * Stream of only text content, filtering out metadata and other chunk types. */ get textStream(): ReadableStream<string>; /** * Resolves to the complete object response from the model. Validated against the 'output' schema when the stream ends. * * @example * ```typescript * const stream = await agent.stream("Extract data", { * structuredOutput: { * schema: z.object({ name: z.string(), age: z.number() }), * model: 'gpt-4o-mini' // optionally use a model for structuring json output * } * }); * // final validated json * const data = await stream.object // { name: 'John', age: 30 } * ``` */ get object(): Promise<OUTPUT>; /** @internal */ _getImmediateToolCalls(): ToolCallChunk[]; /** @internal */ _getImmediateToolResults(): import("..").ToolResultChunk[]; /** @internal */ _getImmediateText(): string; /** @internal */ _getImmediateObject(): OUTPUT | undefined; /** @internal */ _getImmediateUsage(): LanguageModelUsage; /** @internal */ _getImmediateWarnings(): import("@ai-sdk/provider-v5").LanguageModelV2CallWarning[]; /** @internal */ _getImmediateFinishReason(): string | undefined; /** @internal */ _getBaseStream(): ReadableStream<ChunkType<OUTPUT>>; /** @internal */ _waitUntilFinished(): Promise<void>; get status(): WorkflowRunStatus; serializeState(): { status: WorkflowRunStatus; bufferedSteps: LLMStepResult<OUTPUT>[]; bufferedReasoningDetails: Record<string, import("..").ReasoningChunk>; bufferedByStep: LLMStepResult<OUTPUT>; bufferedText: string[]; bufferedTextChunks: Record<string, string[]>; bufferedSources: import("..").SourceChunk[]; bufferedReasoning: import("..").ReasoningChunk[]; bufferedFiles: import("..").FileChunk[]; toolCallArgsDeltas: Record<string, string[]>; toolCallDeltaIdNameMap: Record<string, string>; toolCallStreamingMeta: Record<string, { toolName: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; dynamic?: boolean; }>; toolCalls: ToolCallChunk[]; toolResults: import("..").ToolResultChunk[]; warnings: import("@ai-sdk/provider-v5").LanguageModelV2CallWarning[]; finishReason: string | undefined; request: { body?: unknown; }; usageCount: LanguageModelUsage; tripwire: StepTripwireData | undefined; messageList: import("../../agent/message-list/state").SerializedMessageListState; }; deserializeState(state: any): void; } export {}; //# sourceMappingURL=output.d.ts.map