@openai/agents-core
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
287 lines • 8.99 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StreamedRunResult = exports.RunResult = void 0;
const _shims_1 = require("@openai/agents-core/_shims");
const run_1 = require("./run.js");
const logger_1 = __importDefault(require("./logger.js"));
const protocol_1 = require("./types/protocol.js");
class RunResultBase {
state;
constructor(state) {
this.state = state;
}
/**
* The history of the agent run. This includes the input items and the new items generated during
* the agent run.
*
* This can be used as inputs for the next agent run.
*/
get history() {
return (0, run_1.getTurnInput)(this.input, this.newItems);
}
/**
* The new items generated during the agent run. These include things like new messages, tool
* calls and their outputs, etc.
*
* It does not include information about the agents and instead represents the model data.
*
* For the output including the agents, use the `newItems` property.
*/
get output() {
return (0, run_1.getTurnInput)([], this.newItems);
}
/**
* A copy of the original input items.
*/
get input() {
return this.state._originalInput;
}
/**
* The run items generated during the agent run. This associates the model data with the agents.
*
* For the model data that can be used as inputs for the next agent run, use the `output` property.
*/
get newItems() {
return this.state._generatedItems;
}
/**
* The raw LLM responses generated by the model during the agent run.
*/
get rawResponses() {
return this.state._modelResponses;
}
/**
* The last response ID generated by the model during the agent run.
*/
get lastResponseId() {
const responses = this.rawResponses;
return responses && responses.length > 0
? responses[responses.length - 1].responseId
: undefined;
}
/**
* The last agent that was run
*/
get lastAgent() {
return this.state._currentAgent;
}
/**
* Guardrail results for the input messages.
*/
get inputGuardrailResults() {
return this.state._inputGuardrailResults;
}
/**
* Guardrail results for the final output of the agent.
*/
get outputGuardrailResults() {
return this.state._outputGuardrailResults;
}
/**
* Any interruptions that occurred during the agent run for example for tool approvals.
*/
get interruptions() {
if (this.state._currentStep?.type === 'next_step_interruption') {
return this.state._currentStep.data.interruptions;
}
return [];
}
/**
* The final output of the agent. If the output type was set to anything other than `text`,
* this will be parsed either as JSON or using the Zod schema you provided.
*/
get finalOutput() {
if (this.state._currentStep?.type === 'next_step_final_output') {
return this.state._currentAgent.processFinalOutput(this.state._currentStep.output);
}
logger_1.default.warn('Accessed finalOutput before agent run is completed.');
return undefined;
}
}
/**
* The result of an agent run.
*/
class RunResult extends RunResultBase {
constructor(state) {
super(state);
}
}
exports.RunResult = RunResult;
/**
* The result of an agent run in streaming mode.
*/
class StreamedRunResult extends RunResultBase {
/**
* The current agent that is running
*/
get currentAgent() {
return this.lastAgent;
}
/**
* The current turn number
*/
currentTurn = 0;
/**
* The maximum number of turns that can be run
*/
maxTurns;
#error = null;
#signal;
#readableController;
#readableStream;
#completedPromise;
#completedPromiseResolve;
#completedPromiseReject;
#cancelled = false;
#streamLoopPromise;
constructor(result = {}) {
super(result.state);
this.#signal = result.signal;
this.#readableStream = new _shims_1.ReadableStream({
start: (controller) => {
this.#readableController = controller;
},
cancel: () => {
this.#cancelled = true;
},
});
this.#completedPromise = new Promise((resolve, reject) => {
this.#completedPromiseResolve = resolve;
this.#completedPromiseReject = reject;
});
if (this.#signal) {
const handleAbort = () => {
if (this.#cancelled) {
return;
}
this.#cancelled = true;
const controller = this.#readableController;
this.#readableController = undefined;
if (this.#readableStream.locked) {
if (controller) {
try {
controller.close();
}
catch (err) {
logger_1.default.debug(`Failed to close readable stream on abort: ${err}`);
}
}
}
else {
void this.#readableStream
.cancel(this.#signal?.reason)
.catch((err) => {
logger_1.default.debug(`Failed to cancel readable stream on abort: ${err}`);
});
}
this.#completedPromiseResolve?.();
};
if (this.#signal.aborted) {
handleAbort();
}
else {
this.#signal.addEventListener('abort', handleAbort, { once: true });
}
}
}
/**
* @internal
* Adds an item to the stream of output items
*/
_addItem(item) {
if (!this.cancelled) {
this.#readableController?.enqueue(item);
}
}
/**
* @internal
* Indicates that the stream has been completed
*/
_done() {
if (!this.cancelled && this.#readableController) {
this.#readableController.close();
this.#readableController = undefined;
this.#completedPromiseResolve?.();
}
}
/**
* @internal
* Handles an error in the stream loop.
*/
_raiseError(err) {
if (!this.cancelled && this.#readableController) {
this.#readableController.error(err);
this.#readableController = undefined;
}
this.#error = err;
this.#completedPromiseReject?.(err);
this.#completedPromise.catch((e) => {
logger_1.default.debug(`Resulted in an error: ${e}`);
});
}
/**
* Returns true if the stream has been cancelled.
*/
get cancelled() {
return this.#cancelled;
}
/**
* Returns the underlying readable stream.
* @returns A readable stream of the agent run.
*/
toStream() {
return this.#readableStream;
}
/**
* Await this promise to ensure that the stream has been completed if you are not consuming the
* stream directly.
*/
get completed() {
return this.#completedPromise;
}
/**
* Error thrown during the run, if any.
*/
get error() {
return this.#error;
}
toTextStream(options = {}) {
const stream = this.#readableStream.pipeThrough(new _shims_1.TransformStream({
transform(event, controller) {
if (event.type === 'raw_model_stream_event' &&
event.data.type === 'output_text_delta') {
const item = protocol_1.StreamEventTextStream.parse(event.data);
controller.enqueue(item.delta);
}
},
}));
if (options.compatibleWithNodeStreams) {
return _shims_1.Readable.fromWeb(stream);
}
return stream;
}
[Symbol.asyncIterator]() {
return this.#readableStream[Symbol.asyncIterator]();
}
/**
* @internal
* Sets the stream loop promise that completes when the internal stream loop finishes.
* This is used to defer trace end until all agent work is complete.
*/
_setStreamLoopPromise(promise) {
this.#streamLoopPromise = promise;
}
/**
* @internal
* Returns a promise that resolves when the stream loop completes.
* This is used by the tracing system to wait for all agent work before ending the trace.
*/
_getStreamLoopPromise() {
return this.#streamLoopPromise;
}
}
exports.StreamedRunResult = StreamedRunResult;
//# sourceMappingURL=result.js.map