promptgun 0.2.1 → 0.3.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 +46 -16
- package/package.json +1 -1
- package/{build/index.d.ts → trimmed.d.ts} +107 -16
- package/build/index.js +0 -2
package/README.md
CHANGED
|
@@ -2,16 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
The world's most intuitive library for advanced LLM prompting.
|
|
4
4
|
|
|
5
|
+
### Plain text output
|
|
6
|
+
#### Non-streamed
|
|
5
7
|
```typescript
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
8
|
+
const fruit = await ai.chat('What company makes the iPhone?')
|
|
9
|
+
```
|
|
10
|
+
#### Streamed
|
|
11
|
+
```typescript
|
|
12
|
+
const stream = ai.chat('How to make bread?')
|
|
13
|
+
let recipe = ''
|
|
14
|
+
for await (const chunk of stream) {
|
|
15
|
+
recipe += chunk
|
|
16
|
+
}
|
|
9
17
|
```
|
|
10
18
|
|
|
19
|
+
### Data/JSON output
|
|
20
|
+
#### Non-streamed
|
|
11
21
|
```typescript
|
|
12
|
-
const restaurants =
|
|
13
|
-
.
|
|
14
|
-
.
|
|
22
|
+
const restaurants = ai
|
|
23
|
+
.chat('Give 5 great restaurants in London')
|
|
24
|
+
.json(o => o
|
|
15
25
|
.canBeArray(e => e
|
|
16
26
|
.canBeObject(o => o
|
|
17
27
|
.hasString('name')
|
|
@@ -20,16 +30,18 @@ const restaurants = await promptAI()
|
|
|
20
30
|
)
|
|
21
31
|
)
|
|
22
32
|
)
|
|
23
|
-
|
|
33
|
+
for (const r of restaurants) {
|
|
34
|
+
console.log(r.name)
|
|
35
|
+
}
|
|
24
36
|
```
|
|
25
|
-
|
|
26
|
-
You can
|
|
37
|
+
#### Streamed, smart
|
|
38
|
+
You can put callbacks on elements of the result data, which get called as they come in:
|
|
27
39
|
```typescript
|
|
28
|
-
await
|
|
29
|
-
.
|
|
30
|
-
.
|
|
31
|
-
.canBeArray(
|
|
32
|
-
.canBeObject(
|
|
40
|
+
await ai
|
|
41
|
+
.chat('Give 5 great restaurants in London')
|
|
42
|
+
.json(d => d
|
|
43
|
+
.canBeArray(el => el
|
|
44
|
+
.canBeObject(obj => obj
|
|
33
45
|
.hasString('name')
|
|
34
46
|
.hasString('address')
|
|
35
47
|
.hasString('styleOfFood')
|
|
@@ -42,12 +54,30 @@ await promptAI()
|
|
|
42
54
|
})
|
|
43
55
|
)
|
|
44
56
|
```
|
|
57
|
+
#### Streamed, "dumb"
|
|
58
|
+
You can also simply get the partial data, "what has come in so far". The data is parsed for you, even as the underlying JSON that is received is incomplete.
|
|
59
|
+
```typescript
|
|
60
|
+
const accumulatedDataGenerator = ai
|
|
61
|
+
.chat('What are the top 5 restaurants in New York City?')
|
|
62
|
+
.json(d => d
|
|
63
|
+
.canBeArray(el => el
|
|
64
|
+
.canBeObject(obj => obj
|
|
65
|
+
.hasString('name')
|
|
66
|
+
.hasString('address')
|
|
67
|
+
.hasString('styleOfFood')
|
|
68
|
+
)
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
for await (const accumulatedRestaurants of accumulatedDataGenerator) {
|
|
72
|
+
console.log('Received restaurants:', accumulatedRestaurants?.map(r => r.name))
|
|
73
|
+
}
|
|
74
|
+
```
|
|
45
75
|
|
|
46
76
|
## Setup
|
|
47
77
|
Before you do any prompts, do:
|
|
48
78
|
```typescript
|
|
49
|
-
|
|
50
|
-
promptGridApiKey: '<your PromptGrid API key>',
|
|
79
|
+
setupAI({
|
|
80
|
+
promptGridApiKey: '<your PromptGrid API key>', // optional
|
|
51
81
|
apiKeys: {
|
|
52
82
|
openai: '<Your OpenAI API key>', // optional
|
|
53
83
|
// etc
|
package/package.json
CHANGED
|
@@ -4,16 +4,22 @@ export declare type AccessTokens = {
|
|
|
4
4
|
openai?: string | undefined;
|
|
5
5
|
};
|
|
6
6
|
|
|
7
|
+
export declare let ai: AIClient;
|
|
8
|
+
|
|
7
9
|
export declare class AIClient {
|
|
8
10
|
apiKeys: {
|
|
11
|
+
promptgrid: string | undefined;
|
|
9
12
|
openai: Promise<string | undefined>;
|
|
10
|
-
};
|
|
13
|
+
} | undefined;
|
|
11
14
|
constructor(apiKeys: {
|
|
15
|
+
promptgrid: string | undefined;
|
|
12
16
|
openai: Promise<string | undefined>;
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
+
} | undefined);
|
|
18
|
+
chat<T extends undefined>(userMessage: string): BasicPrompt<T>;
|
|
19
|
+
chat<T extends undefined>(message: Message, ...messages: Message[]): BasicPrompt<T>;
|
|
20
|
+
chat<T extends undefined>(toPrompt: (args?: T) => Prompt): BasicPrompt<T>;
|
|
21
|
+
chat<T>(toPrompt: (args: T) => Prompt, args: T): BasicPrompt<T>;
|
|
22
|
+
chat<T = undefined>(toPrompt: (args?: T) => Prompt, args?: T): BasicPrompt<T>;
|
|
17
23
|
}
|
|
18
24
|
|
|
19
25
|
export declare type AnyJson = string | null | boolean | number | JsonArray | JsonObject;
|
|
@@ -22,6 +28,10 @@ export declare type ArrayType = BaseType<'array'> & {
|
|
|
22
28
|
elementType: Type[];
|
|
23
29
|
};
|
|
24
30
|
|
|
31
|
+
declare type ArrayType_2 = BaseType_2<'array'> & {
|
|
32
|
+
elementType: Type_2[];
|
|
33
|
+
};
|
|
34
|
+
|
|
25
35
|
export declare type AssistantMessage = {
|
|
26
36
|
system?: undefined;
|
|
27
37
|
user?: undefined;
|
|
@@ -32,12 +42,19 @@ export declare type BaseType<TT extends TypeType> = {
|
|
|
32
42
|
type: TT;
|
|
33
43
|
};
|
|
34
44
|
|
|
45
|
+
declare type BaseType_2<TT extends TypeType_2> = {
|
|
46
|
+
type: TT;
|
|
47
|
+
};
|
|
48
|
+
|
|
35
49
|
export declare class BasicPrompt<PSArgs> implements AsyncGenerator<string>, Promise<string> {
|
|
36
50
|
private aiClient;
|
|
37
51
|
private promptSupplier;
|
|
38
52
|
private promptSupplierArgs;
|
|
53
|
+
private callingCodeLine;
|
|
39
54
|
private readonly generator;
|
|
40
|
-
|
|
55
|
+
private promptName?;
|
|
56
|
+
constructor(aiClient: AIClient, promptSupplier: (args: PSArgs) => Prompt, promptSupplierArgs: PSArgs, callingCodeLine: CodeLine);
|
|
57
|
+
name(name: string): BasicPrompt<PSArgs>;
|
|
41
58
|
next(...[value]: [] | [any]): Promise<IteratorResult<string, any>>;
|
|
42
59
|
return(value: any): Promise<IteratorResult<string, any>>;
|
|
43
60
|
throw(e: any): Promise<IteratorResult<string, any>>;
|
|
@@ -46,20 +63,37 @@ export declare class BasicPrompt<PSArgs> implements AsyncGenerator<string>, Prom
|
|
|
46
63
|
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined): Promise<string | TResult>;
|
|
47
64
|
finally(onfinally?: (() => void) | null | undefined): Promise<string>;
|
|
48
65
|
get [Symbol.toStringTag](): string;
|
|
49
|
-
|
|
66
|
+
json<Json extends AnyJson = AnyJson>(type?: (value: TypeSpec_2<unknown>) => TypeSpec_2<Json>): JsonPrompt<PSArgs, Json>;
|
|
50
67
|
private getResponseAsString;
|
|
51
68
|
}
|
|
52
69
|
|
|
53
70
|
export declare type BooleanType = BaseType<'boolean'>;
|
|
54
71
|
|
|
72
|
+
declare type BooleanType_2 = BaseType_2<'boolean'>;
|
|
73
|
+
|
|
74
|
+
declare type CodeLine = {
|
|
75
|
+
stacktraceFrame: string;
|
|
76
|
+
fileName: string;
|
|
77
|
+
lineNumber: number;
|
|
78
|
+
functionName?: string;
|
|
79
|
+
};
|
|
80
|
+
|
|
55
81
|
export declare type Combine<Current, New> = unknown extends Current ? New : (Current & New) extends never ? Current | New : (Current & New);
|
|
56
82
|
|
|
83
|
+
declare type Combine_2<Current, New> = unknown extends Current ? New : (Current & New) extends never ? Current | New : (Current & New);
|
|
84
|
+
|
|
57
85
|
export declare type ConstantType<Value extends (string | number | boolean)> = BaseType<'constant'> & {
|
|
58
86
|
value: Value;
|
|
59
87
|
};
|
|
60
88
|
|
|
89
|
+
declare type ConstantType_2<Value extends (string | number | boolean)> = BaseType_2<'constant'> & {
|
|
90
|
+
value: Value;
|
|
91
|
+
};
|
|
92
|
+
|
|
61
93
|
export declare type Consumer<T> = (value: T) => void;
|
|
62
94
|
|
|
95
|
+
export declare function getCallerFileNameAndLineNumber(): CodeLine;
|
|
96
|
+
|
|
63
97
|
export declare type HandshakeData = {
|
|
64
98
|
apiKeys: AccessTokens;
|
|
65
99
|
withinQuotum: boolean;
|
|
@@ -81,9 +115,10 @@ export declare class JsonPrompt<PSArgs, Json extends AnyJson = AnyJson> extends
|
|
|
81
115
|
private promptSupplier;
|
|
82
116
|
private promptSupplierArgs;
|
|
83
117
|
private jsonTypeSupplier;
|
|
118
|
+
private callingCodeLine;
|
|
84
119
|
private readonly stringGenerator;
|
|
85
120
|
private readonly partialJsonGenerator;
|
|
86
|
-
constructor(aiClient: AIClient, promptSupplier: (args: PSArgs) => Prompt, promptSupplierArgs: PSArgs, jsonTypeSupplier: ((value:
|
|
121
|
+
constructor(aiClient: AIClient, promptSupplier: (args: PSArgs) => Prompt, promptSupplierArgs: PSArgs, jsonTypeSupplier: ((value: TypeSpec_2<unknown>) => TypeSpec_2<Json>) | undefined, callingCodeLine: CodeLine);
|
|
87
122
|
next(...[value]: [] | [any]): Promise<IteratorResult<AnyJson, any>>;
|
|
88
123
|
return(value: any): Promise<IteratorResult<AnyJson, any>>;
|
|
89
124
|
throw(e: any): Promise<IteratorResult<AnyJson, any>>;
|
|
@@ -101,13 +136,21 @@ export declare type Message = SystemMessage | UserMessage | AssistantMessage;
|
|
|
101
136
|
export declare class ModelNotSupportedError extends Error {
|
|
102
137
|
}
|
|
103
138
|
|
|
139
|
+
export declare function newAIClient(promptGridApiKey: string): AIClient;
|
|
140
|
+
|
|
141
|
+
export declare function newAIClient(config: PromptGunConfig): AIClient;
|
|
142
|
+
|
|
104
143
|
export declare class NoAiCredientialsError extends Error {
|
|
105
144
|
}
|
|
106
145
|
|
|
107
146
|
export declare type NullType = BaseType<'null'>;
|
|
108
147
|
|
|
148
|
+
declare type NullType_2 = BaseType_2<'null'>;
|
|
149
|
+
|
|
109
150
|
export declare type NumberType = BaseType<'number'>;
|
|
110
151
|
|
|
152
|
+
declare type NumberType_2 = BaseType_2<'number'>;
|
|
153
|
+
|
|
111
154
|
export declare type ObjectType = BaseType<'object'> & {
|
|
112
155
|
props: Record<string, {
|
|
113
156
|
optional: boolean;
|
|
@@ -115,6 +158,18 @@ export declare type ObjectType = BaseType<'object'> & {
|
|
|
115
158
|
}>;
|
|
116
159
|
};
|
|
117
160
|
|
|
161
|
+
declare type ObjectType_2 = BaseType_2<'object'> & {
|
|
162
|
+
props: Record<string, {
|
|
163
|
+
optional: boolean;
|
|
164
|
+
type: Type_2[];
|
|
165
|
+
}>;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
export declare function obtainAiClientData(config: PromptGunConfig): {
|
|
169
|
+
promptgrid: string | undefined;
|
|
170
|
+
openai: Promise<string | undefined>;
|
|
171
|
+
};
|
|
172
|
+
|
|
118
173
|
export declare type Opts = {
|
|
119
174
|
model?: 'gpt-4o';
|
|
120
175
|
};
|
|
@@ -125,7 +180,8 @@ export declare function promptAI(client?: AIClient): PromptBase;
|
|
|
125
180
|
|
|
126
181
|
export declare class PromptBase {
|
|
127
182
|
private aiClient;
|
|
128
|
-
|
|
183
|
+
private callingCodeLine;
|
|
184
|
+
constructor(aiClient: AIClient, callingCodeLine: CodeLine);
|
|
129
185
|
completeChat<T extends undefined>(toPrompt: (args?: T) => Prompt): BasicPrompt<T>;
|
|
130
186
|
completeChat<T>(toPrompt: (args: T) => Prompt, args: T): BasicPrompt<T>;
|
|
131
187
|
completeChat<T = undefined>(toPrompt: (args?: T) => Prompt, args?: T): BasicPrompt<T>;
|
|
@@ -148,9 +204,7 @@ export declare type RequireThatOpts = {
|
|
|
148
204
|
errorMessage?: string;
|
|
149
205
|
};
|
|
150
206
|
|
|
151
|
-
export declare function
|
|
152
|
-
|
|
153
|
-
export declare function setupPromptGun(config: PromptGunConfig): AIClient;
|
|
207
|
+
export declare function setupAI(arg: string | PromptGunConfig): void;
|
|
154
208
|
|
|
155
209
|
export declare class StreamedJsonChildElement extends StreamedJsonElement {
|
|
156
210
|
constructor();
|
|
@@ -165,14 +219,14 @@ export declare abstract class StreamedJsonElement {
|
|
|
165
219
|
private currentToken?;
|
|
166
220
|
private state;
|
|
167
221
|
private receivedExcerpts;
|
|
168
|
-
onElement(callback: Consumer<StreamedJsonElement>):
|
|
169
|
-
onProperty(propertyName: string, callback: (element: StreamedJsonElement) => void):
|
|
222
|
+
onElement(callback: Consumer<StreamedJsonElement>): this;
|
|
223
|
+
onProperty(propertyName: string, callback: (element: StreamedJsonElement) => void): this;
|
|
170
224
|
/**
|
|
171
225
|
* @deprecated Does not work right now because FIELD_NAME
|
|
172
226
|
* token comes after string value is already streaming
|
|
173
227
|
*/
|
|
174
|
-
onJsonStringProperty(propertyName: string, callback: (element: StreamedJsonElement) => void):
|
|
175
|
-
onEachExcerpt(callback: Consumer<JsonExcerpt>):
|
|
228
|
+
onJsonStringProperty(propertyName: string, callback: (element: StreamedJsonElement) => void): this;
|
|
229
|
+
onEachExcerpt(callback: Consumer<JsonExcerpt>): this;
|
|
176
230
|
/**
|
|
177
231
|
* @param onComplete - a callback that will receive the complete JSON
|
|
178
232
|
* string for this element once it's done streaming
|
|
@@ -209,6 +263,8 @@ export declare class StreamedJsonRootElement extends StreamedJsonElement {
|
|
|
209
263
|
|
|
210
264
|
export declare type StringType = BaseType<'string'>;
|
|
211
265
|
|
|
266
|
+
declare type StringType_2 = BaseType_2<'string'>;
|
|
267
|
+
|
|
212
268
|
export declare type SystemMessage = {
|
|
213
269
|
system: string;
|
|
214
270
|
user?: undefined;
|
|
@@ -240,6 +296,23 @@ export declare enum TokenType {
|
|
|
240
296
|
|
|
241
297
|
export declare type Type = UndefinedType | NullType | BooleanType | StringType | NumberType | ObjectType | ArrayType | ConstantType<any>;
|
|
242
298
|
|
|
299
|
+
declare type Type_2 = UndefinedType_2 | NullType_2 | BooleanType_2 | StringType_2 | NumberType_2 | ObjectType_2 | ArrayType_2 | ConstantType_2<any>;
|
|
300
|
+
|
|
301
|
+
declare class TypeMemberSpec<T> {
|
|
302
|
+
protected readonly type: Type_2[];
|
|
303
|
+
private readonly value;
|
|
304
|
+
constructor(type: Type_2[], value: unknown);
|
|
305
|
+
canHaveProperty<Key extends string, T_prop>(propertyName: Key, assertTypeOfProperty: (arg: TypeSpec_2<unknown>) => TypeSpec_2<T_prop | undefined>): TypeMemberSpec<Combine_2<T, Partial<Record<Key, T_prop>>>>;
|
|
306
|
+
canHaveString<Key extends string>(propertyName: Key): TypeMemberSpec<Combine_2<T, Partial<Record<Key, string>>>>;
|
|
307
|
+
canHaveNumber<Key extends string>(propertyName: Key): TypeMemberSpec<Combine_2<T, Partial<Record<Key, number>>>>;
|
|
308
|
+
canHaveBoolean<Key extends string>(propertyName: Key): TypeMemberSpec<Combine_2<T, Partial<Record<Key, boolean>>>>;
|
|
309
|
+
hasProperty<Key extends string, T_prop>(propertyName: Key, assertTypeOfProperty: (arg: TypeSpec_2<unknown>) => TypeSpec_2<T_prop>, optional: false): TypeMemberSpec<Combine_2<T, Partial<Record<Key, T_prop>>>>;
|
|
310
|
+
hasProperty<Key extends string, T_prop>(propertyName: Key, assertTypeOfProperty: (arg: TypeSpec_2<unknown>) => TypeSpec_2<T_prop>, optional?: boolean): TypeMemberSpec<Combine_2<T, Record<Key, T_prop>>>;
|
|
311
|
+
hasString<Key extends string>(propertyName: Key): TypeMemberSpec<Combine_2<T, Record<Key, string>>>;
|
|
312
|
+
hasNumber<Key extends string>(propertyName: Key): TypeMemberSpec<Combine_2<T, Record<Key, number>>>;
|
|
313
|
+
hasBoolean<Key extends string>(propertyName: Key): TypeMemberSpec<Combine_2<T, Record<Key, boolean>>>;
|
|
314
|
+
}
|
|
315
|
+
|
|
243
316
|
export declare class TypeSpec<T> {
|
|
244
317
|
readonly type: Type[];
|
|
245
318
|
private readonly value;
|
|
@@ -261,10 +334,28 @@ export declare class TypeSpec<T> {
|
|
|
261
334
|
describe(): string;
|
|
262
335
|
}
|
|
263
336
|
|
|
337
|
+
declare class TypeSpec_2<T> {
|
|
338
|
+
protected readonly type: Type_2[];
|
|
339
|
+
private readonly value;
|
|
340
|
+
constructor(type: Type_2[], value: unknown);
|
|
341
|
+
canBeArray<T_arr = unknown>(element: (arg: TypeSpec_2<unknown>) => TypeSpec_2<T_arr>): TypeSpec_2<Combine_2<T, T_arr[]>>;
|
|
342
|
+
canBeObject<T_obj extends {}>(properties: (arg: TypeMemberSpec<{}>) => TypeMemberSpec<T_obj>): TypeSpec_2<Combine_2<T, T_obj>>;
|
|
343
|
+
canBeString(): TypeSpec_2<Combine_2<T, string>>;
|
|
344
|
+
canBeNumber(): TypeSpec_2<Combine_2<T, number>>;
|
|
345
|
+
canBeBoolean(): TypeSpec_2<Combine_2<T, boolean>>;
|
|
346
|
+
canBeConstant<Value extends (string | number | boolean)>(value: Value): TypeSpec_2<Combine_2<T, Value>>;
|
|
347
|
+
canBeNull(): TypeSpec_2<Combine_2<T, null>>;
|
|
348
|
+
canBeUndefined(): TypeSpec_2<Combine_2<T, undefined>>;
|
|
349
|
+
}
|
|
350
|
+
|
|
264
351
|
export declare type TypeType = 'undefined' | 'null' | 'boolean' | 'string' | 'number' | 'object' | 'array' | 'constant';
|
|
265
352
|
|
|
353
|
+
declare type TypeType_2 = 'undefined' | 'null' | 'boolean' | 'string' | 'number' | 'object' | 'array' | 'constant';
|
|
354
|
+
|
|
266
355
|
export declare type UndefinedType = BaseType<'undefined'>;
|
|
267
356
|
|
|
357
|
+
declare type UndefinedType_2 = BaseType_2<'undefined'>;
|
|
358
|
+
|
|
268
359
|
export declare type UserMessage = {
|
|
269
360
|
system?: undefined;
|
|
270
361
|
user: string;
|
package/build/index.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var t=Object.create,e=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,n={}.hasOwnProperty,o=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),a=(o,a,l)=>(l=null!=o?t(i(o)):{},((t,i,o,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let o of s(i))!n.call(t,o)&&void 0!==o&&e(t,o,{get:()=>i[o],enumerable:!(a=r(i,o))||a.enumerable});return t})(!a&&o&&o.t?l:e(l,"default",{value:o,enumerable:!0}),o)),l=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=class t{generator;upstream;handleCancel;i=!1;constructor(t,e,s){let i=this;this.generator=async function*(){try{yield*t}catch(t){throw yield r,t}finally{i.i=!0}}(),this.upstream=e,this.handleCancel=s}[Symbol.asyncIterator](){return this}async next(...t){let e=await this.generator.next(t);return e.value!==r?e:await this.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}async cancel(t){if(!this.closed){if(void 0!==this.upstream)return this.upstream.cancel(t);void 0!==this.handleCancel?this.handleCancel(t):await this.throw(t)}}async then(t,e){try{let e=await this.asList();return null!=t?await t(e):e}catch(t){if(null!=e)return e(t);throw t}}async catch(t){try{return this.asList()}catch(e){if(null!=t)return t(e);throw e}}async finally(t){let e=await this.asList();return t?.(),e}get[Symbol.toStringTag](){return"Flux"}subscribe(t){let e=void 0!==t?this.doOnEach(t):this,r=()=>{e.next().then((t=>{t.done||r()})).catch((t=>{}))};return r(),{unsubscribe:()=>this.return()}}filter(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t)&&(yield t)}),this)}untilExcl(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){if(e(t))break;yield t}}),this)}doOnEach(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t),yield t}),this)}doAfterLast(e){let r=this,s=[];return t.constructFromGeneratorFunction((async function*(){for await(let t of r)s.push(t),yield t;await e(s)}),this)}map(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield e(t)}),this)}take(e){let r=this;return t.constructFromGeneratorFunction((async function*(){let t=0;for await(let s of r){if(t>=e){r.cancel();break}t++,yield s}}),this)}flatMap(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){let r=e(t);if(Array.isArray(r))for(let t of r)yield t;else yield await r}}),this)}transform(e){let r=e(this);return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield t}),this)}async reduce(t,e){let r=e;for await(let e of this)r=t(r,e);return r}async asList(){let t=[];for await(let e of this)t.push(e);return t}async whenComplete(){for await(let t of this);}static create(e){let r,s=[],i=[],n=!1,o=()=>{for(n=!0;i.length>0;)i.shift().resolve({done:!0,value:void 0})};return e((t=>{if(n)throw Error("Cannot push to a completed generator");i.length>0?i.shift().resolve({done:!1,value:t}):s.push(t)}),o),t.fromGenerator({[Symbol.asyncIterator](){return this},next(...t){if(r){let t=r.value;return r=void 0,Promise.reject(t)}if(s.length>0){let t=s.shift();return Promise.resolve({done:!1,value:t})}return n?Promise.resolve({done:!0,value:void 0}):new Promise(((t,e)=>{i.push({resolve:t,reject:e})}))},return:()=>(o(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r=t,i.length>0&&i.shift()?.reject(),Promise.reject(t))})}static fromArray(e){return t.fromGeneratorFunction((async function*(){for(let t of e)yield t}))}static constructFromGeneratorFunction(e,r,s){return new t(e(),r,s)}static fromGeneratorFunction(e,r){return t.constructFromGeneratorFunction(e,void 0,r)}static fromGenerator(e,r){return new t(e,void 0,r)}static fromReadableStream(e,r){return t.fromGeneratorFunction((async function*(){let t=e.getReader();try{let e;for(;!(e=await t.read()).done;)yield e.value}finally{await t.cancel()}}),r)}get closed(){return this.i}};t.Flux=e;var r={}})),h=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=l();Object.defineProperty(t,"Flux",{enumerable:!0,get:function(){return e.Flux}})})),u=a(h(),1),c=a(h(),1),p=new TextDecoder,f=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(v).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function d(t){return new E([],t)}function w(t,e,r,s){let i=e.map((e=>function(t,e,r,s){let{ignoreUnknownProps:i=!0}=s;switch(e.type){case"array":return Array.isArray(t)?0===t.length?[]:w(t[0],e.elementType,r+"[..]",s):[{expectedType:[e],path:r,value:t}];case"boolean":return"boolean"!=typeof t?[{expectedType:[e],path:r,value:t}]:[];case"undefined":return void 0===t?[]:[{expectedType:[e],path:r,value:t}];case"object":{if("object"!=typeof t||null===t)return[{expectedType:[e],path:r,value:t}];let n=[];for(let i in e.props){let o=e.props[i];if(!(i in t)){o.optional||n.push({expectedProp:i,path:r,value:t});continue}let a=o.optional?[...o.type,{type:"undefined"}]:o.type;n.push(...w(t[i],a,r+"."+i,s))}if(!i)for(let s in t)s in e.props||n.push({unknownProp:s,path:r,value:t});return n}case"string":return"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"null":return null===t?[]:[{expectedType:[e],path:r,value:t}];case"number":return"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"constant":return t===e.value?[]:[{expectedType:[e],path:r,value:t}]}}(t,e,r,s)));if(i.some((t=>0===t.length)))return[];{let e=i.flatMap((t=>t.filter((t=>void 0!==t.expectedType&&t.path===r))));return e.length>0?[{expectedType:e.flatMap((t=>t.expectedType)),path:r,value:t}]:i.flatMap((t=>t))}}var y,E=class t{type;value;constructor(t=[],e){this.type=t,this.value=e}canBeArray(e){let r=e(new t([{type:"array",elementType:[]}],this.value));return new t([...this.type,...r.type],this.value)}canBeObject(e){let r=e(new t([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}hasString(t){return this.hasProperty(t,(t=>t.canBeString()))}canHaveProperty(t,e){return this.hasProperty(t,e,!0)}hasProperty(e,r,s=!1){let i=1===this.type.length?this.type[0]:void 0;if(void 0===i||"object"!==i.type)throw Error("illegal state");let{type:n}=r(new t([],this.value));return new t([{...i,props:{...i.props,[e]:{optional:s,type:n}}}],this.value)}canBeString(){return new t([...this.type,{type:"string"}],this.value)}canBeNumber(){return new t([...this.type,{type:"number"}],this.value)}canBeBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}canBeConstant(e){return new t([...this.type,{type:"constant",value:e}],this.value)}canBeNull(){return new t([...this.type,{type:"null"}],this.value)}canBeUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}andNothingElse(t={}){let e=w(this.value,this.type,"root",t);if(e.length>0)throw new f(e,t.errorMessage);return this.value}orDefaultTo(t,e={}){return w(this.value,this.type,"root",e).length>0?t:this.value}describe(){return A(this.type)}};function A(t,e=0){if(Array.isArray(t))return t.map((t=>A(t,e))).join(" | ");switch(t.type){case"array":return A(t.elementType)+"[]\n";case"boolean":return"boolean";case"undefined":return"undefined";case"object":return`{\n${function(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}(e+1)}${Object.keys(t.props).map((e=>`${e}: ${A(t.props[e].type)}\n`)).join(", ")}}`;case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function v(t){return"constant"===t.type?`'${t.value}'`:t.type}var m=class{constructor(t,e,r,s,i=!1){this.type=t,this.source=e,this.value=r,this.fieldName=s,this.maybeIncomplete=i}},L=class t{jsonBuffer="";highestOffsetParsed=-1;static toJsonTokenFlux(e){return(new t).processDataBuffer(e)}processDataBuffer(t){return t.flatMap((t=>this.getExcerpts(t)))}getExcerpts(t){this.jsonBuffer+=t;let e,r=[],s=new _(this.jsonBuffer);for(;e=this.nextToken(s);)s.currentTokenLocation().getCharOffset()>this.highestOffsetParsed&&(r.push({token:e}),this.highestOffsetParsed=s.currentTokenLocation().getCharOffset());return r.push({source:t}),r}nextToken(t){let e=t.nextToken();return"string"!=typeof e?e:void 0}},_=class{constructor(t){this.content=t}position=0;currentTokenType;parentFieldName;currentValue=null;nextToken(){let t=this.position;if(this.position>=this.content.length)return"string-ended";for(;this.position<this.content.length&&/\s/.test(this.content[this.position]);)this.position++;if(this.position>=this.content.length)return"string-ended";let e=t=>{let e=t;for(;e<this.content.length&&/\s/.test(this.content[e]);)e++;return","===this.content[e]?e+1:void 0},r=e=>this.content.substring(t,e),s=this.content[this.position];switch(s){case"{":return this.position++,this.currentTokenType="START_OBJECT",new m(this.currentTokenType,r(this.position),void 0,this.parentFieldName);case"}":{this.position++,this.currentTokenType="END_OBJECT",this.position=e(this.position)??this.position;let t=new m(this.currentTokenType,r(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,t}case"[":return this.position++,this.currentTokenType="START_ARRAY",new m(this.currentTokenType,r(this.position),void 0,this.parentFieldName);case"]":{this.position++,this.currentTokenType="END_ARRAY",this.position=e(this.position)??this.position;let t=new m(this.currentTokenType,r(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,t}case'"':let t=++this.position,i=this.content.indexOf('"',t);for(;i>0&&"\\"===this.content[i-1];)i=this.content.indexOf('"',i+1);if(-1===i)return"token-incomplete";let n=this.content.substring(t,i);this.position=i+1;let o=this.position;for(;o<this.content.length&&/\s/.test(this.content[o]);)o++;if(this.currentTokenType=o<this.content.length&&":"===this.content[o]?"FIELD_NAME":"VALUE_STRING","FIELD_NAME"===this.currentTokenType){this.position=o+1,this.position=e(this.position)??this.position;let t=new m(this.currentTokenType,r(this.position),n,void 0);return this.parentFieldName=n,t}{this.currentValue=n,this.position=e(this.position)??this.position;let t=new m(this.currentTokenType,r(this.position),n,"VALUE_STRING"===this.currentTokenType?this.parentFieldName:void 0);return this.parentFieldName=void 0,t}case"t":{let t=this.content.substring(this.position,this.position+4);if("true"===t)return this.position+=4,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_TRUE",this.currentValue=!0,new m(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}case"f":{let t=this.content.substring(this.position,this.position+5);if("false"===t)return this.position+=5,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_FALSE",this.currentValue=!1,new m(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<5)return"token-incomplete";break}case"n":{let t=this.content.substring(this.position,this.position+4);if("null"===t)return this.position+=4,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_NULL",this.currentValue=null,new m(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}default:if(/[0-9-]/.test(s)){let t="",s=!1;for(;this.position<this.content.length&&(/[0-9]/.test(this.content[this.position])||"-"===this.content[this.position]||"."===this.content[this.position]||"e"===this.content[this.position]||"E"===this.content[this.position]||"+"===this.content[this.position]);)"."===this.content[this.position]&&(s=!0),t+=this.content[this.position++];s?(this.currentTokenType="VALUE_NUMBER_FLOAT",this.currentValue=parseFloat(t)):(this.currentTokenType="VALUE_NUMBER_INT",this.currentValue=parseInt(t,10));let i=this.position>=this.content.length;return this.position=e(this.position)??this.position,new m(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName,i)}}throw new U("Invalid JSON at position "+this.position)}currentTokenLocation(){return{getCharOffset:()=>this.position}}},U=class extends Error{constructor(t){super(t),this.name="JsonParseException"}},T=a(h(),1),N=class{receivedJson=[];propertyCallbacks=new Map;onElementCallbacks=new Set;onCompleteCallbacks=new Set;onEachExcerptCallbacks=new Set;currentToken;state=new S;receivedExcerpts=[];onElement(t){return this.onElementCallbacks.add(t),this}onProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push(e),this}onJsonStringProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push((t=>{let r=new C,s=[],i=new B;t.onEachExcerpt((t=>{void 0!==t.source&&s.push(t.source);let e=s.join(""),n=this.endsOnUnevenNumberOfBackslashes(e)?e.substring(0,e.length-1):e;s.length=0;let o=n.replace(/\\"/g,'"').substring(1),a=null!=t.token?o.substring(0,o.length-1):o;r.getExcerpts(a).forEach((t=>i.push(t)))})),e(i)})),this}onEachExcerpt(t){return this.onEachExcerptCallbacks.add(t),this.receivedExcerpts.forEach(t),this}onComplete(t){this.o(this.toAsync(t),void 0)}o(t,e){this.onCompleteCallbacks.add({consumer:t,expectedTokenType:e})}onCompleteAsync(t){this.o(t,void 0)}onCompleteAs(t){this.onCompleteAsAsync(this.toAsync(t))}onCompleteAsAsync(t){this.o((e=>{let r=JSON.parse(e.replace(/,$/,""));return t(r)}),void 0)}onCompleteAsString(t){this.o(this.toAsync(t),new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsStringAsync(t){this.o(t,new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsInt(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsIntAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsNumber(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsNumberAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsBoolean(t){this.o(this.toAsync(t),new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}onCompleteAsBooleanAsync(t){this.o(t,new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}whenComplete(){return new Promise((t=>{this.onComplete((e=>t(e)))}))}asJsonFlux(){return T.Flux.create(((t,e)=>{this.onEachExcerpt((e=>{e.source&&t(e.source)})),this.o((async()=>e()))}))}whenCompleteAs(){return new Promise((t=>{this.onCompleteAs(t)}))}async push(t){let e=t.token;if(this.onEachExcerptCallbacks.forEach((e=>e(t))),this.isState(g))return this.state.child.push(t);if(!e)return;let r=e.type;if(this.currentToken=e,this.isState(S))switch(r){case"START_OBJECT":if(this.onElementCallbacks.size>0)throw Error("registered onElement for object");return this.state=new V,void this.receivedJson.push(e.source);case"START_ARRAY":if(this.propertyCallbacks.size>0)throw Error("registered onProperty for array");return this.state=new R,void this.receivedJson.push(e.source);case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":return this.receivedJson.push(e.source),this.end();default:throw new P(e)}else if(this.isState(V))switch(r){case"FIELD_NAME":return void this.receivedJson.push(e.source);case"END_OBJECT":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let r=new B;return r.onComplete((t=>{this.receivedJson.push(t),this.state=new V})),this.state=new O(r),this.propertyCallbacks.get(e.fieldName)?.forEach((t=>t(r))),r.push(t)}default:throw new P(e)}else if(this.isState(R))switch(r){case"END_ARRAY":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let e=new B;return e.onComplete((t=>{this.receivedJson.push(t),this.state=new R})),this.onElementCallbacks.forEach((t=>t(e))),this.state=new x(e),e.push(t)}default:throw new P(e)}throw Error("Unknown state")}async end(){if(void 0===this.currentToken)throw Error("Illegal state");await T.Flux.fromArray([...this.onCompleteCallbacks]).flatMap((t=>{let e=t.expectedTokenType,r=(()=>{if(void 0===e)return this.receivedJson.join("");if(!e.has(this.currentToken.type))throw Error(`Expected token type ${Array.from(e).join(", ")} but got ${this.currentToken.type}`);return this.currentToken.value})();return t.consumer(r)}))}isState(t){return this.state instanceof t}endsOnUnevenNumberOfBackslashes(t){let e=0;for(let r=t.length-1;r>=0&&"\\"===t[r];r--)e++;return e%2==1}toAsync(t){return async e=>{t(e)}}},b=class{},g=class extends b{constructor(t){super(),this.child=t}},S=class extends b{},R=class extends b{},x=class extends g{constructor(t){super(t)}},V=class extends b{},O=class extends g{constructor(t){super(t)}},P=class extends Error{constructor(t){super("Unexpected token: "+t.type),this.name="UnexpectedTokenException"}},C=class{getExcerpts(t){return[{source:t}]}},B=class extends N{constructor(){super()}},k=a(h(),1),I=class extends N{jsonTokenFlux;constructor(t){super();let e=this;this.jsonTokenFlux=k.Flux.fromGeneratorFunction((async function*(){let r;for await(let s of t)void 0!==s.token&&(r?.token?.maybeIncomplete&&r.token.type===s.token.type&&!s.token.maybeIncomplete&&await e.push(s),r=s.token),(void 0===s.token||!s.token.maybeIncomplete)&&await e.push(s),yield s;r?.token?.maybeIncomplete&&await e.push(r)}))}whenComplete(){return this.jsonTokenFlux.then((()=>this.receivedJson.join("")))}asJsonFlux(){return this.jsonTokenFlux.map((t=>t.source)).filter((t=>void 0!==t))}},M=class{parse(t){return new I(t)}};function j(t){if(""===t.trim())return;let e=[],r=!1,s=t=>e.push(t),i=(...t)=>{let r=e[e.length-1];if(void 0===r||!t.includes(r))throw Error("illegal state");e.pop()},n=()=>Error(`Illegal state (json: ${t})`);for(let o of t){let t=e.length>0?e[e.length-1]:null,a=!1;if('"'===o)if(null===t)s('"value');else if("["===t)s('"value');else if("{"===t)s('"prop');else if('"prop":'===t)i('"prop":'),s('"value');else if('"prop'===t)r||(i('"prop'),s('"prop"'));else{if('"value'!==t)throw n();r||i('"value')}else if("["===o){if(null===t)s("[");else if("["===t)s("[");else if('"prop":'===t)s("[");else if('"prop'!==t&&'"value'!==t)throw n()}else if("{"===o){if(null!==t&&"["!==t&&'"prop":'!==t)throw n();s("{")}else if("\\"===o){if('"prop'!==t&&'"value'!==t)throw n();r||(a=!0)}else if(":"===o){if('"prop"'===t)i('"prop"'),s('"prop":');else if('"prop'!==t&&'"value'!==t)throw n()}else if("n"===o){if('"prop":'===t)i('"prop":'),s("n");else if('"prop'!==t&&'"value'!==t)throw n()}else if("u"===o){if("n"===t)i("n"),s("nu");else if("tr"===t)i("tr"),s("tru");else if('"prop'!==t&&'"value'!==t)throw n()}else if("l"===o){if("nu"===t)i("nu"),s("nul");else if("nul"===t)i("nul");else if("fa"===t)i("fa"),s("fal");else if('"prop'!==t&&'"value'!==t)throw n()}else if("t"===o){if('"prop":'===t)i('"prop":'),s("t");else if('"prop'!==t&&'"value'!==t)throw n()}else if("r"===o){if("t"===t)i("t"),s("tr");else if('"prop'!==t&&'"value'!==t)throw n()}else if("e"===o){if("tru"===t)i("tru");else if("fals"===t)i("fals");else if('"prop'!==t&&'"value'!==t)throw n()}else if("f"===o){if('"prop":'===t)i('"prop":'),s("f");else if('"prop'!==t&&'"value'!==t)throw n()}else if("a"===o){if("f"===t)i("f"),s("fa");else if('"prop'!==t&&'"value'!==t)throw n()}else if("s"===o){if("fal"===t)i("fal"),s("fals");else if('"prop'!==t&&'"value'!==t)throw n()}else if("."===o){if('"prop":'===t)i('"prop":'),s("number.");else if('"prop'!==t&&'"value'!==t)throw n()}else if(o.match(/[0-9]/)){if("number."===t)i("number.");else if('"prop'!==t&&'"value'!==t){if('"prop":'!==t)throw n();i('"prop":')}}else if("}"===o){if("{"===t)i("{");else if('"prop'!==t&&'"value'!==t)throw n()}else if("]"===o)if("["===t)i("[");else if('"prop'!==t&&'"value'!==t)throw n();r=a}let o=e.reverse().map((t=>{switch(t){case"{":return"}";case"[":return"]";case'"prop':return'": null';case'"prop"':return": null";case'"prop":':return" null";case"n":return"ull";case"nu":return"ll";case"nul":return"l";case"t":return"rue";case"tr":return"ue";case"tru":case"fals":return"e";case"f":return"alse";case"fa":return"lse";case"fal":return"se";case'"value':return'"';case"number.":return"0";default:throw n()}})).join(""),a=(r?t.substring(0,t.length-1):t).replace(/( |\n|,)+$/,"")+o;try{return JSON.parse(a)}catch(t){throw t}}function J(t){return null!=t}function F(t){if(void 0===t)throw Error("Value is undefined");return t}var G,$=class{constructor(t){this.apiKeys=t}promptLLM(t,e,r,s){return Z(this,t,e,r,s)}};function D(t){let e=(()=>{let e="string"==typeof t?t:t.promptGridApiKey;return d(e).canBeString().andNothingElse({errorMessage:"Please provide a valid API key; got "+e})})(),r="object"==typeof t&&null!==t?t.apiKeys:void 0,s=void 0!==e?(async()=>{let t=await fetch(function(){if(!y){let t=function(){let t="t";t+="ps",t="ht"+t,t+=":",t+="/",t+="/ap",t+="i.pr";let e="i";return e="d.a"+e,e="gri"+e,t+="ompt",t+e}();y=d(t).canBeString().andNothingElse({errorMessage:"PromptGrid API URL invalid: "+t})}return y}()+"/handshake",{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"promptgun",Authorization:"Bearer "+e}});if(200!==t.status){let e=await t.text();throw Error(`Handshake failed with status ${t.status}, body: ${e}`)}return await t.json()})():void 0,i=new $({openai:(async()=>r?.openai??(await s)?.apiKeys.openai)()});return G=i,i}function Y(t,e,r,s){if(void 0===G)throw Error("No LLM set up. Call setupLLM first: ```import { setupPromptGun } from 'promptgun';\n\nsetupPromptGun({openAI: \"YOUR_OPENAI_API_KEY\"});\n```");return Z(G,t,e,r,s)}function q(t){let e=t??G;if(void 0===e)throw Error("No LLM set up. Call setupPromptGun first: ```import { setupPromptGun } from 'promptgun';\n\nsetupPromptGun({openAI: \"YOUR_OPENAI_API_KEY\"});\n```");return new z(e)}var z=class{constructor(t){this.aiClient=t}completeChat(t,e){return new H(this.aiClient,t,e)}},H=class{constructor(t,e,r){this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.generator=async function*(){yield*await W(t,void 0,e(r),!1)}()}generator;next(...[t]){return this.generator.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async then(t,e){try{let e=await this.getResponseAsString();return J(t)?await t(e):e}catch(t){if(J(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(J(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"BasicPrompt"}outputJson(t){return new K(this.aiClient,this.promptSupplier,this.promptSupplierArgs,t)}async getResponseAsString(){let t="";for await(let e of this)t+=e;return t}},K=class extends B{constructor(t,e,r,s){let i=async function*(){yield*await W(t,void 0,e(r),void 0!==s&&s(d(void 0)))}(),n=u.Flux.fromGenerator(i),o=(new L).processDataBuffer(n);super(),this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.jsonTypeSupplier=s;let a=this,l=(new M).parse(o);l.onProperty("result",(t=>t.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})))),this.stringGenerator=async function*(){for await(let t of o)void 0!==t.token?l.push(t):void 0!==t.source&&(yield t.source)}(),this.partialJsonGenerator=async function*(){let t="";for await(let e of a.stringGenerator)t+=e,yield j(t).result}()}stringGenerator;partialJsonGenerator;next(...[t]){return this.partialJsonGenerator.next(t)}return(t){return this.partialJsonGenerator.return(t)}throw(t){return this.partialJsonGenerator.throw(t)}[Symbol.asyncIterator](){return this.partialJsonGenerator}async then(t,e){try{let e=await this.getResponse();return J(t)?await t(e):e}catch(t){if(J(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(J(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"BasicPrompt"}async getResponse(){let t=await this.getResponseAsString(),e=JSON.parse(t)?.result,r=this.jsonTypeSupplier;return void 0===r?e:r(d(e)).andNothingElse()}async getResponseAsString(){let t="";for await(let e of this.stringGenerator)t+=e;return t}};function Q(t){return t??"gpt-4o"}async function*W(t,e,r,s){let i=d(await t.apiKeys.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),n=function(t){let e=t=>({role:void 0!==t.user?"user":void 0!==t.system?"system":"assistant",content:F(t.user??t.system??t.assistant)});return"string"==typeof t?[{role:"user",content:t}]:Array.isArray(t)?t.map(e):[e(t)]}(r),o=s?[...n,{role:"system",content:X(0,s)}]:n;yield*function({model:t,prompt:e,apiToken:r,requireJsonResponse:s}){return c.Flux.fromGeneratorFunction((async function*(){let i=new AbortController;if("llama-2-7b-chat"===t)throw Error("illegal state");let n=await fetch("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:"Bearer "+r},method:"POST",signal:i.signal,body:JSON.stringify({model:t,messages:e,stream:!0,response_format:s?{type:"json_object"}:void 0})});if(n.status<200||n.status>=300){let t=function(t){try{return JSON.parse(t).error.message}catch{return t}}(await n.text());throw Error("OpenAPI reported: "+t)}if(null===n.body)throw Error("illegal state");let o="";yield*c.Flux.fromReadableStream(n.body,(()=>i.abort())).map((t=>p.decode(t,{stream:!0}))).flatMap((t=>t.replaceAll("data: [DONE]","").replace(/^data: /,"").split("data: "))).map((t=>t.replace(/[\n ]*$/,"").trim())).flatMap((t=>{o+=t;try{let t=JSON.parse(o);return o="",[t]}catch{return[]}})).map((t=>t.choices[0])).untilExcl((t=>null!=t.finish_reason)).map((t=>t.delta.content)).filter((t=>void 0!==t))}))}({model:Q(e),prompt:o,apiToken:i,requireJsonResponse:!1!==s})}function X(t,e){return!0===e?"Respond with JSON":"Respond with JSON matching the following type spec (note: everything is nonnullable unless explicitly stated otherwise): "+new E([{type:"object",props:{}}],void 0).hasProperty("result",(()=>e)).describe()}function Z(t,e,r,s,i){let n="object"!=typeof s&&(s??!1),o="object"==typeof s?s:i??{model:"gpt-4o"},a=u.Flux.fromGeneratorFunction((async function*(){let{model:s}=o,i=r(e);if("gpt-4o"!==s)throw new et(`Model ${s} not supported`);yield*await W(t,s,i,n)}));if(!n)return a;let l=L.toJsonTokenFlux(a);return(new M).parse(l)}var tt=class extends Error{},et=class extends Error{};export{$ as AIClient,H as BasicPrompt,K as JsonPrompt,et as ModelNotSupportedError,tt as NoAiCredientialsError,z as PromptBase,B as StreamedJsonChildElement,I as StreamedJsonRootElement,q as promptAI,Y as promptLLM,D as setupPromptGun};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|