openai 4.14.2 → 4.15.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.
Files changed (120) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +114 -1
  3. package/core.d.ts +1 -0
  4. package/core.d.ts.map +1 -1
  5. package/core.js +5 -1
  6. package/core.js.map +1 -1
  7. package/core.mjs +5 -1
  8. package/core.mjs.map +1 -1
  9. package/index.d.mts +2 -0
  10. package/index.d.ts +2 -0
  11. package/index.d.ts.map +1 -1
  12. package/index.js +2 -0
  13. package/index.js.map +1 -1
  14. package/index.mjs +2 -0
  15. package/index.mjs.map +1 -1
  16. package/lib/AbstractChatCompletionRunner.d.ts +111 -0
  17. package/lib/AbstractChatCompletionRunner.d.ts.map +1 -0
  18. package/lib/AbstractChatCompletionRunner.js +386 -0
  19. package/lib/AbstractChatCompletionRunner.js.map +1 -0
  20. package/lib/AbstractChatCompletionRunner.mjs +382 -0
  21. package/lib/AbstractChatCompletionRunner.mjs.map +1 -0
  22. package/lib/ChatCompletionRunFunctions.test.d.ts +2 -0
  23. package/lib/ChatCompletionRunFunctions.test.d.ts.map +1 -0
  24. package/lib/ChatCompletionRunFunctions.test.js +1850 -0
  25. package/lib/ChatCompletionRunFunctions.test.js.map +1 -0
  26. package/lib/ChatCompletionRunFunctions.test.mjs +1845 -0
  27. package/lib/ChatCompletionRunFunctions.test.mjs.map +1 -0
  28. package/lib/ChatCompletionRunner.d.ts +17 -0
  29. package/lib/ChatCompletionRunner.d.ts.map +1 -0
  30. package/lib/ChatCompletionRunner.js +19 -0
  31. package/lib/ChatCompletionRunner.js.map +1 -0
  32. package/lib/ChatCompletionRunner.mjs +15 -0
  33. package/lib/ChatCompletionRunner.mjs.map +1 -0
  34. package/lib/ChatCompletionStream.d.ts +111 -0
  35. package/lib/ChatCompletionStream.d.ts.map +1 -0
  36. package/lib/ChatCompletionStream.js +210 -0
  37. package/lib/ChatCompletionStream.js.map +1 -0
  38. package/lib/ChatCompletionStream.mjs +206 -0
  39. package/lib/ChatCompletionStream.mjs.map +1 -0
  40. package/lib/ChatCompletionStreamingRunner.d.ts +20 -0
  41. package/lib/ChatCompletionStreamingRunner.d.ts.map +1 -0
  42. package/lib/ChatCompletionStreamingRunner.js +18 -0
  43. package/lib/ChatCompletionStreamingRunner.js.map +1 -0
  44. package/lib/ChatCompletionStreamingRunner.mjs +14 -0
  45. package/lib/ChatCompletionStreamingRunner.mjs.map +1 -0
  46. package/lib/RunnableFunction.d.ts +70 -0
  47. package/lib/RunnableFunction.d.ts.map +1 -0
  48. package/lib/RunnableFunction.js +22 -0
  49. package/lib/RunnableFunction.js.map +1 -0
  50. package/lib/RunnableFunction.mjs +17 -0
  51. package/lib/RunnableFunction.mjs.map +1 -0
  52. package/lib/jsonschema.d.ts +106 -0
  53. package/lib/jsonschema.d.ts.map +1 -0
  54. package/lib/jsonschema.js +11 -0
  55. package/lib/jsonschema.js.map +1 -0
  56. package/lib/jsonschema.mjs +10 -0
  57. package/lib/jsonschema.mjs.map +1 -0
  58. package/package.json +1 -1
  59. package/resources/beta/beta.d.ts +9 -0
  60. package/resources/beta/beta.d.ts.map +1 -0
  61. package/resources/beta/beta.js +40 -0
  62. package/resources/beta/beta.js.map +1 -0
  63. package/resources/beta/beta.mjs +13 -0
  64. package/resources/beta/beta.mjs.map +1 -0
  65. package/resources/beta/chat/chat.d.ts +9 -0
  66. package/resources/beta/chat/chat.d.ts.map +1 -0
  67. package/resources/beta/chat/chat.js +40 -0
  68. package/resources/beta/chat/chat.js.map +1 -0
  69. package/resources/beta/chat/chat.mjs +13 -0
  70. package/resources/beta/chat/chat.mjs.map +1 -0
  71. package/resources/beta/chat/completions.d.ts +28 -0
  72. package/resources/beta/chat/completions.d.ts.map +1 -0
  73. package/resources/beta/chat/completions.js +32 -0
  74. package/resources/beta/chat/completions.js.map +1 -0
  75. package/resources/beta/chat/completions.mjs +24 -0
  76. package/resources/beta/chat/completions.mjs.map +1 -0
  77. package/resources/beta/chat/index.d.ts +3 -0
  78. package/resources/beta/chat/index.d.ts.map +1 -0
  79. package/resources/beta/chat/index.js +9 -0
  80. package/resources/beta/chat/index.js.map +1 -0
  81. package/resources/beta/chat/index.mjs +4 -0
  82. package/resources/beta/chat/index.mjs.map +1 -0
  83. package/resources/beta/index.d.ts +3 -0
  84. package/resources/beta/index.d.ts.map +1 -0
  85. package/resources/beta/index.js +9 -0
  86. package/resources/beta/index.js.map +1 -0
  87. package/resources/beta/index.mjs +4 -0
  88. package/resources/beta/index.mjs.map +1 -0
  89. package/resources/index.d.ts +1 -0
  90. package/resources/index.d.ts.map +1 -1
  91. package/resources/index.js +3 -1
  92. package/resources/index.js.map +1 -1
  93. package/resources/index.mjs +1 -0
  94. package/resources/index.mjs.map +1 -1
  95. package/src/core.ts +11 -2
  96. package/src/index.ts +3 -0
  97. package/src/lib/AbstractChatCompletionRunner.ts +488 -0
  98. package/src/lib/ChatCompletionRunFunctions.test.ts +1987 -0
  99. package/src/lib/ChatCompletionRunner.ts +42 -0
  100. package/src/lib/ChatCompletionStream.ts +327 -0
  101. package/src/lib/ChatCompletionStreamingRunner.ts +43 -0
  102. package/src/lib/RunnableFunction.ts +96 -0
  103. package/src/lib/jsonschema.ts +148 -0
  104. package/src/resources/beta/beta.ts +12 -0
  105. package/src/resources/beta/chat/chat.ts +12 -0
  106. package/src/resources/beta/chat/completions.ts +70 -0
  107. package/src/resources/beta/chat/index.ts +4 -0
  108. package/src/resources/beta/index.ts +4 -0
  109. package/src/resources/index.ts +1 -0
  110. package/src/streaming.ts +13 -4
  111. package/src/version.ts +1 -1
  112. package/streaming.d.ts +13 -0
  113. package/streaming.d.ts.map +1 -1
  114. package/streaming.js +13 -4
  115. package/streaming.js.map +1 -1
  116. package/streaming.mjs +13 -4
  117. package/streaming.mjs.map +1 -1
  118. package/version.d.ts +1 -1
  119. package/version.js +1 -1
  120. package/version.mjs +1 -1
@@ -0,0 +1,42 @@
1
+ import * as Core from "../core";
2
+ import {
3
+ type Completions,
4
+ type ChatCompletionMessage,
5
+ type ChatCompletionMessageParam,
6
+ type ChatCompletionCreateParamsNonStreaming,
7
+ } from "../resources/chat/completions";
8
+ import { type RunnableFunctions, type BaseFunctionsArgs } from './RunnableFunction';
9
+ import {
10
+ AbstractChatCompletionRunner,
11
+ AbstractChatCompletionRunnerEvents,
12
+ } from './AbstractChatCompletionRunner';
13
+
14
+ export interface ChatCompletionRunnerEvents extends AbstractChatCompletionRunnerEvents {
15
+ content: (content: string) => void;
16
+ }
17
+
18
+ export type ChatCompletionFunctionRunnerParams<FunctionsArgs extends BaseFunctionsArgs> = Omit<
19
+ ChatCompletionCreateParamsNonStreaming,
20
+ 'functions'
21
+ > & {
22
+ functions: RunnableFunctions<FunctionsArgs>;
23
+ };
24
+
25
+ export class ChatCompletionRunner extends AbstractChatCompletionRunner<ChatCompletionRunnerEvents> {
26
+ static runFunctions(
27
+ completions: Completions,
28
+ params: ChatCompletionFunctionRunnerParams<any[]>,
29
+ options?: Core.RequestOptions & { maxChatCompletions?: number },
30
+ ): ChatCompletionRunner {
31
+ const runner = new ChatCompletionRunner();
32
+ runner._run(() => runner._runFunctions(completions, params, options));
33
+ return runner;
34
+ }
35
+
36
+ override _addMessage(message: ChatCompletionMessage | ChatCompletionMessageParam) {
37
+ super._addMessage(message);
38
+ if (message.role === 'assistant' && message.content) {
39
+ this._emit('content', message.content);
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,327 @@
1
+ import * as Core from "../core";
2
+ import { OpenAIError, APIUserAbortError } from "../error";
3
+ import {
4
+ Completions,
5
+ type ChatCompletion,
6
+ type ChatCompletionChunk,
7
+ type ChatCompletionCreateParams,
8
+ ChatCompletionCreateParamsBase,
9
+ } from "../resources/chat/completions";
10
+ import {
11
+ AbstractChatCompletionRunner,
12
+ type AbstractChatCompletionRunnerEvents,
13
+ } from './AbstractChatCompletionRunner';
14
+ import { type ReadableStream } from "../_shims/index";
15
+ import { Stream } from "../streaming";
16
+
17
+ export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents {
18
+ content: (contentDelta: string, contentSnapshot: string) => void;
19
+ chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void;
20
+ }
21
+
22
+ export type ChatCompletionStreamParams = Omit<ChatCompletionCreateParamsBase, 'stream'> & {
23
+ stream?: true;
24
+ };
25
+
26
+ export class ChatCompletionStream
27
+ extends AbstractChatCompletionRunner<ChatCompletionStreamEvents>
28
+ implements AsyncIterable<ChatCompletionChunk>
29
+ {
30
+ #currentChatCompletionSnapshot: ChatCompletionSnapshot | undefined;
31
+
32
+ get currentChatCompletionSnapshot(): ChatCompletionSnapshot | undefined {
33
+ return this.#currentChatCompletionSnapshot;
34
+ }
35
+
36
+ /**
37
+ * Intended for use on the frontend, consuming a stream produced with
38
+ * `.toReadableStream()` on the backend.
39
+ *
40
+ * Note that messages sent to the model do not appear in `.on('message')`
41
+ * in this context.
42
+ */
43
+ static fromReadableStream(stream: ReadableStream): ChatCompletionStream {
44
+ const runner = new ChatCompletionStream();
45
+ runner._run(() => runner._fromReadableStream(stream));
46
+ return runner;
47
+ }
48
+
49
+ static createChatCompletion(
50
+ completions: Completions,
51
+ params: ChatCompletionStreamParams,
52
+ options?: Core.RequestOptions,
53
+ ): ChatCompletionStream {
54
+ const runner = new ChatCompletionStream();
55
+ runner._run(() => runner._runChatCompletion(completions, { ...params, stream: true }, options));
56
+ return runner;
57
+ }
58
+
59
+ #beginRequest() {
60
+ if (this.ended) return;
61
+ this.#currentChatCompletionSnapshot = undefined;
62
+ }
63
+ #addChunk(chunk: ChatCompletionChunk) {
64
+ if (this.ended) return;
65
+ const completion = this.#accumulateChatCompletion(chunk);
66
+ this._emit('chunk', chunk, completion);
67
+ const delta = chunk.choices[0]?.delta.content;
68
+ const snapshot = completion.choices[0]?.message;
69
+ if (delta != null && snapshot?.role === 'assistant' && snapshot?.content) {
70
+ this._emit('content', delta, snapshot.content);
71
+ }
72
+ }
73
+ #endRequest(): ChatCompletion {
74
+ if (this.ended) {
75
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
76
+ }
77
+ const snapshot = this.#currentChatCompletionSnapshot;
78
+ if (!snapshot) {
79
+ throw new OpenAIError(`request ended without sending any chunks`);
80
+ }
81
+ this.#currentChatCompletionSnapshot = undefined;
82
+ return finalizeChatCompletion(snapshot);
83
+ }
84
+
85
+ protected override async _createChatCompletion(
86
+ completions: Completions,
87
+ params: ChatCompletionCreateParams,
88
+ options?: Core.RequestOptions,
89
+ ): Promise<ChatCompletion> {
90
+ const signal = options?.signal;
91
+ if (signal) {
92
+ if (signal.aborted) this.controller.abort();
93
+ signal.addEventListener('abort', () => this.controller.abort());
94
+ }
95
+ this.#beginRequest();
96
+ const stream = await completions.create(
97
+ { ...params, stream: true },
98
+ { ...options, signal: this.controller.signal },
99
+ );
100
+ this._connected();
101
+ for await (const chunk of stream) {
102
+ this.#addChunk(chunk);
103
+ }
104
+ if (stream.controller.signal?.aborted) {
105
+ throw new APIUserAbortError();
106
+ }
107
+ return this._addChatCompletion(this.#endRequest());
108
+ }
109
+
110
+ protected async _fromReadableStream(
111
+ readableStream: ReadableStream,
112
+ options?: Core.RequestOptions,
113
+ ): Promise<ChatCompletion> {
114
+ const signal = options?.signal;
115
+ if (signal) {
116
+ if (signal.aborted) this.controller.abort();
117
+ signal.addEventListener('abort', () => this.controller.abort());
118
+ }
119
+ this.#beginRequest();
120
+ this._connected();
121
+ const stream = Stream.fromReadableStream<ChatCompletionChunk>(readableStream, this.controller);
122
+ let chatId;
123
+ for await (const chunk of stream) {
124
+ if (chatId && chatId !== chunk.id) {
125
+ // A new request has been made.
126
+ this._addChatCompletion(this.#endRequest());
127
+ }
128
+
129
+ this.#addChunk(chunk);
130
+ chatId = chunk.id;
131
+ }
132
+ if (stream.controller.signal?.aborted) {
133
+ throw new APIUserAbortError();
134
+ }
135
+ return this._addChatCompletion(this.#endRequest());
136
+ }
137
+
138
+ #accumulateChatCompletion(chunk: ChatCompletionChunk): ChatCompletionSnapshot {
139
+ let snapshot = this.#currentChatCompletionSnapshot;
140
+ if (!snapshot) {
141
+ const { choices, ...rest } = chunk;
142
+ this.#currentChatCompletionSnapshot = snapshot = {
143
+ ...rest,
144
+ choices: [],
145
+ };
146
+ }
147
+ for (const { delta, finish_reason, index } of chunk.choices) {
148
+ let choice = snapshot.choices[index];
149
+ if (!choice) snapshot.choices[index] = choice = { finish_reason, index, message: delta };
150
+ else {
151
+ if (finish_reason) choice.finish_reason = finish_reason;
152
+ const { content, function_call, role } = delta;
153
+ if (content) choice.message.content = (choice.message.content || '') + content;
154
+ if (role) choice.message.role = role;
155
+ if (function_call) {
156
+ if (!choice.message.function_call) choice.message.function_call = function_call;
157
+ else {
158
+ if (function_call.arguments)
159
+ choice.message.function_call.arguments =
160
+ (choice.message.function_call.arguments || '') + function_call.arguments;
161
+ if (function_call.name) choice.message.function_call.name = function_call.name;
162
+ }
163
+ }
164
+ }
165
+ }
166
+ return snapshot;
167
+ }
168
+
169
+ [Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {
170
+ const pushQueue: ChatCompletionChunk[] = [];
171
+ const readQueue: ((chunk: ChatCompletionChunk | undefined) => void)[] = [];
172
+ let done = false;
173
+
174
+ this.on('chunk', (chunk) => {
175
+ const reader = readQueue.shift();
176
+ if (reader) {
177
+ reader(chunk);
178
+ } else {
179
+ pushQueue.push(chunk);
180
+ }
181
+ });
182
+
183
+ this.on('end', () => {
184
+ done = true;
185
+ for (const reader of readQueue) {
186
+ reader(undefined);
187
+ }
188
+ readQueue.length = 0;
189
+ });
190
+
191
+ return {
192
+ next: async (): Promise<IteratorResult<ChatCompletionChunk>> => {
193
+ if (!pushQueue.length) {
194
+ if (done) {
195
+ return { value: undefined, done: true };
196
+ }
197
+ return new Promise<ChatCompletionChunk | undefined>((resolve) => readQueue.push(resolve)).then(
198
+ (chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }),
199
+ );
200
+ }
201
+ const chunk = pushQueue.shift()!;
202
+ return { value: chunk, done: false };
203
+ },
204
+ };
205
+ }
206
+
207
+ toReadableStream(): ReadableStream {
208
+ const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
209
+ return stream.toReadableStream();
210
+ }
211
+ }
212
+
213
+ function finalizeChatCompletion(snapshot: ChatCompletionSnapshot): ChatCompletion {
214
+ const { id, choices, created, model } = snapshot;
215
+ return {
216
+ id,
217
+ choices: choices.map(({ message, finish_reason, index }): ChatCompletion.Choice => {
218
+ if (!finish_reason) throw new OpenAIError(`missing finish_reason for choice ${index}`);
219
+ const { content = null, function_call, role } = message;
220
+ if (!role) throw new OpenAIError(`missing role for choice ${index}`);
221
+ if (function_call) {
222
+ const { arguments: args, name } = function_call;
223
+ if (args == null) throw new OpenAIError(`missing function_call.arguments for choice ${index}`);
224
+ if (!name) throw new OpenAIError(`missing function_call.name for choice ${index}`);
225
+ return { message: { content, function_call: { arguments: args, name }, role }, finish_reason, index };
226
+ }
227
+ return { message: { content: content, role }, finish_reason, index };
228
+ }),
229
+ created,
230
+ model,
231
+ object: 'chat.completion',
232
+ };
233
+ }
234
+
235
+ /**
236
+ * Represents a streamed chunk of a chat completion response returned by model,
237
+ * based on the provided input.
238
+ */
239
+ export interface ChatCompletionSnapshot {
240
+ /**
241
+ * A unique identifier for the chat completion.
242
+ */
243
+ id: string;
244
+
245
+ /**
246
+ * A list of chat completion choices. Can be more than one if `n` is greater
247
+ * than 1.
248
+ */
249
+ choices: Array<ChatCompletionSnapshot.Choice>;
250
+
251
+ /**
252
+ * The Unix timestamp (in seconds) of when the chat completion was created.
253
+ */
254
+ created: number;
255
+
256
+ /**
257
+ * The model to generate the completion.
258
+ */
259
+ model: string;
260
+ }
261
+
262
+ export namespace ChatCompletionSnapshot {
263
+ export interface Choice {
264
+ /**
265
+ * A chat completion delta generated by streamed model responses.
266
+ */
267
+ message: Choice.Message;
268
+
269
+ /**
270
+ * The reason the model stopped generating tokens. This will be `stop` if the model
271
+ * hit a natural stop point or a provided stop sequence, `length` if the maximum
272
+ * number of tokens specified in the request was reached, `content_filter` if
273
+ * content was omitted due to a flag from our content filters, or `function_call`
274
+ * if the model called a function.
275
+ */
276
+ finish_reason: 'stop' | 'length' | 'function_call' | 'content_filter' | null;
277
+
278
+ /**
279
+ * The index of the choice in the list of choices.
280
+ */
281
+ index: number;
282
+ }
283
+
284
+ export namespace Choice {
285
+ /**
286
+ * A chat completion delta generated by streamed model responses.
287
+ */
288
+ export interface Message {
289
+ /**
290
+ * The contents of the chunk message.
291
+ */
292
+ content?: string | null;
293
+
294
+ /**
295
+ * The name and arguments of a function that should be called, as generated by the
296
+ * model.
297
+ */
298
+ function_call?: Message.FunctionCall;
299
+
300
+ /**
301
+ * The role of the author of this message.
302
+ */
303
+ role?: 'system' | 'user' | 'assistant' | 'function';
304
+ }
305
+
306
+ export namespace Message {
307
+ /**
308
+ * The name and arguments of a function that should be called, as generated by the
309
+ * model.
310
+ */
311
+ export interface FunctionCall {
312
+ /**
313
+ * The arguments to call the function with, as generated by the model in JSON
314
+ * format. Note that the model does not always generate valid JSON, and may
315
+ * hallucinate parameters not defined by your function schema. Validate the
316
+ * arguments in your code before calling your function.
317
+ */
318
+ arguments?: string;
319
+
320
+ /**
321
+ * The name of the function to call.
322
+ */
323
+ name?: string;
324
+ }
325
+ }
326
+ }
327
+ }
@@ -0,0 +1,43 @@
1
+ import * as Core from "../core";
2
+ import {
3
+ Completions,
4
+ type ChatCompletionChunk,
5
+ type ChatCompletionCreateParamsStreaming,
6
+ } from "../resources/chat/completions";
7
+ import { type AbstractChatCompletionRunnerEvents } from './AbstractChatCompletionRunner';
8
+ import { type ReadableStream } from "../_shims/index";
9
+ import { type BaseFunctionsArgs, type RunnableFunctions } from './RunnableFunction';
10
+ import { ChatCompletionSnapshot, ChatCompletionStream } from './ChatCompletionStream';
11
+
12
+ export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents {
13
+ content: (contentDelta: string, contentSnapshot: string) => void;
14
+ chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void;
15
+ }
16
+
17
+ export type ChatCompletionStreamingFunctionRunnerParams<FunctionsArgs extends BaseFunctionsArgs> = Omit<
18
+ ChatCompletionCreateParamsStreaming,
19
+ 'functions'
20
+ > & {
21
+ functions: RunnableFunctions<FunctionsArgs>;
22
+ };
23
+
24
+ export class ChatCompletionStreamingRunner
25
+ extends ChatCompletionStream
26
+ implements AsyncIterable<ChatCompletionChunk>
27
+ {
28
+ static override fromReadableStream(stream: ReadableStream): ChatCompletionStreamingRunner {
29
+ const runner = new ChatCompletionStreamingRunner();
30
+ runner._run(() => runner._fromReadableStream(stream));
31
+ return runner;
32
+ }
33
+
34
+ static runFunctions<T extends (string | object)[]>(
35
+ completions: Completions,
36
+ params: ChatCompletionStreamingFunctionRunnerParams<T>,
37
+ options?: Core.RequestOptions & { maxChatCompletions?: number },
38
+ ): ChatCompletionStreamingRunner {
39
+ const runner = new ChatCompletionStreamingRunner();
40
+ runner._run(() => runner._runFunctions(completions, params, options));
41
+ return runner;
42
+ }
43
+ }
@@ -0,0 +1,96 @@
1
+ import { type ChatCompletionRunner } from './ChatCompletionRunner';
2
+ import { type ChatCompletionStreamingRunner } from './ChatCompletionStreamingRunner';
3
+ import { JSONSchema } from './jsonschema';
4
+
5
+ type PromiseOrValue<T> = T | Promise<T>;
6
+
7
+ export type RunnableFunctionWithParse<Args extends object> = {
8
+ /**
9
+ * @param args the return value from `parse`.
10
+ * @param runner the runner evaluating this callback.
11
+ * @returns a string to send back to OpenAI.
12
+ */
13
+ function: (
14
+ args: Args,
15
+ runner: ChatCompletionRunner | ChatCompletionStreamingRunner,
16
+ ) => PromiseOrValue<unknown>;
17
+ /**
18
+ * @param input the raw args from the OpenAI function call.
19
+ * @returns the parsed arguments to pass to `function`
20
+ */
21
+ parse: (input: string) => PromiseOrValue<Args>;
22
+ /**
23
+ * The parameters the function accepts, describes as a JSON Schema object.
24
+ */
25
+ parameters: JSONSchema;
26
+ /**
27
+ * A description of what the function does, used by the model to choose when and how to call the function.
28
+ */
29
+ description: string;
30
+ /**
31
+ * The name of the function to be called. Will default to function.name if omitted.
32
+ */
33
+ name?: string | undefined;
34
+ };
35
+
36
+ export type RunnableFunctionWithoutParse = {
37
+ /**
38
+ * @param args the raw args from the OpenAI function call.
39
+ * @returns a string to send back to OpenAI
40
+ */
41
+ function: (
42
+ args: string,
43
+ runner: ChatCompletionRunner | ChatCompletionStreamingRunner,
44
+ ) => PromiseOrValue<unknown>;
45
+ /**
46
+ * The parameters the function accepts, describes as a JSON Schema object.
47
+ */
48
+ parameters: JSONSchema;
49
+ /**
50
+ * A description of what the function does, used by the model to choose when and how to call the function.
51
+ */
52
+ description: string;
53
+ /**
54
+ * The name of the function to be called. Will default to function.name if omitted.
55
+ */
56
+ name?: string | undefined;
57
+ };
58
+
59
+ export type RunnableFunction<Args extends object | string> =
60
+ Args extends string ? RunnableFunctionWithoutParse
61
+ : Args extends object ? RunnableFunctionWithParse<Args>
62
+ : never;
63
+
64
+ export function isRunnableFunctionWithParse<Args extends object>(
65
+ fn: any,
66
+ ): fn is RunnableFunctionWithParse<Args> {
67
+ return typeof (fn as any).parse === 'function';
68
+ }
69
+
70
+ export type BaseFunctionsArgs = readonly (object | string)[];
71
+
72
+ export type RunnableFunctions<FunctionsArgs extends BaseFunctionsArgs> =
73
+ [any[]] extends [FunctionsArgs] ? readonly RunnableFunction<any>[]
74
+ : {
75
+ [Index in keyof FunctionsArgs]: Index extends number ? RunnableFunction<FunctionsArgs[Index]>
76
+ : FunctionsArgs[Index];
77
+ };
78
+
79
+ /**
80
+ * This is helper class for passing a `function` and `parse` where the `function`
81
+ * argument type matches the `parse` return type.
82
+ */
83
+ export class ParsingFunction<Args extends object> {
84
+ constructor(input: RunnableFunctionWithParse<Args>) {
85
+ this.function = input.function;
86
+ this.parse = input.parse;
87
+ this.parameters = input.parameters;
88
+ this.description = input.description;
89
+ this.name = input.name;
90
+ }
91
+ function: RunnableFunctionWithParse<Args>['function'];
92
+ parse: RunnableFunctionWithParse<Args>['parse'];
93
+ parameters: RunnableFunctionWithParse<Args>['parameters'];
94
+ description: RunnableFunctionWithParse<Args>['description'];
95
+ name?: RunnableFunctionWithParse<Args>['name'];
96
+ }
@@ -0,0 +1,148 @@
1
+ // File mostly copied from @types/json-schema, but stripped down a bit for brevity
2
+ // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/817274f3280152ba2929a6067c93df8b34c4c9aa/types/json-schema/index.d.ts
3
+ //
4
+ // ==================================================================================================
5
+ // JSON Schema Draft 07
6
+ // ==================================================================================================
7
+ // https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
8
+ // --------------------------------------------------------------------------------------------------
9
+
10
+ /**
11
+ * Primitive type
12
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
13
+ */
14
+ export type JSONSchemaTypeName =
15
+ | ({} & string)
16
+ | 'string'
17
+ | 'number'
18
+ | 'integer'
19
+ | 'boolean'
20
+ | 'object'
21
+ | 'array'
22
+ | 'null';
23
+
24
+ /**
25
+ * Primitive type
26
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
27
+ */
28
+ export type JSONSchemaType =
29
+ | string //
30
+ | number
31
+ | boolean
32
+ | JSONSchemaObject
33
+ | JSONSchemaArray
34
+ | null;
35
+
36
+ // Workaround for infinite type recursion
37
+ export interface JSONSchemaObject {
38
+ [key: string]: JSONSchemaType;
39
+ }
40
+
41
+ // Workaround for infinite type recursion
42
+ // https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
43
+ export interface JSONSchemaArray extends Array<JSONSchemaType> {}
44
+
45
+ /**
46
+ * Meta schema
47
+ *
48
+ * Recommended values:
49
+ * - 'http://json-schema.org/schema#'
50
+ * - 'http://json-schema.org/hyper-schema#'
51
+ * - 'http://json-schema.org/draft-07/schema#'
52
+ * - 'http://json-schema.org/draft-07/hyper-schema#'
53
+ *
54
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5
55
+ */
56
+ export type JSONSchemaVersion = string;
57
+
58
+ /**
59
+ * JSON Schema v7
60
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
61
+ */
62
+ export type JSONSchemaDefinition = JSONSchema | boolean;
63
+ export interface JSONSchema {
64
+ $id?: string | undefined;
65
+ $comment?: string | undefined;
66
+
67
+ /**
68
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1
69
+ */
70
+ type?: JSONSchemaTypeName | JSONSchemaTypeName[] | undefined;
71
+ enum?: JSONSchemaType[] | undefined;
72
+ const?: JSONSchemaType | undefined;
73
+
74
+ /**
75
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2
76
+ */
77
+ multipleOf?: number | undefined;
78
+ maximum?: number | undefined;
79
+ exclusiveMaximum?: number | undefined;
80
+ minimum?: number | undefined;
81
+ exclusiveMinimum?: number | undefined;
82
+
83
+ /**
84
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3
85
+ */
86
+ maxLength?: number | undefined;
87
+ minLength?: number | undefined;
88
+ pattern?: string | undefined;
89
+
90
+ /**
91
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4
92
+ */
93
+ items?: JSONSchemaDefinition | JSONSchemaDefinition[] | undefined;
94
+ additionalItems?: JSONSchemaDefinition | undefined;
95
+ maxItems?: number | undefined;
96
+ minItems?: number | undefined;
97
+ uniqueItems?: boolean | undefined;
98
+ contains?: JSONSchemaDefinition | undefined;
99
+
100
+ /**
101
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5
102
+ */
103
+ maxProperties?: number | undefined;
104
+ minProperties?: number | undefined;
105
+ required?: string[] | undefined;
106
+ properties?:
107
+ | {
108
+ [key: string]: JSONSchemaDefinition;
109
+ }
110
+ | undefined;
111
+ patternProperties?:
112
+ | {
113
+ [key: string]: JSONSchemaDefinition;
114
+ }
115
+ | undefined;
116
+ additionalProperties?: JSONSchemaDefinition | undefined;
117
+ propertyNames?: JSONSchemaDefinition | undefined;
118
+
119
+ /**
120
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6
121
+ */
122
+ if?: JSONSchemaDefinition | undefined;
123
+ then?: JSONSchemaDefinition | undefined;
124
+ else?: JSONSchemaDefinition | undefined;
125
+
126
+ /**
127
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7
128
+ */
129
+ allOf?: JSONSchemaDefinition[] | undefined;
130
+ anyOf?: JSONSchemaDefinition[] | undefined;
131
+ oneOf?: JSONSchemaDefinition[] | undefined;
132
+ not?: JSONSchemaDefinition | undefined;
133
+
134
+ /**
135
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7
136
+ */
137
+ format?: string | undefined;
138
+
139
+ /**
140
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10
141
+ */
142
+ title?: string | undefined;
143
+ description?: string | undefined;
144
+ default?: JSONSchemaType | undefined;
145
+ readOnly?: boolean | undefined;
146
+ writeOnly?: boolean | undefined;
147
+ examples?: JSONSchemaType | undefined;
148
+ }
@@ -0,0 +1,12 @@
1
+ // File generated from our OpenAPI spec by Stainless.
2
+
3
+ import { APIResource } from "../../resource";
4
+ import * as ChatAPI from "./chat/chat";
5
+
6
+ export class Beta extends APIResource {
7
+ chat: ChatAPI.Chat = new ChatAPI.Chat(this.client);
8
+ }
9
+
10
+ export namespace Beta {
11
+ export import Chat = ChatAPI.Chat;
12
+ }
@@ -0,0 +1,12 @@
1
+ // File generated from our OpenAPI spec by Stainless.
2
+
3
+ import { APIResource } from "../../../resource";
4
+ import * as CompletionsAPI from "./completions";
5
+
6
+ export class Chat extends APIResource {
7
+ completions: CompletionsAPI.Completions = new CompletionsAPI.Completions(this.client);
8
+ }
9
+
10
+ export namespace Chat {
11
+ export import Completions = CompletionsAPI.Completions;
12
+ }