openai
Version:
The official TypeScript library for the OpenAI API
471 lines (442 loc) • 14 kB
text/typescript
// File generated from our OpenAPI spec by Castiron. See CONTRIBUTING.md for details.
import { APIResource } from '../../../../core/resource';
import { APIPromise } from '../../../../core/api-promise';
import { CursorPage, type CursorPageParams, PagePromise } from '../../../../core/pagination';
import { buildHeaders } from '../../../../internal/headers';
import { RequestOptions } from '../../../../internal/request-options';
import { path } from '../../../../internal/utils/path';
import { AgentResultArtifacts } from '../../../../lib/beta/agents/result-artifacts';
import type { AgentTurnResult } from '../../../../lib/beta/agents/agent-turn-result';
function resolveResourceRequestOptions(
options: RequestOptions | undefined,
buildOptions: (options: RequestOptions | undefined) => RequestOptions | Promise<RequestOptions>,
): Promise<RequestOptions> {
return Promise.resolve(options).then(buildOptions);
}
// Recognizable options across SDK runtime versions. Keep this independent of
// private RequestOptions fields so older handwritten runtimes still compile.
const normalizeRequestOptionsForQueryKeys = new Set([
'method',
'path',
'query',
'body',
'headers',
'maxRetries',
'stream',
'timeout',
'httpAgent',
'fetchOptions',
'signal',
'idempotencyKey',
'defaultBaseURL',
'__metadata',
'__binaryRequest',
'__binaryResponse',
'__streamClass',
'__streamMode',
'__security',
'__synthesizeEventData',
]);
function normalizeRequestOptionsForQuery(
value: unknown,
queryKeys: ReadonlyArray<string>,
options: RequestOptions | undefined,
):
| ({
[K in 'headers' | 'maxRetries' | 'timeout' | 'signal' | 'idempotencyKey' | 'query']?: RequestOptions[K];
} & {
[
K in
| 'method'
| 'path'
| 'body'
| 'stream'
| 'httpAgent'
| 'fetchOptions'
| 'defaultBaseURL'
| '__metadata'
| '__binaryRequest'
| '__binaryResponse'
| '__streamClass'
| '__streamMode'
| '__security'
| '__synthesizeEventData'
]?: never;
})
| undefined {
if (typeof value !== 'object' || value === null) return undefined;
// Optional never fields can still be explicitly undefined unless consumers
// enable exactOptionalPropertyTypes. Snapshot data without invoking getters.
const entries = Object.entries(Object.getOwnPropertyDescriptors(value)).filter(
([, descriptor]) => descriptor.enumerable && (!('value' in descriptor) || descriptor.value !== undefined),
);
const keys = entries.map(([key]) => key);
const requestOnly = keys.some(
(key) => normalizeRequestOptionsForQueryKeys.has(key) && !queryKeys.includes(key),
);
if (!requestOnly) return undefined;
// Declared query fields, including stream, must use the query argument.
// Mixing them with request-only options is ambiguous and could change the return type.
if (
options !== undefined ||
keys.some((key) => !normalizeRequestOptionsForQueryKeys.has(key) || queryKeys.includes(key))
) {
throw new TypeError('Query parameters and request options must be passed as separate arguments.');
}
// The query position must not gain authority to change the request destination
// or transport. Those overrides require the explicit request options argument.
if (
keys.some(
(key) => !['headers', 'maxRetries', 'timeout', 'signal', 'idempotencyKey', 'query'].includes(key),
)
) {
throw new TypeError('Pass transport overrides in the explicit request options argument.');
}
// Copy only the validated fields. Spreading value would reintroduce undefined
// transport overrides, and deleting them would mutate the caller's object.
return Object.fromEntries(
entries.map(([key, descriptor]) => {
if ('value' in descriptor) return [key, descriptor.value];
return [key, descriptor.get ? Reflect.apply(descriptor.get, value, []) : undefined];
}),
) as {
[K in 'headers' | 'maxRetries' | 'timeout' | 'signal' | 'idempotencyKey' | 'query']?: RequestOptions[K];
} & {
[
K in
| 'method'
| 'path'
| 'body'
| 'stream'
| 'httpAgent'
| 'fetchOptions'
| 'defaultBaseURL'
| '__metadata'
| '__binaryRequest'
| '__binaryResponse'
| '__streamClass'
| '__streamMode'
| '__security'
| '__synthesizeEventData'
]?: never;
};
}
export class Artifacts extends APIResource {
/**
* Retrieves immutable metadata for one durable session artifact. See
* [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
*
* @example
* ```ts
* const sessionArtifact =
* await client.beta.agents.sessions.artifacts.retrieve(
* 'artifact_id',
* { session_id: 'session_id' },
* );
* ```
*/
retrieve(
artifactID: string,
params: ArtifactRetrieveParams,
options?: RequestOptions,
): APIPromise<SessionArtifact> {
const { session_id } = params;
return this._client.get(
path`/agents/sessions/${session_id}/artifacts/${artifactID}`,
resolveResourceRequestOptions(options, (options) => ({
...options,
headers: buildHeaders([{ 'OpenAI-Beta': 'agents=v1' }, options?.headers]),
__security: { bearerAuth: true },
})),
);
}
/**
* Lists immutable artifacts published by completed hosted session turns. See
* [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const sessionArtifact of client.beta.agents.sessions.artifacts.list(
* 'session_id',
* )) {
* // ...
* }
* ```
*/
list(
sessionID: string,
query?:
| (ArtifactListParams &
(
| {
[
K in
| 'method'
| 'path'
| 'query'
| 'body'
| 'headers'
| 'maxRetries'
| 'stream'
| 'timeout'
| 'httpAgent'
| 'fetchOptions'
| 'signal'
| 'idempotencyKey'
| 'defaultBaseURL'
| '__metadata'
| '__binaryRequest'
| '__binaryResponse'
| '__streamClass'
| '__streamMode'
| '__security'
| '__synthesizeEventData'
]?: never;
}
| null
| undefined
))
| null
| undefined,
options?: RequestOptions,
): PagePromise<SessionArtifactsPage, SessionArtifact>;
list(
sessionID: string,
options?: {
[K in 'headers' | 'maxRetries' | 'timeout' | 'signal' | 'idempotencyKey' | 'query']?: RequestOptions[K];
} & {
[
K in
| 'method'
| 'path'
| 'body'
| 'stream'
| 'httpAgent'
| 'fetchOptions'
| 'defaultBaseURL'
| '__metadata'
| '__binaryRequest'
| '__binaryResponse'
| '__streamClass'
| '__streamMode'
| '__security'
| '__synthesizeEventData'
]?: never;
},
): PagePromise<SessionArtifactsPage, SessionArtifact>;
list(
sessionID: string,
query:
| ArtifactListParams
| ({
[
K in 'headers' | 'maxRetries' | 'timeout' | 'signal' | 'idempotencyKey' | 'query'
]?: RequestOptions[K];
} & {
[
K in
| 'method'
| 'path'
| 'body'
| 'stream'
| 'httpAgent'
| 'fetchOptions'
| 'defaultBaseURL'
| '__metadata'
| '__binaryRequest'
| '__binaryResponse'
| '__streamClass'
| '__streamMode'
| '__security'
| '__synthesizeEventData'
]?: never;
})
| null
| undefined = {},
options?: RequestOptions,
): PagePromise<SessionArtifactsPage, SessionArtifact> {
const normalizeRequestOptionsForQueryOptions = normalizeRequestOptionsForQuery(
query,
['after', 'environment_id', 'limit', 'order'],
options,
);
if (normalizeRequestOptionsForQueryOptions !== undefined) {
options = normalizeRequestOptionsForQueryOptions;
query = {};
}
query = query as ArtifactListParams | null | undefined;
return this._client.getAPIList(
path`/agents/sessions/${sessionID}/artifacts`,
CursorPage<SessionArtifact>,
resolveResourceRequestOptions(options, (options) => ({
query,
...options,
headers: buildHeaders([{ 'OpenAI-Beta': 'agents=v1' }, options?.headers]),
__security: { bearerAuth: true },
})),
);
}
/**
* Deletes an immutable session artifact without deleting its live environment file
* or original Files API object. See
* [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
*
* @example
* ```ts
* const sessionArtifactDeleted =
* await client.beta.agents.sessions.artifacts.delete(
* 'artifact_id',
* { session_id: 'session_id' },
* );
* ```
*/
delete(
artifactID: string,
params: ArtifactDeleteParams,
options?: RequestOptions,
): APIPromise<SessionArtifactDeleted> {
const { session_id } = params;
return this._client.delete(
path`/agents/sessions/${session_id}/artifacts/${artifactID}`,
resolveResourceRequestOptions(options, (options) => ({
...options,
headers: buildHeaders([{ 'OpenAI-Beta': 'agents=v1' }, options?.headers]),
__security: { bearerAuth: true },
})),
);
}
/**
* Downloads immutable session artifact bytes after the execution environment
* expires. See
* [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
*
* @example
* ```ts
* const response =
* await client.beta.agents.sessions.artifacts.content(
* 'artifact_id',
* { session_id: 'session_id' },
* );
*
* const content = await response.blob();
* console.log(content);
* ```
*/
content(artifactID: string, params: ArtifactContentParams, options?: RequestOptions): APIPromise<Response> {
const { session_id } = params;
return this._client.get(
path`/agents/sessions/${session_id}/artifacts/${artifactID}/content`,
resolveResourceRequestOptions(options, (options) => ({
...options,
headers: buildHeaders([
{ 'OpenAI-Beta': 'agents=v1', Accept: 'application/octet-stream' },
options?.headers,
]),
__security: { bearerAuth: true },
__binaryResponse: true,
})),
);
}
/** Beta: bind artifact lookup and downloads to a completed result's exact session and turn. */
forResult(result: AgentTurnResult): AgentResultArtifacts {
return new AgentResultArtifacts(this, result);
}
}
export type SessionArtifactsPage = CursorPage<SessionArtifact>;
/**
* An immutable file published by a completed hosted session turn.
*/
export interface SessionArtifact {
/**
* The immutable artifact ID.
*/
id: string;
/**
* The Unix timestamp, in seconds, when the artifact was published.
*/
created_at: number;
/**
* The ID of the environment that produced the artifact.
*/
environment_id: string;
/**
* The object type. Always `agent.session.artifact`.
*/
object: 'agent.session.artifact';
/**
* The original absolute file path in the execution environment.
*/
path: string;
/**
* The ID of the session that owns the artifact.
*/
session_id: string;
/**
* The immutable artifact size in bytes.
*/
size_bytes: number;
/**
* The ID of the completed turn that published the artifact.
*/
turn_id: string;
}
/**
* Confirmation that an immutable session artifact was deleted.
*/
export interface SessionArtifactDeleted {
/**
* The ID of the deleted session artifact.
*/
id: string;
/**
* Whether the session artifact was deleted. Always `true`.
*/
deleted: boolean;
/**
* The object type. Always `agent.session.artifact.deleted`.
*/
object: 'agent.session.artifact.deleted';
}
export interface ArtifactRetrieveParams {
/**
* The ID of the session that owns the artifact.
*/
session_id: string;
}
export interface ArtifactListParams extends CursorPageParams {
/**
* Restrict the listing to artifacts produced by this environment.
*/
environment_id?: string | null;
/**
* The order in which resources are returned. Defaults to `desc`.
*
* - `asc` - Returns resources in ascending order.
* - `desc` - Returns resources in descending order.
*/
order?: 'asc' | 'desc';
}
export interface ArtifactDeleteParams {
/**
* The ID of the session that owns the artifact.
*/
session_id: string;
}
export interface ArtifactContentParams {
/**
* The ID of the session that owns the artifact.
*/
session_id: string;
}
export declare namespace Artifacts {
export {
type SessionArtifact as SessionArtifact,
type SessionArtifactDeleted as SessionArtifactDeleted,
type SessionArtifactsPage as SessionArtifactsPage,
type ArtifactRetrieveParams as ArtifactRetrieveParams,
type ArtifactListParams as ArtifactListParams,
type ArtifactDeleteParams as ArtifactDeleteParams,
type ArtifactContentParams as ArtifactContentParams,
};
}