@lostgradient/operative-openai 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,309 @@
1
+ import type { BaseProviderOptions } from '@lostgradient/operative/provider-kit';
2
+ /**
3
+ * The subset of the `openai` SDK's per-request `RequestOptions` that operative
4
+ * passes as `chat.completions.create`'s second argument.
5
+ *
6
+ * `signal` lives here and never in the body params: like the Anthropic SDK
7
+ * (see `AnthropicRequestOptions`, AB-189), the OpenAI SDK only honors
8
+ * an abort signal handed to it as request options — a signal inside the
9
+ * body is JSON-serialized away and ignored, so `run.abort()` used to leave
10
+ * the upstream stream open until the model finished on its own (AB-238).
11
+ */
12
+ export interface OpenAIRequestOptions {
13
+ /** Aborts the in-flight HTTP request, closing a streaming response early. */
14
+ signal?: AbortSignal | undefined;
15
+ }
16
+ /**
17
+ * Minimal shape of an OpenAI `chat.completions.create` request body.
18
+ *
19
+ * Mirrors `ChatCompletionCreateParamsBase` in the installed `openai` SDK
20
+ * (7.15.0): `model` and `messages` are required, everything else is optional.
21
+ * Shared by {@link OpenAIClient} and {@link OpenAIStreamingClient}, so
22
+ * `stream` is `unknown` rather than a literal. There is deliberately no
23
+ * `signal` field: the abort signal travels in {@link OpenAIRequestOptions}.
24
+ *
25
+ * Bodies are widened to `unknown` rather than `Record<string, unknown>`. The
26
+ * SDK's parameter types are `interface`s with no implicit index signature, so
27
+ * `Record<string, unknown>` fails the bivariant method check in both
28
+ * directions and makes a real `OpenAI` un-injectable without a cast.
29
+ * `openai-client-assignability.test-d.ts` asserts every SDK field is named.
30
+ */
31
+ export interface OpenAIChatCompletionCreateRequest {
32
+ /** Provider-native model id. */
33
+ model: string;
34
+ /** `Array<ChatCompletionMessageParam>` in the SDK; widened so fakes need not model it. */
35
+ messages: unknown;
36
+ /** Audio output parameters; accepted so a request can carry them, never set by Operative. */
37
+ audio?: unknown;
38
+ /** Penalizes tokens by how often they have already appeared. */
39
+ frequency_penalty?: unknown;
40
+ /** The deprecated single-function selector; never set by Operative. */
41
+ function_call?: unknown;
42
+ /** The deprecated function definitions; never set by Operative. */
43
+ functions?: unknown;
44
+ /** Per-token bias applied before sampling. */
45
+ logit_bias?: unknown;
46
+ /** Whether to return log probabilities of the output tokens. */
47
+ logprobs?: unknown;
48
+ /** Upper bound on generated tokens, reasoning tokens included. */
49
+ max_completion_tokens?: unknown;
50
+ /** Upper bound on generated tokens; what Operative sends for `maximumTokens`. */
51
+ max_tokens?: unknown;
52
+ /** Caller-supplied key-value metadata attached to the request. */
53
+ metadata?: unknown;
54
+ /** The output modalities the model should produce. */
55
+ modalities?: unknown;
56
+ /** Moderation settings applied to the request. */
57
+ moderation?: unknown;
58
+ /** How many completions to generate. */
59
+ n?: unknown;
60
+ /** Whether the model may call several tools in one turn. */
61
+ parallel_tool_calls?: unknown;
62
+ /** A predicted output the model can use to speed up generation. */
63
+ prediction?: unknown;
64
+ /** Penalizes tokens that have already appeared at all. */
65
+ presence_penalty?: unknown;
66
+ /** A stable key that groups requests sharing a prompt prefix for caching. */
67
+ prompt_cache_key?: unknown;
68
+ /** Options that tune how the prompt cache is used. */
69
+ prompt_cache_options?: unknown;
70
+ /** How long a cached prompt prefix is retained. */
71
+ prompt_cache_retention?: unknown;
72
+ /** How much reasoning a reasoning model spends; set from Operative's `effort`. */
73
+ reasoning_effort?: unknown;
74
+ /** The output format: plain text, a JSON object, or a JSON schema. */
75
+ response_format?: unknown;
76
+ /** A stable identifier for the end user, for abuse detection. */
77
+ safety_identifier?: unknown;
78
+ /** Seed for best-effort deterministic sampling. */
79
+ seed?: unknown;
80
+ /** The processing tier the request asks for. */
81
+ service_tier?: unknown;
82
+ /** Sequences at which generation stops. */
83
+ stop?: unknown;
84
+ /** Whether OpenAI stores the completion for later retrieval. */
85
+ store?: unknown;
86
+ /** Whether the response streams; `unknown` because both client shapes share this request type. */
87
+ stream?: unknown;
88
+ /** Streaming options, such as including usage in the final chunk. */
89
+ stream_options?: unknown;
90
+ /** Sampling temperature. */
91
+ temperature?: unknown;
92
+ /** Which tool, if any, the model must call; set from Operative's `toolChoice`. */
93
+ tool_choice?: unknown;
94
+ /** The tool definitions the model may call. */
95
+ tools?: unknown;
96
+ /** How many of the most likely tokens to return log probabilities for. */
97
+ top_logprobs?: unknown;
98
+ /** Nucleus-sampling probability mass. */
99
+ top_p?: unknown;
100
+ /** The deprecated end-user identifier. */
101
+ user?: unknown;
102
+ /** How verbose the model's answer should be. */
103
+ verbosity?: unknown;
104
+ /** Options for the built-in web-search tool. */
105
+ web_search_options?: unknown;
106
+ }
107
+ /**
108
+ * Structural interface for the OpenAI SDK client surface the provider uses.
109
+ */
110
+ export interface OpenAIClient {
111
+ /** The Chat Completions resource; `chat.completions.create` returns one whole completion. */
112
+ chat: {
113
+ completions: {
114
+ create(params: OpenAIChatCompletionCreateRequest, options?: OpenAIRequestOptions): Promise<OpenAIChatCompletion>;
115
+ };
116
+ };
117
+ }
118
+ /**
119
+ * Minimal shape of an OpenAI Chat Completion response.
120
+ */
121
+ export interface OpenAIChatCompletion {
122
+ /** The generated choices; Operative reads the first. */
123
+ choices: Array<{
124
+ message: {
125
+ content?: (string | null) | undefined;
126
+ /** The model's refusal text; model output, kept in metadata. */
127
+ refusal?: (string | null) | undefined;
128
+ /** Citation annotations on `content`; kept in metadata. */
129
+ annotations?: unknown;
130
+ /** Audio output; unadvertised, so a response carrying it fails typed. */
131
+ audio?: unknown;
132
+ /** The deprecated single function call; unmapped, so a response carrying it fails typed. */
133
+ function_call?: unknown;
134
+ tool_calls?: Array<{
135
+ id: string;
136
+ type: 'function';
137
+ function: {
138
+ name: string;
139
+ arguments: string;
140
+ };
141
+ } | {
142
+ id: string;
143
+ type: 'custom';
144
+ custom: {
145
+ name: string;
146
+ input: string;
147
+ };
148
+ }> | undefined;
149
+ };
150
+ finish_reason?: string | undefined;
151
+ }>;
152
+ /** Token counts for the request, when the API reports them. */
153
+ usage?: {
154
+ prompt_tokens?: number;
155
+ completion_tokens?: number;
156
+ total_tokens?: number;
157
+ prompt_tokens_details?: {
158
+ cached_tokens?: number;
159
+ };
160
+ } | undefined;
161
+ }
162
+ /**
163
+ * Options for createOpenAIProvider.
164
+ */
165
+ export interface OpenAIProviderOptions extends BaseProviderOptions {
166
+ /** An injected client; when absent the provider loads the OpenAI SDK on first call and builds one. */
167
+ client?: OpenAIClient | undefined;
168
+ /** The API key handed to the SDK; the SDK falls back to `OPENAI_API_KEY` when absent. */
169
+ apiKey?: string | undefined;
170
+ /**
171
+ * Overrides the OpenAI SDK's default base URL. Accepts any string —
172
+ * including a credential-injecting proxy origin — with no shape
173
+ * validation. Enables LM Studio, Ollama, Groq, etc.
174
+ */
175
+ baseURL?: string | undefined;
176
+ }
177
+ /**
178
+ * A single chunk from the OpenAI Chat Completions streaming API.
179
+ */
180
+ export interface OpenAIChatCompletionChunk {
181
+ /** The choice deltas this chunk carries; Operative reads the first. */
182
+ choices: Array<{
183
+ delta: {
184
+ content?: (string | null) | undefined;
185
+ refusal?: (string | null) | undefined;
186
+ role?: string | undefined;
187
+ /** Audio output; unadvertised, so a stream carrying it fails typed. */
188
+ audio?: unknown;
189
+ /** The deprecated single function call; unmapped, so a stream carrying it fails typed. */
190
+ function_call?: unknown;
191
+ tool_calls?: Array<{
192
+ index: number;
193
+ id?: string;
194
+ type?: 'function' | 'custom';
195
+ function?: {
196
+ name?: string;
197
+ arguments?: string;
198
+ };
199
+ }> | undefined;
200
+ };
201
+ finish_reason?: (string | null) | undefined;
202
+ }>;
203
+ /** Token counts, present on the final chunk when usage streaming is requested. */
204
+ usage?: ({
205
+ prompt_tokens?: number;
206
+ completion_tokens?: number;
207
+ total_tokens?: number;
208
+ prompt_tokens_details?: {
209
+ cached_tokens?: number;
210
+ };
211
+ } | null) | undefined;
212
+ }
213
+ /**
214
+ * Structural interface for an OpenAI client that supports streaming.
215
+ */
216
+ export interface OpenAIStreamingClient {
217
+ /** The Chat Completions resource; `chat.completions.create` returns the stream of chunks. */
218
+ chat: {
219
+ completions: {
220
+ create(params: OpenAIChatCompletionCreateRequest, options?: OpenAIRequestOptions): AsyncIterable<OpenAIChatCompletionChunk> | Promise<AsyncIterable<OpenAIChatCompletionChunk>>;
221
+ };
222
+ };
223
+ }
224
+ /**
225
+ * Minimal shape of an OpenAI `batches.create` request body.
226
+ *
227
+ * Unlike Anthropic and Gemini, OpenAI takes no inline requests: the batch is
228
+ * built from a JSONL file already uploaded with purpose `batch`, named here by
229
+ * `input_file_id`.
230
+ */
231
+ export interface OpenAIBatchCreateRequest {
232
+ /** Only `'24h'` is currently accepted by the API. */
233
+ completion_window: '24h';
234
+ /**
235
+ * The API route every request in the file targets, e.g.
236
+ * `'/v1/chat/completions'`, `'/v1/responses'`, or `'/v1/embeddings'`. Typed
237
+ * as `string` rather than pinned to the SDK's literal union so a newly
238
+ * supported route does not require an operative release; the installed SDK's
239
+ * `BatchCreateParams['endpoint']` is the authority on what the API accepts.
240
+ */
241
+ endpoint: string;
242
+ /** Id of an uploaded JSONL file containing the batched requests. */
243
+ input_file_id: string;
244
+ /** Caller-supplied key-value metadata attached to the batch. */
245
+ metadata?: (Record<string, string> | null) | undefined;
246
+ }
247
+ /**
248
+ * Minimal shape of OpenAI's `batches.list` query, mirroring the SDK's
249
+ * `CursorPageParams`.
250
+ */
251
+ export interface OpenAIBatchListQuery {
252
+ /** Cursor: return the batches after this batch id. */
253
+ after?: string;
254
+ /** Maximum number of batches per page. */
255
+ limit?: number;
256
+ }
257
+ /**
258
+ * Per-status request tallies on an OpenAI batch.
259
+ */
260
+ export interface OpenAIBatchRequestCounts {
261
+ /** Requests in the batch that completed successfully. */
262
+ completed: number;
263
+ /** Requests in the batch that failed. */
264
+ failed: number;
265
+ /** Requests in the batch. */
266
+ total: number;
267
+ }
268
+ /**
269
+ * Minimal shape of an OpenAI `Batch`.
270
+ */
271
+ export interface OpenAIBatch {
272
+ /** The batch id. */
273
+ id: string;
274
+ /** Always `'batch'`. */
275
+ object: 'batch';
276
+ /** The API route every request in the batch targets. */
277
+ endpoint: string;
278
+ /** Id of the uploaded JSONL file the batch was built from. */
279
+ input_file_id: string;
280
+ /** The window within which the batch must finish, such as `'24h'`. */
281
+ completion_window: string;
282
+ /** Unix seconds. */
283
+ created_at: number;
284
+ /** Where the batch is in its lifecycle. */
285
+ status: 'validating' | 'failed' | 'in_progress' | 'finalizing' | 'completed' | 'expired' | 'cancelling' | 'cancelled';
286
+ /** Id of the file holding results for the requests that succeeded. */
287
+ output_file_id?: string | undefined;
288
+ /** Id of the file holding results for the requests that errored. */
289
+ error_file_id?: string | undefined;
290
+ /** Per-status request tallies, once the API reports them. */
291
+ request_counts?: OpenAIBatchRequestCounts | undefined;
292
+ }
293
+ /**
294
+ * Structural interface for the OpenAI SDK client surface the batch factory
295
+ * uses: the top-level `client.batches` resource.
296
+ *
297
+ * There is deliberately no `results` member: OpenAI returns results as an
298
+ * uploaded file, so a caller reads `output_file_id` through `client.files`
299
+ * rather than streaming them off the batch itself.
300
+ */
301
+ export interface OpenAIBatchClient {
302
+ /** The `client.batches` resource: create, retrieve, list, and cancel. */
303
+ batches: {
304
+ create(body: OpenAIBatchCreateRequest): Promise<OpenAIBatch>;
305
+ retrieve(batchId: string): Promise<OpenAIBatch>;
306
+ list(query?: OpenAIBatchListQuery): AsyncIterable<OpenAIBatch>;
307
+ cancel(batchId: string): Promise<OpenAIBatch>;
308
+ };
309
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,28 @@
1
+ import type { GenerateFunction, StreamingGenerateFunction } from '@lostgradient/operative/provider-kit';
2
+ import type { OpenAIProviderOptions, OpenAIStreamingClient } from "./openai-types.js";
3
+ /**
4
+ * Creates a GenerateFunction backed by the OpenAI Chat Completions API.
5
+ *
6
+ * When no `client` is provided, dynamically imports `openai`
7
+ * and constructs one using `apiKey` or the `OPENAI_API_KEY` env var.
8
+ * The optional `baseURL` enables LM Studio, Ollama, Groq, etc.
9
+ *
10
+ * Note: "Provider" here is distinct from the Vercel AI SDK's concept of
11
+ * "provider". This factory returns a `GenerateFunction` — a plain async
12
+ * function that produces a `GenerateResponse` — not an SDK provider object.
13
+ */
14
+ export declare function createOpenAIProvider(options: OpenAIProviderOptions): GenerateFunction;
15
+ /**
16
+ * Creates a StreamingGenerateFunction backed by the OpenAI Chat Completions API.
17
+ *
18
+ * Streams chunks from the API, progressively calling `streaming.update`
19
+ * with accumulated text and collecting tool call fragments into complete
20
+ * ToolCallInput objects.
21
+ *
22
+ * When no `client` is provided, dynamically imports `openai`
23
+ * and constructs one using `apiKey` or the `OPENAI_API_KEY` env var.
24
+ * The optional `baseURL` enables LM Studio, Ollama, Groq, etc.
25
+ */
26
+ export declare function createOpenAIProviderStream(options: Omit<OpenAIProviderOptions, 'client'> & {
27
+ client?: OpenAIStreamingClient | undefined;
28
+ }): StreamingGenerateFunction;