@lostgradient/operative-openai 0.1.0 → 0.1.1

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/README.md CHANGED
@@ -15,6 +15,7 @@ Its source imports Operative only through `@lostgradient/operative/provider-kit`
15
15
  ## What It Exports
16
16
 
17
17
  - `createOpenAIProvider(options)` returns a `GenerateFunction` backed by the Chat Completions API. `createOpenAIProviderStream(options)` returns the streaming counterpart.
18
+ - `OpenAIOutputLimitError` is what both factories throw when a response stops at `finish_reason: "length"`. Its text is cut short and its tool calls may be, so nothing in it is returned or executed. It is a non-retryable `ProviderContractError` carrying the billed `usage` and the `responseId`. An agent run over this provider ends with `finishReason: 'error'`, and the run's `AgentRunError` holds it as `cause`. `isOpenAIOutputLimitError` recognizes it from another package copy.
18
19
  - `openaiProvider` is the `ProviderDefinition` a host registers by name. Its `OpenAIProviderConfiguration` is the shared `ProviderConfigurationBase` plus every factory option.
19
20
  - `openAIRows(options?)` is the provider's catalog rows, one per model and frozen. `options.freshness` stamps every row. `options.baseURL`, or an `OPENAI_BASE_URL` in the environment, makes the endpoint ambiguous: the rows then report `endpointAmbiguous`, no batch inference and an `unknown` availability, because the request may reach a server that is not OpenAI's. The OpenAI plugin passes them as its provider's `rows`.
20
21
  - `openAIPricingTable` is the list prices by model (`ModelPricing`), the source of each row's `pricing`; a host that prices a run passes it as `customPricing`.
package/dist/index.d.ts CHANGED
@@ -20,6 +20,7 @@ export { OPENAI_MODEL_ALIASES, OPENAI_REASONING_MODELS, openAIPricingTable, open
20
20
  export type { OpenAIRowsOptions } from "./openai-catalog.js";
21
21
  export { openaiProvider } from "./openai-definition.js";
22
22
  export type { OpenAIProviderConfiguration } from "./openai-definition.js";
23
+ export { OpenAIOutputLimitError, isOpenAIOutputLimitError } from "./openai-errors.js";
23
24
  export { mapOpenAIMessage, mergeAssembledField } from "./openai-parts.js";
24
25
  export type { OpenAIMessageMapping } from "./openai-parts.js";
25
26
  export { toOpenAIResponseFormat } from "./openai-response-format.js";
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ export { createOpenAIBatchClient } from "./batches/openai.js";
16
16
  export { createOpenAIEmbedder } from "./embeddings/openai.js";
17
17
  export { OPENAI_MODEL_ALIASES, OPENAI_REASONING_MODELS, openAIPricingTable, openAIRows, resolveOpenAIEffort, resolveOpenAIModel, } from "./openai-catalog.js";
18
18
  export { openaiProvider } from "./openai-definition.js";
19
+ export { OpenAIOutputLimitError, isOpenAIOutputLimitError } from "./openai-errors.js";
19
20
  export { mapOpenAIMessage, mergeAssembledField } from "./openai-parts.js";
20
21
  export { toOpenAIResponseFormat } from "./openai-response-format.js";
21
22
  export { toOpenAIToolChoice } from "./openai-tool-choice.js";
@@ -0,0 +1,27 @@
1
+ import { ProviderContractError, type GenerateResponse } from '@lostgradient/operative/provider-kit';
2
+ /** The Chat Completions finish reason for a response cut off at the output-token limit. */
3
+ export declare const OUTPUT_LIMIT_FINISH_REASON = "length";
4
+ /**
5
+ * Thrown when a Chat Completions response stopped at the output-token limit
6
+ * (`finish_reason: "length"`), whole or streamed. The response is discarded: its text is cut short
7
+ * and any tool call in it may carry cut-off arguments, so nothing in it is returned or executed. A
8
+ * run over this provider ends with `finishReason: 'error'` and this error.
9
+ *
10
+ * It is a {@link ProviderContractError} with the `truncated-stream` reason and keeps that class's
11
+ * `name`, so Operative's loop treats it as one wherever it checks, across package copies included:
12
+ * it is never retried, because the same request would stop at the same limit, and `usage`, the
13
+ * billed usage of the discarded response, still counts toward the run.
14
+ */
15
+ export declare class OpenAIOutputLimitError extends ProviderContractError {
16
+ /** The Chat Completions finish reason. */
17
+ readonly finishReason = "length";
18
+ /** The completion identifier of the discarded response, when reported. */
19
+ readonly responseId: string | undefined;
20
+ constructor(options: {
21
+ usage: GenerateResponse['usage'];
22
+ responseId?: string | undefined;
23
+ toolCallCount: number;
24
+ });
25
+ }
26
+ /** Structural guard for {@link OpenAIOutputLimitError}, for a copy loaded from another package instance. */
27
+ export declare function isOpenAIOutputLimitError(error: unknown): error is OpenAIOutputLimitError;
@@ -0,0 +1,43 @@
1
+ import { isProviderContractError, ProviderContractError, } from '@lostgradient/operative/provider-kit';
2
+ const PROVIDER = 'openai';
3
+ /** The Chat Completions finish reason for a response cut off at the output-token limit. */
4
+ export const OUTPUT_LIMIT_FINISH_REASON = 'length';
5
+ /**
6
+ * Thrown when a Chat Completions response stopped at the output-token limit
7
+ * (`finish_reason: "length"`), whole or streamed. The response is discarded: its text is cut short
8
+ * and any tool call in it may carry cut-off arguments, so nothing in it is returned or executed. A
9
+ * run over this provider ends with `finishReason: 'error'` and this error.
10
+ *
11
+ * It is a {@link ProviderContractError} with the `truncated-stream` reason and keeps that class's
12
+ * `name`, so Operative's loop treats it as one wherever it checks, across package copies included:
13
+ * it is never retried, because the same request would stop at the same limit, and `usage`, the
14
+ * billed usage of the discarded response, still counts toward the run.
15
+ */
16
+ export class OpenAIOutputLimitError extends ProviderContractError {
17
+ /** The Chat Completions finish reason. */
18
+ finishReason = OUTPUT_LIMIT_FINISH_REASON;
19
+ /** The completion identifier of the discarded response, when reported. */
20
+ responseId;
21
+ constructor(options) {
22
+ super({
23
+ provider: PROVIDER,
24
+ reason: 'truncated-stream',
25
+ blockType: options.toolCallCount > 0 ? 'tool_call' : 'text',
26
+ partIndex: 0,
27
+ usage: options.usage,
28
+ });
29
+ const discarded = options.toolCallCount > 0
30
+ ? `its text and ${options.toolCallCount} tool call(s) were discarded unexecuted`
31
+ : 'its text was discarded';
32
+ this.message = `[provider:${PROVIDER}] the response stopped at the output-token limit; ${discarded}.`;
33
+ this.responseId = options.responseId;
34
+ }
35
+ }
36
+ /** Structural guard for {@link OpenAIOutputLimitError}, for a copy loaded from another package instance. */
37
+ export function isOpenAIOutputLimitError(error) {
38
+ if (error instanceof OpenAIOutputLimitError)
39
+ return true;
40
+ return (isProviderContractError(error) &&
41
+ error.provider === PROVIDER &&
42
+ error['finishReason'] === OUTPUT_LIMIT_FINISH_REASON);
43
+ }
@@ -119,6 +119,8 @@ export interface OpenAIClient {
119
119
  * Minimal shape of an OpenAI Chat Completion response.
120
120
  */
121
121
  export interface OpenAIChatCompletion {
122
+ /** The completion identifier. */
123
+ id?: string | undefined;
122
124
  /** The generated choices; Operative reads the first. */
123
125
  choices: Array<{
124
126
  message: {
@@ -178,6 +180,8 @@ export interface OpenAIProviderOptions extends BaseProviderOptions {
178
180
  * A single chunk from the OpenAI Chat Completions streaming API.
179
181
  */
180
182
  export interface OpenAIChatCompletionChunk {
183
+ /** The completion identifier every chunk of one stream shares. */
184
+ id?: string | undefined;
181
185
  /** The choice deltas this chunk carries; Operative reads the first. */
182
186
  choices: Array<{
183
187
  delta: {
package/dist/openai.js CHANGED
@@ -2,6 +2,7 @@ import { parseOpenAIToolCalls } from 'armorer';
2
2
  import { toOpenAIMessagesGrouped } from 'conversationalist';
3
3
  import { concatenateTextParts, isProviderContractError, ProviderError, resolveCommonParameters, ToolCallParseError, withBackendDescriptors, withInputLineage, } from '@lostgradient/operative/provider-kit';
4
4
  import { openAIRows, resolveOpenAIEffort, resolveOpenAIModel } from "./openai-catalog.js";
5
+ import { OpenAIOutputLimitError, OUTPUT_LIMIT_FINISH_REASON } from "./openai-errors.js";
5
6
  import { mapOpenAIMessage, mergeAssembledField } from "./openai-parts.js";
6
7
  import { toOpenAIResponseFormat } from "./openai-response-format.js";
7
8
  import { toOpenAIToolChoice } from "./openai-tool-choice.js";
@@ -149,6 +150,15 @@ export function createOpenAIProvider(options) {
149
150
  const response = await client.chat.completions.create(params, requestOptions);
150
151
  const choice = response.choices[0];
151
152
  const usage = response.usage ? buildOpenAIUsage(response.usage) : undefined;
153
+ // A capped response is cut short: its text is partial and its tool calls may be, so none of
154
+ // it is mapped, returned for the loop to commit, or executed.
155
+ if (choice?.finish_reason === OUTPUT_LIMIT_FINISH_REASON) {
156
+ throw new OpenAIOutputLimitError({
157
+ usage,
158
+ responseId: response.id,
159
+ toolCallCount: choice.message.tool_calls?.length ?? 0,
160
+ });
161
+ }
152
162
  // Every message field is a part, metadata or a typed error: nothing the model returned vanishes.
153
163
  const mapped = mapOpenAIMessage(choice?.message ?? {}, usage);
154
164
  const content = concatenateTextParts(mapped.parts);
@@ -269,6 +279,8 @@ export function createOpenAIProviderStream(options) {
269
279
  // completion once the stream has drained, so the two modes cannot disagree.
270
280
  const assembled = {};
271
281
  let textSequence = 0;
282
+ let finishReason;
283
+ let responseId;
272
284
  // Track in-progress tool calls by index. `blockId` is the stable identity
273
285
  // carried on the live `stream:tool-call-*` events, so a host can
274
286
  // correlate a start with its deltas before the response closes.
@@ -276,8 +288,12 @@ export function createOpenAIProviderStream(options) {
276
288
  for await (const chunk of stream) {
277
289
  if (context.signal?.aborted)
278
290
  break;
291
+ if (chunk.id !== undefined)
292
+ responseId = chunk.id;
279
293
  const choice = chunk.choices[0];
280
294
  if (choice) {
295
+ if (choice.finish_reason)
296
+ finishReason = choice.finish_reason;
281
297
  // Accumulate text content
282
298
  if (choice.delta.content != null && choice.delta.content !== '') {
283
299
  if (streaming.reportPart !== undefined) {
@@ -384,6 +400,16 @@ export function createOpenAIProviderStream(options) {
384
400
  usage = buildOpenAIUsage(chunk.usage);
385
401
  }
386
402
  }
403
+ // A capped stream's text and tool-call arguments are cut short by the limit, not malformed:
404
+ // fail typed before any of it is parsed, returned or executed. The check waits for the drain
405
+ // because the billed usage arrives in a trailing chunk after the finish reason.
406
+ if (!context.signal?.aborted && finishReason === OUTPUT_LIMIT_FINISH_REASON) {
407
+ throw new OpenAIOutputLimitError({
408
+ usage,
409
+ responseId,
410
+ toolCallCount: pendingToolCalls.size,
411
+ });
412
+ }
387
413
  // Build completed tool calls. Skipped entirely when the caller aborted mid-stream:
388
414
  // any accumulated arguments fragment is caller-truncated, not model-malformed, so it
389
415
  // must never be parsed and misreported as a ToolCallParseError.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lostgradient/operative-openai",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The OpenAI model provider for Operative: a lazy-loading generate function for the Chat Completions API and any OpenAI-compatible endpoint, streaming, batches, the embedder, and the test doubles that exercise them.",
5
5
  "type": "module",
6
6
  "license": "MIT",