promptgun 0.0.2-development → 0.2.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.
- package/README.md +12 -2
- package/build/index.d.ts +15 -4
- package/build/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -46,7 +46,17 @@ await promptAI()
|
|
|
46
46
|
## Setup
|
|
47
47
|
Before you do any prompts, do:
|
|
48
48
|
```typescript
|
|
49
|
-
setupPromptGun(
|
|
49
|
+
setupPromptGun({
|
|
50
|
+
promptGridApiKey: '<your PromptGrid API key>',
|
|
51
|
+
apiKeys: {
|
|
52
|
+
openai: '<Your OpenAI API key>', // optional
|
|
53
|
+
// etc
|
|
54
|
+
},
|
|
55
|
+
})
|
|
50
56
|
```
|
|
57
|
+
Get your PromptGrid API key for free at <a href="https://promptgrid.ai">PromptGrid.ai</a>.
|
|
51
58
|
|
|
52
|
-
|
|
59
|
+
## Terms of use
|
|
60
|
+
By using Promptgun, some metadata of your prompt code, including the code of the callback you provide to the "completeChat" clause of a Promptgun call and where you call your prompts in your code, will be saved to the PromptGrid servers.
|
|
61
|
+
The content of individual prompt calls will not be stored in PromptGrid unless you opt in at <a href="https://promptgrid.ai/prompts">promptgrid.ai/prompts</a>.
|
|
62
|
+
You can delete any data stored on PromptGrid at any time.
|
package/build/index.d.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import { Flux } from 'monoflux';
|
|
2
2
|
|
|
3
3
|
export declare type AccessTokens = {
|
|
4
|
-
|
|
4
|
+
openai?: string | undefined;
|
|
5
5
|
};
|
|
6
6
|
|
|
7
7
|
export declare class AIClient {
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
apiKeys: {
|
|
9
|
+
openai: Promise<string | undefined>;
|
|
10
|
+
};
|
|
11
|
+
constructor(apiKeys: {
|
|
12
|
+
openai: Promise<string | undefined>;
|
|
13
|
+
});
|
|
10
14
|
promptLLM<T>(args: T, toPrompt: (args: T) => Prompt, opts?: Opts): Flux<string>;
|
|
11
15
|
promptLLM<T>(args: T, toPrompt: (args: T) => Prompt, json: true, opts?: Opts): StreamedJsonRootElement;
|
|
12
16
|
promptLLM<T>(args: T, toPrompt: (args: T) => Prompt, json?: boolean, opts?: Opts): Flux<string> | StreamedJsonRootElement;
|
|
@@ -127,6 +131,11 @@ export declare class PromptBase {
|
|
|
127
131
|
completeChat<T = undefined>(toPrompt: (args?: T) => Prompt, args?: T): BasicPrompt<T>;
|
|
128
132
|
}
|
|
129
133
|
|
|
134
|
+
export declare type PromptGunConfig = {
|
|
135
|
+
promptGridApiKey?: string;
|
|
136
|
+
apiKeys?: AccessTokens;
|
|
137
|
+
};
|
|
138
|
+
|
|
130
139
|
export declare function promptLLM<T>(args: T, toPrompt: (args: T) => Prompt): Flux<string>;
|
|
131
140
|
|
|
132
141
|
export declare function promptLLM<T>(args: T, toPrompt: (args: T) => Prompt, json: true): StreamedJsonRootElement;
|
|
@@ -139,7 +148,9 @@ export declare type RequireThatOpts = {
|
|
|
139
148
|
errorMessage?: string;
|
|
140
149
|
};
|
|
141
150
|
|
|
142
|
-
export declare function setupPromptGun(
|
|
151
|
+
export declare function setupPromptGun(promptGridApiKey: string): AIClient;
|
|
152
|
+
|
|
153
|
+
export declare function setupPromptGun(config: PromptGunConfig): AIClient;
|
|
143
154
|
|
|
144
155
|
export declare class StreamedJsonChildElement extends StreamedJsonElement {
|
|
145
156
|
constructor();
|
package/build/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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 w(t){return new E([],t)}function d(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?[]:d(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(...d(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=d(this.value,this.type,"root",t);if(e.length>0)throw new f(e,t.errorMessage);return this.value}orDefaultTo(t,e={}){return d(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 g;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(S))return this.state.child.push(t);if(!e)return;let r=e.type;if(this.currentToken=e,this.isState(g))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{},S=class extends b{constructor(t){super(),this.child=t}},g=class extends b{},R=class extends b{},x=class extends S{constructor(t){super(t)}},V=class extends b{},O=class extends S{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))}},j=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 M(t){return null!=t}function F(t){if(void 0===t)throw Error("Value is undefined");return t}var G,$=class{constructor(t){this.handshakeData=t}promptLLM(t,e,r,s){return Z(this,t,e,r,s)}};function D(t){if("string"!=typeof t)throw Error("Please provide a valid API key; got "+t);let e=new $((async()=>{let e=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=w(t).canBeString().andNothingElse({errorMessage:"PromptGrid API URL invalid: "+t})}return y}()+"/handshake",{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"promptgun",Authorization:"Bearer "+t}});if(200!==e.status){let t=await e.text();throw Error(`Handshake failed with status ${e.status}, body: ${t}`)}return await e.json()})());return G=e,e}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 K(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 q(e)}var q=class{constructor(t){this.aiClient=t}completeChat(t,e){return new z(this.aiClient,t,e)}},z=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 M(t)?await t(e):e}catch(t){if(M(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(M(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 H(this.aiClient,this.promptSupplier,this.promptSupplierArgs,t)}async getResponseAsString(){let t="";for await(let e of this)t+=e;return t}},H=class extends B{constructor(t,e,r,s){let i=async function*(){yield*await W(t,void 0,e(r),void 0!==s&&s(w(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 j).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 M(t)?await t(e):e}catch(t){if(M(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(M(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(w(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=await t.handshakeData,{apiKeys:n}=i;if(void 0===n.openAi)throw new tt("No OpenAI access token set");let o=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),a=s?[...o,{role:"system",content:X(0,s)}]:o;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:a,apiToken:n.openAi,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 j).parse(l)}var tt=class extends Error{},et=class extends Error{};export{$ as AIClient,z as BasicPrompt,H as JsonPrompt,et as ModelNotSupportedError,tt as NoAiCredientialsError,q as PromptBase,B as StreamedJsonChildElement,I as StreamedJsonRootElement,K as promptAI,Y as promptLLM,D as setupPromptGun};
|
|
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
2
|
//# sourceMappingURL=index.js.map
|