@lostgradient/operative-openai 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024–2026 Steve Kinney
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,175 @@
1
- # Temporary Holding Version
1
+ # Operative OpenAI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This package runs on Cloudflare Workers with `nodejs_compat`. Supply an OpenAI client through the provider configuration.
4
+
5
+ `@lostgradient/operative-openai` is the OpenAI model provider for [`@lostgradient/operative`](../operative/README.md). It holds the Chat Completions generate function and its streaming sibling, the batch client, the embedder, the stream normalizer, and the structural client types a test double or a proxy can satisfy. Because the factories speak the Chat Completions shape, they also work against any OpenAI-compatible endpoint (LM Studio, Ollama, Groq, and the like) through `baseURL`. Operative's loop is provider-neutral; the shared model, effort, and catalog tables this package resolves against stay in Operative and reach it through `@lostgradient/operative/provider-kit`.
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ npm install @lostgradient/operative-openai
11
+ ```
12
+
13
+ Its source imports Operative only through `@lostgradient/operative/provider-kit`. Its tests also use `@lostgradient/operative` and `@lostgradient/operative/provider-testing`.
14
+
15
+ ## What It Exports
16
+
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.
19
+ - `openaiProvider` is the `ProviderDefinition` a host registers by name. Its `OpenAIProviderConfiguration` is the shared `ProviderConfigurationBase` plus every factory option.
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`.
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`.
22
+ - `resolveOpenAIModel(model)` resolves an alias in `OPENAI_MODEL_ALIASES` to its model and passes any other name through. `resolveOpenAIEffort(tier, model)` clamps an effort tier to `high` on a reasoning model (`OPENAI_REASONING_MODELS`) and returns `undefined` for any other.
23
+ - `createOpenAIBatchClient(options)` wraps `client.batches`.
24
+ - `createOpenAIEmbedder(options)` returns an `Embedder` backed by the Embeddings API.
25
+ - `normalizeOpenAIStream` turns a stream of Chat Completions chunks into Operative stream events.
26
+ - The structural client types (`OpenAIClient`, `OpenAIStreamingClient`, `OpenAIBatchClient`, `OpenAIEmbeddingClient`) and the request, response, and chunk types they use.
27
+ - The response-format and tool-choice mappers (`toOpenAIResponseFormat`, `toOpenAIToolChoice`) and the message mapper (`mapOpenAIMessage`) the factories are made of.
28
+ - From `@lostgradient/operative-openai/testing`: canned responses and stream chunks, and `createMockOpenAIClient` and `createMockOpenAIStreamingClient`, which record the requests they receive.
29
+
30
+ ## Registering the provider
31
+
32
+ A host that picks a model provider by name holds a `ProviderDefinition`: a `name` and two methods, `generate(configuration, pluginConfiguration)` and `stream(configuration, pluginConfiguration)`. The second argument is the validated plugin configuration; pass `{}` when the provider has no plugin-level configuration. `openaiProvider` passes both objects to `createOpenAIProvider` and `createOpenAIProviderStream`, so a field the shared `ProviderConfigurationBase` does not name, such as an injected `client`, still reaches the factory:
33
+
34
+ ```typescript
35
+ import type { ProviderDefinition } from '@lostgradient/operative';
36
+ import { openaiProvider } from '@lostgradient/operative-openai';
37
+
38
+ // A host registers one definition per provider package it uses.
39
+ const definitions: ProviderDefinition[] = [openaiProvider];
40
+
41
+ const generate = definitions
42
+ .find((definition) => definition.name === 'openai')
43
+ ?.generate?.({ provider: 'openai', model: 'gpt-4o' }, {});
44
+ ```
45
+
46
+ `stream` returns a streaming generate function, which a host wraps with `withEnhancedStreaming` to get an ordinary one. An injected `client` has to serve both methods, because one configuration feeds both; to inject a client that serves only one, call the factory directly.
47
+
48
+ ## Calling the factory directly
49
+
50
+ ```typescript
51
+ import { createOpenAIProvider } from '@lostgradient/operative-openai';
52
+
53
+ const generate = createOpenAIProvider({ model: 'gpt-4o' });
54
+ ```
55
+
56
+ `apiKey` is optional: the SDK falls back to the `OPENAI_API_KEY` environment variable. The model name goes through Operative's alias registry, so a short alias resolves to the model it names.
57
+
58
+ ## Providers behind a proxy
59
+
60
+ `createOpenAIProvider` and `createOpenAIProviderStream` accept a `baseURL` override and an arbitrary `apiKey` string with no shape validation—both pass straight to the SDK client, so a credential-injecting proxy can sit in front of OpenAI and swap in the real key server-side. The same override points the factories at an OpenAI-compatible local server:
61
+
62
+ ```typescript
63
+ import { createOpenAIProvider } from '@lostgradient/operative-openai';
64
+
65
+ const generate = createOpenAIProvider({
66
+ model: 'gpt-4o',
67
+ apiKey: 'placeholder-token', // never a real key—the proxy injects it
68
+ baseURL: 'https://llm-proxy.internal.example.com/v1',
69
+ });
70
+ ```
71
+
72
+ Each generate call issues one `POST` to `/chat/completions` (streaming uses the same path), authenticated with an `authorization: Bearer <token>` header. `test/proxy-contract.test.ts` runs both factories through a real SDK client against a local `Bun.serve` mock and asserts that exact `(method, path)` set over a multi-step run. Use it to build a proxy allowlist. The provider issues no token-counting, models-list, or beta/experimental endpoint call as part of a normal generate step.
73
+
74
+ ## Per-run request metadata
75
+
76
+ `requestMetadata` (a `Record<string, string>`) attaches to every generate request of a run and is mapped to the Chat Completions `metadata` field, a native string-keyed map of up to 16 keys:
77
+
78
+ ```typescript
79
+ import { createOpenAIProvider } from '@lostgradient/operative-openai';
80
+
81
+ const generate = createOpenAIProvider({
82
+ model: 'gpt-4o',
83
+ requestMetadata: { requestId: 'run-42', tenant: 'acme' },
84
+ });
85
+ ```
86
+
87
+ ## Live tool-call streaming
88
+
89
+ By default a host reconstructs tool-call events from the resolved `GenerateResponse`, so they land after the provider response has closed. `withEnhancedStreaming`'s `liveToolCalls` option changes that. The OpenAI streaming adapter pushes through `StreamingHandle.report` as the provider emits, from `delta.tool_calls`, so `stream:tool-call-start` and `stream:tool-call-delta` reach a host while the response is still open:
90
+
91
+ ```typescript
92
+ import { TypedEventTarget } from '@lostgradient/lifecycle';
93
+ import { withEnhancedStreaming } from '@lostgradient/operative';
94
+ import type { StreamEventMap } from '@lostgradient/operative';
95
+ import { createOpenAIProviderStream } from '@lostgradient/operative-openai';
96
+
97
+ const eventTarget = new TypedEventTarget<StreamEventMap>();
98
+ const provider = createOpenAIProviderStream({ model: 'gpt-4o', apiKey: '...' });
99
+
100
+ const generate = withEnhancedStreaming(provider, {
101
+ eventTarget,
102
+ liveToolCalls: true,
103
+ });
104
+ ```
105
+
106
+ Operative's README lists the rest of what to know before turning it on.
107
+
108
+ ## Batches
109
+
110
+ `createOpenAIBatchClient` wraps `client.batches` with a lazily constructed client and `ProviderError` normalization. OpenAI takes no inline requests: upload a JSONL file with purpose `batch` through `client.files`, then name it by `input_file_id`. Results come back as an uploaded file, so a caller reads `output_file_id` through `client.files` rather than off the batch:
111
+
112
+ ```typescript
113
+ import { createOpenAIBatchClient } from '@lostgradient/operative-openai';
114
+
115
+ const batches = createOpenAIBatchClient();
116
+
117
+ const batch = await batches.create({
118
+ completion_window: '24h',
119
+ endpoint: '/v1/chat/completions',
120
+ input_file_id: 'file-abc123',
121
+ });
122
+ const latest = await batches.retrieve(batch.id);
123
+ ```
124
+
125
+ The client has no `baseURL` option: it constructs the SDK client without one, so the SDK honors `OPENAI_BASE_URL`. `openAIRows()` reads the same variable, so `getProviderCapabilities('openai', { descriptors: openAIRows() })` in Operative reports no batch inference while it is set, and what the rows advertise and where a request lands agree.
126
+
127
+ ## Embeddings
128
+
129
+ `createOpenAIEmbedder` returns an `Embedder` backed by the Embeddings API. `model` defaults to `text-embedding-3-small`:
130
+
131
+ ```typescript
132
+ import { createOpenAIEmbedder } from '@lostgradient/operative-openai';
133
+
134
+ const embedder = createOpenAIEmbedder({ model: 'text-embedding-3-small' });
135
+ ```
136
+
137
+ ## OpenTelemetry
138
+
139
+ `instrumentGenerate` from `@lostgradient/operative` wraps any `GenerateFunction`, this one included, with a single CLIENT span per call that carries the model, provider, and token usage:
140
+
141
+ ```typescript
142
+ import { instrumentGenerate } from '@lostgradient/operative';
143
+ import { createOpenAIProvider } from '@lostgradient/operative-openai';
144
+
145
+ declare const tracer: Parameters<typeof instrumentGenerate>[1]['tracer'];
146
+
147
+ const rawGenerate = createOpenAIProvider({ model: 'gpt-4o' });
148
+ const generate = instrumentGenerate(rawGenerate, {
149
+ provider: 'openai',
150
+ model: 'gpt-4o',
151
+ tracer,
152
+ });
153
+ ```
154
+
155
+ ## Testing
156
+
157
+ `@lostgradient/operative-openai/testing` exports the doubles this package's own tests use. A mock client records every request and returns queued responses, so a test drives the factory without the SDK or a network:
158
+
159
+ ```typescript
160
+ import { createOpenAIProvider } from '@lostgradient/operative-openai';
161
+ import { createMockOpenAIClient, openAITextResponse } from '@lostgradient/operative-openai/testing';
162
+
163
+ const client = createMockOpenAIClient([openAITextResponse]);
164
+ const generate = createOpenAIProvider({ model: 'gpt-4o', client });
165
+ ```
166
+
167
+ After `generate` runs, `client._calls` holds each request body that was sent.
168
+
169
+ `test/contract.test.ts` runs `runProviderContract` from `@lostgradient/operative/provider-testing` against `openaiProvider`, which checks what every provider package shares: its name, handing the whole configuration and the injected `client` to both factories, the backend descriptor for the resolved model, and keeping unavailable tools out of the request.
170
+
171
+ ## Commands
172
+
173
+ ```bash
174
+ bunx turbo run lint typecheck test --filter=@lostgradient/operative-openai
175
+ ```
@@ -0,0 +1,83 @@
1
+ import type { OpenAIBatch, OpenAIBatchClient, OpenAIBatchCreateRequest, OpenAIBatchListQuery } from "../openai-types.js";
2
+ /**
3
+ * Options for createOpenAIBatchClient.
4
+ *
5
+ * There is deliberately no `baseURL` here, unlike every other OpenAI factory in
6
+ * this package.
7
+ *
8
+ * `OpenAIProviderOptions.baseURL` exists to point the *chat* surface at an
9
+ * OpenAI-compatible server — LM Studio, Ollama, vLLM, Groq. None of those
10
+ * implement `/v1/batches`; they reuse the chat shape and nothing more. Offering
11
+ * a `baseURL` knob on a batch factory would advertise a configuration that
12
+ * cannot work, and would contradict `openAIRows({ baseURL })`, whose rows
13
+ * report `batchInference: false` for exactly that reason.
14
+ *
15
+ * A caller who genuinely has a batch-capable endpoint behind another origin — a
16
+ * credential-injecting proxy in front of `api.openai.com`, say — constructs
17
+ * their own `OpenAI` client with whatever `baseURL` they need and passes it as
18
+ * `client`. That path is unchanged and needs no cast.
19
+ *
20
+ * Omitting the knob does not pin the endpoint, though. A client this factory
21
+ * constructs for itself carries no explicit `baseURL`, and `openai` documents
22
+ * that option as defaulting to `process.env['OPENAI_BASE_URL']` — so an
23
+ * ambient override routes these batch calls wherever it points.
24
+ * `openAIRows()` reads the same variable for exactly that reason, so what the
25
+ * rows advertise and where a request lands stay in agreement.
26
+ */
27
+ export interface OpenAIBatchClientOptions {
28
+ /**
29
+ * An already-constructed client. A real `OpenAI` instance satisfies
30
+ * {@link OpenAIBatchClient} with no cast — see
31
+ * `src/openai-batch-client-assignability.test-d.ts`. This is also the escape
32
+ * hatch for a non-default base URL; see the note on this interface.
33
+ */
34
+ client?: OpenAIBatchClient | undefined;
35
+ /** Falls back to the SDK's own `OPENAI_API_KEY` lookup when omitted. */
36
+ apiKey?: string | undefined;
37
+ }
38
+ /**
39
+ * The OpenAI Batch API operations, error-normalized.
40
+ *
41
+ * A thin wrapper over `client.batches`: the verbs, the argument shapes, and the
42
+ * returned objects are OpenAI's own. The wrapper adds a lazily constructed
43
+ * client and {@link ProviderError} normalization, and nothing else.
44
+ */
45
+ export interface OpenAIBatchOperations {
46
+ /**
47
+ * Creates a batch from an already-uploaded JSONL file. Unlike Anthropic and
48
+ * Gemini, OpenAI accepts no inline requests: upload the file first (purpose
49
+ * `batch`, through `client.files`) and name it by `input_file_id`.
50
+ */
51
+ create(request: OpenAIBatchCreateRequest): Promise<OpenAIBatch>;
52
+ /** Polls one batch. `status: 'completed'` means `output_file_id` is set. */
53
+ retrieve(batchId: string): Promise<OpenAIBatch>;
54
+ /** Iterates batches, fetching further pages as it goes. */
55
+ list(query?: OpenAIBatchListQuery): AsyncIterable<OpenAIBatch>;
56
+ /**
57
+ * Requests cancellation. The batch sits in `cancelling` for up to ten minutes
58
+ * before reaching `cancelled` with whatever partial results it produced.
59
+ */
60
+ cancel(batchId: string): Promise<OpenAIBatch>;
61
+ }
62
+ /**
63
+ * Creates a client for OpenAI's native Batch API.
64
+ *
65
+ * When no `client` is provided, dynamically imports `openai` and constructs one
66
+ * from `apiKey` — so a consumer that never calls a batch method never loads the
67
+ * SDK.
68
+ *
69
+ * There is no `results` operation, and that is not an omission: OpenAI returns
70
+ * a batch's output as an uploaded file, so results are read through
71
+ * `client.files` using the `output_file_id` (and `error_file_id`) on the
72
+ * retrieved batch, not streamed off the batch itself.
73
+ *
74
+ * Requires `openai >= 4.38.0` — the first release whose `client.batches`
75
+ * carries every method {@link OpenAIBatchOperations} advertises. The package's
76
+ * declared peer range is intentionally wider (`>=4.0.0`), because chat-only
77
+ * consumers should not be held to a batch-API floor; a client that predates
78
+ * 4.38.0 is rejected here with a {@link ProviderError} naming the requirement
79
+ * rather than failing with an opaque `TypeError` on every operation. An
80
+ * injected `client` is checked when this factory is called; a lazily imported
81
+ * one is checked as soon as it is constructed.
82
+ */
83
+ export declare function createOpenAIBatchClient(options?: OpenAIBatchClientOptions): OpenAIBatchOperations;
@@ -0,0 +1,101 @@
1
+ import { assertBatchSurface, ProviderError } from '@lostgradient/operative/provider-kit';
2
+ function wrapOpenAIError(error) {
3
+ if (error instanceof ProviderError)
4
+ return error;
5
+ return new ProviderError({ provider: 'openai', cause: error });
6
+ }
7
+ /**
8
+ * `openai` 4.34.0 introduced `client.batches` with `create`/`retrieve`/`cancel`;
9
+ * `list` landed in 4.38.0. See `shared/batch-support.ts` for how both were
10
+ * established and why the declared peer range stays `>=4.0.0`.
11
+ */
12
+ const OPENAI_BATCH_REQUIREMENT = {
13
+ provider: 'openai',
14
+ packageName: 'openai',
15
+ minimumVersion: '4.38.0',
16
+ path: ['batches'],
17
+ methods: ['create', 'retrieve', 'list', 'cancel'],
18
+ };
19
+ /**
20
+ * Creates a client for OpenAI's native Batch API.
21
+ *
22
+ * When no `client` is provided, dynamically imports `openai` and constructs one
23
+ * from `apiKey` — so a consumer that never calls a batch method never loads the
24
+ * SDK.
25
+ *
26
+ * There is no `results` operation, and that is not an omission: OpenAI returns
27
+ * a batch's output as an uploaded file, so results are read through
28
+ * `client.files` using the `output_file_id` (and `error_file_id`) on the
29
+ * retrieved batch, not streamed off the batch itself.
30
+ *
31
+ * Requires `openai >= 4.38.0` — the first release whose `client.batches`
32
+ * carries every method {@link OpenAIBatchOperations} advertises. The package's
33
+ * declared peer range is intentionally wider (`>=4.0.0`), because chat-only
34
+ * consumers should not be held to a batch-API floor; a client that predates
35
+ * 4.38.0 is rejected here with a {@link ProviderError} naming the requirement
36
+ * rather than failing with an opaque `TypeError` on every operation. An
37
+ * injected `client` is checked when this factory is called; a lazily imported
38
+ * one is checked as soon as it is constructed.
39
+ */
40
+ export function createOpenAIBatchClient(options = {}) {
41
+ if (options.client)
42
+ assertBatchSurface(options.client, OPENAI_BATCH_REQUIREMENT);
43
+ let clientPromise;
44
+ function getClient() {
45
+ if (options.client)
46
+ return Promise.resolve(options.client);
47
+ if (!clientPromise) {
48
+ clientPromise = import('openai').then((module) => {
49
+ const OpenAI = module.default ?? module.OpenAI;
50
+ const clientOptions = {};
51
+ if (options.apiKey)
52
+ clientOptions.apiKey = options.apiKey;
53
+ // No cast: a real `OpenAI` satisfies `OpenAIBatchClient` as declared,
54
+ // the same guarantee a consumer passing their own client relies on.
55
+ // `openai-batch-client-assignability.test-d.ts` locks it in.
56
+ const client = new OpenAI(clientOptions);
57
+ assertBatchSurface(client, OPENAI_BATCH_REQUIREMENT);
58
+ return client;
59
+ });
60
+ }
61
+ return clientPromise;
62
+ }
63
+ return {
64
+ async create(request) {
65
+ try {
66
+ const client = await getClient();
67
+ return await client.batches.create(request);
68
+ }
69
+ catch (error) {
70
+ throw wrapOpenAIError(error);
71
+ }
72
+ },
73
+ async retrieve(batchId) {
74
+ try {
75
+ const client = await getClient();
76
+ return await client.batches.retrieve(batchId);
77
+ }
78
+ catch (error) {
79
+ throw wrapOpenAIError(error);
80
+ }
81
+ },
82
+ async *list(query) {
83
+ try {
84
+ const client = await getClient();
85
+ yield* client.batches.list(query);
86
+ }
87
+ catch (error) {
88
+ throw wrapOpenAIError(error);
89
+ }
90
+ },
91
+ async cancel(batchId) {
92
+ try {
93
+ const client = await getClient();
94
+ return await client.batches.cancel(batchId);
95
+ }
96
+ catch (error) {
97
+ throw wrapOpenAIError(error);
98
+ }
99
+ },
100
+ };
101
+ }
@@ -0,0 +1,36 @@
1
+ import type { Embedder } from 'armorer';
2
+ /**
3
+ * Structural interface for the OpenAI SDK surface used by the embedder.
4
+ */
5
+ export interface OpenAIEmbeddingClient {
6
+ /** The Embeddings resource; `embeddings.create` returns one vector per input. */
7
+ embeddings: {
8
+ create(params: Record<string, unknown>,
9
+ /** Request options; the SDK ends the request when `signal` aborts. Given only with a signal. */
10
+ options?: {
11
+ signal?: AbortSignal;
12
+ }): Promise<{
13
+ data: Array<{
14
+ embedding: number[];
15
+ }>;
16
+ }>;
17
+ };
18
+ }
19
+ /**
20
+ * Options for createOpenAIEmbedder.
21
+ */
22
+ export interface OpenAIEmbedderOptions {
23
+ /** An injected client; when absent the embedder loads the OpenAI SDK on first call and builds one. */
24
+ client?: OpenAIEmbeddingClient | undefined;
25
+ /** The API key handed to the SDK; the SDK falls back to `OPENAI_API_KEY` when absent. */
26
+ apiKey?: string | undefined;
27
+ /** The embedding model; defaults to `text-embedding-3-small`. */
28
+ model?: string | undefined;
29
+ }
30
+ /**
31
+ * Creates an Embedder backed by the OpenAI Embeddings API.
32
+ *
33
+ * When no `client` is provided, dynamically imports `openai`
34
+ * and constructs one using `apiKey` or the `OPENAI_API_KEY` env var.
35
+ */
36
+ export declare function createOpenAIEmbedder(options?: OpenAIEmbedderOptions): Embedder;
@@ -0,0 +1,37 @@
1
+ import { ProviderError } from '@lostgradient/operative/provider-kit';
2
+ /**
3
+ * Creates an Embedder backed by the OpenAI Embeddings API.
4
+ *
5
+ * When no `client` is provided, dynamically imports `openai`
6
+ * and constructs one using `apiKey` or the `OPENAI_API_KEY` env var.
7
+ */
8
+ export function createOpenAIEmbedder(options = {}) {
9
+ const { model = 'text-embedding-3-small' } = options;
10
+ let clientPromise;
11
+ function getClient() {
12
+ if (options.client)
13
+ return Promise.resolve(options.client);
14
+ if (!clientPromise) {
15
+ clientPromise = import('openai').then((module) => {
16
+ const OpenAI = module.default ?? module.OpenAI;
17
+ return new OpenAI({ apiKey: options.apiKey });
18
+ });
19
+ }
20
+ return clientPromise;
21
+ }
22
+ return async (texts, callOptions) => {
23
+ const client = await getClient();
24
+ const signal = callOptions?.signal;
25
+ try {
26
+ const parameters = { model, input: texts };
27
+ // The signal rides in the SDK's request options, and only when the caller gave one.
28
+ const response = await (signal === undefined
29
+ ? client.embeddings.create(parameters)
30
+ : client.embeddings.create(parameters, { signal }));
31
+ return response.data.map((entry) => entry.embedding);
32
+ }
33
+ catch (error) {
34
+ throw new ProviderError({ provider: 'openai', cause: error });
35
+ }
36
+ };
37
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The OpenAI model provider for Operative — `@lostgradient/operative-openai`.
3
+ *
4
+ * {@link openaiProvider} is the definition a host registers with Operative's provider machinery;
5
+ * {@link createOpenAIProvider} and {@link createOpenAIProviderStream} are the factories it wraps.
6
+ * The OpenAI SDK loads on first call, so a host that never reaches this provider never loads it.
7
+ * The same factories work against any OpenAI-compatible endpoint (LM Studio, Ollama, Groq, and
8
+ * the like) through `baseURL`. Everything else exported here is what those factories are built
9
+ * from: the structural client types a test or a proxy can satisfy, the response-format and
10
+ * tool-choice mappers, the message mapper, the batch client, the embedder, and the stream
11
+ * normalizer. The doubles that exercise them are in `@lostgradient/operative-openai/testing`.
12
+ *
13
+ * @module operative-openai
14
+ */
15
+ export { createOpenAIBatchClient } from "./batches/openai.js";
16
+ export type { OpenAIBatchClientOptions, OpenAIBatchOperations } from "./batches/openai.js";
17
+ export { createOpenAIEmbedder } from "./embeddings/openai.js";
18
+ export type { OpenAIEmbedderOptions, OpenAIEmbeddingClient } from "./embeddings/openai.js";
19
+ export { OPENAI_MODEL_ALIASES, OPENAI_REASONING_MODELS, openAIPricingTable, openAIRows, resolveOpenAIEffort, resolveOpenAIModel, } from "./openai-catalog.js";
20
+ export type { OpenAIRowsOptions } from "./openai-catalog.js";
21
+ export { openaiProvider } from "./openai-definition.js";
22
+ export type { OpenAIProviderConfiguration } from "./openai-definition.js";
23
+ export { OpenAIOutputLimitError, isOpenAIOutputLimitError } from "./openai-errors.js";
24
+ export { mapOpenAIMessage, mergeAssembledField } from "./openai-parts.js";
25
+ export type { OpenAIMessageMapping } from "./openai-parts.js";
26
+ export { toOpenAIResponseFormat } from "./openai-response-format.js";
27
+ export { toOpenAIToolChoice } from "./openai-tool-choice.js";
28
+ export type { OpenAIBatch, OpenAIBatchClient, OpenAIBatchCreateRequest, OpenAIBatchListQuery, OpenAIBatchRequestCounts, OpenAIChatCompletion, OpenAIChatCompletionChunk, OpenAIChatCompletionCreateRequest, OpenAIClient, OpenAIProviderOptions, OpenAIRequestOptions, OpenAIStreamingClient, } from "./openai-types.js";
29
+ export { createOpenAIProvider, createOpenAIProviderStream } from "./openai.js";
30
+ export { normalizeOpenAIStream } from "./streaming/normalize-openai.js";
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The OpenAI model provider for Operative — `@lostgradient/operative-openai`.
3
+ *
4
+ * {@link openaiProvider} is the definition a host registers with Operative's provider machinery;
5
+ * {@link createOpenAIProvider} and {@link createOpenAIProviderStream} are the factories it wraps.
6
+ * The OpenAI SDK loads on first call, so a host that never reaches this provider never loads it.
7
+ * The same factories work against any OpenAI-compatible endpoint (LM Studio, Ollama, Groq, and
8
+ * the like) through `baseURL`. Everything else exported here is what those factories are built
9
+ * from: the structural client types a test or a proxy can satisfy, the response-format and
10
+ * tool-choice mappers, the message mapper, the batch client, the embedder, and the stream
11
+ * normalizer. The doubles that exercise them are in `@lostgradient/operative-openai/testing`.
12
+ *
13
+ * @module operative-openai
14
+ */
15
+ export { createOpenAIBatchClient } from "./batches/openai.js";
16
+ export { createOpenAIEmbedder } from "./embeddings/openai.js";
17
+ export { OPENAI_MODEL_ALIASES, OPENAI_REASONING_MODELS, openAIPricingTable, openAIRows, resolveOpenAIEffort, resolveOpenAIModel, } from "./openai-catalog.js";
18
+ export { openaiProvider } from "./openai-definition.js";
19
+ export { OpenAIOutputLimitError, isOpenAIOutputLimitError } from "./openai-errors.js";
20
+ export { mapOpenAIMessage, mergeAssembledField } from "./openai-parts.js";
21
+ export { toOpenAIResponseFormat } from "./openai-response-format.js";
22
+ export { toOpenAIToolChoice } from "./openai-tool-choice.js";
23
+ export { createOpenAIProvider, createOpenAIProviderStream } from "./openai.js";
24
+ export { normalizeOpenAIStream } from "./streaming/normalize-openai.js";
@@ -0,0 +1,44 @@
1
+ import type { ModelPricing } from '@lostgradient/operative';
2
+ import { type BackendDescriptor, type Effort, type ModelLimitEntry } from '@lostgradient/operative/provider-kit';
3
+ export declare const OPENAI_LIMITS: Readonly<Record<string, ModelLimitEntry>>;
4
+ /** OpenAI list prices by model. */
5
+ export declare const openAIPricingTable: Readonly<Record<string, ModelPricing>>;
6
+ /**
7
+ * OpenAI shorthand aliases. `gpt`/`gpt-mini`/`gpt-nano` map to the GPT-4.1
8
+ * chat-completion family; `o`/`o-mini` map to the o-series reasoning models
9
+ * that accept `reasoning_effort` (see `./effort.ts`). Targets are drawn from
10
+ * the model IDs already pinned in `cost-estimation.ts`.
11
+ */
12
+ export declare const OPENAI_MODEL_ALIASES: Readonly<Record<string, string>>;
13
+ /** Resolves an OpenAI shorthand alias (or full model ID) to a concrete model ID. */
14
+ export declare function resolveOpenAIModel(model: string): string;
15
+ /**
16
+ * OpenAI models that accept `reasoning_effort` — the o-series reasoning
17
+ * models. The GPT-4o / GPT-4.1 chat-completion family rejects the
18
+ * parameter, so it is degraded to "omit" for those models.
19
+ */
20
+ export declare const OPENAI_REASONING_MODELS: ReadonlySet<string>;
21
+ /**
22
+ * Resolves the requested effort tier to OpenAI's `reasoning_effort` value.
23
+ * OpenAI's own vocabulary has only three tiers (`low`/`medium`/`high`) —
24
+ * the two provider-neutral tiers above `high` (`xhigh`, `max`) clamp down
25
+ * to `high` rather than erroring. Returns `undefined` for non-reasoning
26
+ * models, where the caller must omit `reasoning_effort` entirely.
27
+ */
28
+ export declare function resolveOpenAIEffort(requested: Effort, resolvedModel: string): 'low' | 'medium' | 'high' | undefined;
29
+ /** The options of {@link openAIRows}. */
30
+ export interface OpenAIRowsOptions {
31
+ /** The `freshness` stamped on every row. Defaults to the time of the call. */
32
+ readonly freshness?: string | undefined;
33
+ /**
34
+ * The base URL the provider will be configured with. A custom one, or an `OPENAI_BASE_URL` in
35
+ * the environment, makes the endpoint ambiguous: the rows then report no batch inference and an
36
+ * `unknown` availability, because the request may reach a server that is not OpenAI's.
37
+ */
38
+ readonly baseURL?: string | undefined;
39
+ }
40
+ /**
41
+ * The catalog rows of the OpenAI models, one per model, frozen. The OpenAI plugin passes them as
42
+ * its provider's `rows`.
43
+ */
44
+ export declare function openAIRows(options?: OpenAIRowsOptions): readonly BackendDescriptor[];