@graphysdk/agents-sdk 1.3.0-beta.1775565657758 → 1.3.0-beta.1776177078818
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/dist/index.cjs +1 -1
- package/dist/index.d.ts +186 -40
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t=require("tslib"),e=require("zod");class r extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const i=t=>"progress"===t.type,o=t=>"complete"===t.type,s=t=>"error"===t.type;class n{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return i(t)}static isCompleteEvent(t){return o(t)}static isErrorEvent(t){return s(t)}stream(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,i);return this.parseSSE(t)})}fetch(e,n,a,l){return t.__awaiter(this,void 0,void 0,function*(){var c,g,h,u,d;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${e}`);try{const w=yield this.makeRequest(e,n,l),v=w.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var y,f=!0,m=t.__asyncValues(this.parseSSE(w));!(c=(y=yield m.next()).done);f=!0){u=y.value,f=!1;const t=u;if(i(t)&&a&&a(t),o(t))return t.data;if(s(t)){const i=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${e} ${i}ms`,t.error),new r(t.error,{code:t.code,retryable:null!==(d=t.retryable)&&void 0!==d&&d})}}}catch(t){g={error:t}}finally{try{f||c||!(h=m.return)||(yield h.call(m))}finally{if(g)throw g.error}}const n=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${e} ${n}ms`),new r("Stream ended without completion")}return yield w.json()}catch(t){const i=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${e} ${i}ms`,t),t instanceof r)throw t;throw t}finally{const t=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${e} ${t}ms`)}})}ping(){return t.__awaiter(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t.__awaiter(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(e){return t.__asyncGenerator(this,arguments,function*(){if(!e.body)throw new r("Response body is null");const i=e.body.getReader(),o=new TextDecoder;let s="",n="",a="";try{for(;;){const{done:e,value:r}=yield t.__await(i.read());if(e)break;s+=o.decode(r,{stream:!0});const l=s.split(/\r?\n/);s=l.pop()||"";for(const e of l)if(e.startsWith("event: "))n=e.slice(7).trim();else if(e.startsWith("data: "))a+=(a?"\n":"")+e.slice(6);else if(""===e.trim()&&a){try{const e=JSON.parse(a);let r;if("progress"===n){const t=e;r=Object.assign({type:"progress"},t)}else if("complete"===n)r={type:"complete",data:e};else{if("error"!==n){n="",a="";continue}{const t=e;r=Object.assign({type:"error"},t)}}if(yield yield t.__await(r),"complete"===n||"error"===n)return yield t.__await(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}n="",a=""}}}finally{i.releaseLock()}})}makeRequest(e,i,o){return t.__awaiter(this,arguments,void 0,function*(t,e,i,o=1,s="POST"){if(!t.startsWith("/"))throw new r("Invalid endpoint: must start with /");const n=new URL(t,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${o}/${this.retryConfig.attempts}: ${n}`);const a=new AbortController,l=setTimeout(()=>a.abort(),this.timeout),c=()=>a.abort();i&&i.addEventListener("abort",c);try{const l=yield fetch(n,Object.assign({method:s,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:a.signal},"POST"===s&&{body:JSON.stringify(e)}));if(!l.ok){const n=l.status>=500||429===l.status;let a,c=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?c=e.message:"string"==typeof e.error&&(c=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new r(c,{status:l.status,code:a,retryable:n});if(n&&o<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${r}ms (attempt ${o+1})`),yield this.sleep(r),this.makeRequest(t,e,i,o+1,s)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${c}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),l}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),n;if(o<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${r}ms`),yield this.sleep(r),this.makeRequest(t,e,i,o+1,s)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new r("Network error",{retryable:!0})}finally{clearTimeout(l),i&&i.removeEventListener("abort",c)}})}}const a=e.z.enum(["EN_GB","EN_US"]),l=e.z.custom(t=>null!=t&&"object"==typeof t),c=e.z.enum(["none","low","medium","high"]);e.z.object({callId:e.z.string(),locale:a.optional(),storytellingEffort:c.optional().default("low")});const g=e.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),h=e.z.object({dataPrepPrompt:e.z.string(),chartType:g,summary:e.z.string()}),u=e.z.object({title:e.z.string(),subtitle:e.z.string(),caption:e.z.string().nullable()}),d=e.z.object({suggestions:e.z.array(h)}),p=e.z.object({config:l,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string()).optional()})}),y="/api/v0";exports.AiChartTypeEnum=g,exports.GenerateGraphNarrativeResponseSchema=u,exports.GenerateGraphResponseSchema=p,exports.GenerateGraphSuggestionsResponseSchema=d,exports.GraphyAiSdk=class{constructor(t){this.client=new n(t)}generateGraph(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:o}=e,s=t.__rest(e,["storytellingOptions"]),n=yield this.client.fetch(`${y}/generate`,s,r,i),a=p.parse(n);return this.stripStorytelling(a,o)})}generateGraphStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=e,o=t.__rest(e,["storytellingOptions"]),s=yield this.client.stream(`${y}/generate`,o,r);return this.wrapStreamWithStorytellingStripping(s,i)})}generateNarrative(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${y}/narrative`,e,r,i);return u.parse(t)})}generateNarrativeStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${y}/narrative`,e,r)})}generateSuggestions(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${y}/suggestions`,e,r,i);return d.parse(t)})}generateSuggestionsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${y}/suggestions`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(e,r){return t.__asyncGenerator(this,arguments,function*(){var i,s,n,a;try{for(var l,c=!0,g=t.__asyncValues(e);!(i=(l=yield t.__await(g.next())).done);c=!0){a=l.value,c=!1;const e=a;if(o(e)){const i=this.stripStorytelling(e.data,r);yield yield t.__await(Object.assign(Object.assign({},e),{data:i}))}else yield yield t.__await(e)}}catch(t){s={error:t}}finally{try{c||i||!(n=g.return)||(yield t.__await(n.call(g)))}finally{if(s)throw s.error}}})}},exports.GraphyApiError=r,exports.StorytellingEffortSchema=c,exports.SuggestionSchema=h,exports.isCompleteEvent=o,exports.isErrorEvent=s,exports.isGraphyApiError=t=>t instanceof r,exports.isProgressEvent=i;
|
|
1
|
+
"use strict";var t=require("tslib"),e=require("zod");class r extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const i=t=>"progress"===t.type,o=t=>"complete"===t.type,n=t=>"error"===t.type;class s{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return i(t)}static isCompleteEvent(t){return o(t)}static isErrorEvent(t){return n(t)}stream(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,i);return this.parseSSE(t)})}fetch(e,s,a,l){return t.__awaiter(this,void 0,void 0,function*(){var c,g,h,d,p;const u=Date.now();this.logger.debug(`${this.tag} Fetch: ${e}`);try{const b=yield this.makeRequest(e,s,l),w=b.headers.get("content-type");if(null==w?void 0:w.includes("text/event-stream")){try{for(var y,m=!0,f=t.__asyncValues(this.parseSSE(b));!(c=(y=yield f.next()).done);m=!0){d=y.value,m=!1;const t=d;if(i(t)&&a&&a(t),o(t))return t.data;if(n(t)){const i=Date.now()-u;throw this.logger.error(`${this.tag} Server error: ${e} ${i}ms`,t.error),new r(t.error,{code:t.code,retryable:null!==(p=t.retryable)&&void 0!==p&&p})}}}catch(t){g={error:t}}finally{try{m||c||!(h=f.return)||(yield h.call(f))}finally{if(g)throw g.error}}const s=Date.now()-u;throw this.logger.error(`${this.tag} Stream incomplete: ${e} ${s}ms`),new r("Stream ended without completion")}return yield b.json()}catch(t){const i=Date.now()-u;if(this.logger.error(`${this.tag} Fetch failed: ${e} ${i}ms`,t),t instanceof r)throw t;throw t}finally{const t=Date.now()-u;this.logger.debug(`${this.tag} Fetch completed: ${e} ${t}ms`)}})}ping(){return t.__awaiter(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t.__awaiter(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(e){return t.__asyncGenerator(this,arguments,function*(){if(!e.body)throw new r("Response body is null");const i=e.body.getReader(),o=new TextDecoder;let n="",s="",a="";try{for(;;){const{done:e,value:r}=yield t.__await(i.read());if(e)break;n+=o.decode(r,{stream:!0});const l=n.split(/\r?\n/);n=l.pop()||"";for(const e of l)if(e.startsWith("event: "))s=e.slice(7).trim();else if(e.startsWith("data: "))a+=(a?"\n":"")+e.slice(6);else if(""===e.trim()&&a){try{const e=JSON.parse(a);let r;if("progress"===s){const t=e;r=Object.assign({type:"progress"},t)}else if("complete"===s)r={type:"complete",data:e};else{if("error"!==s){s="",a="";continue}{const t=e;r=Object.assign({type:"error"},t)}}if(yield yield t.__await(r),"complete"===s||"error"===s)return yield t.__await(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}s="",a=""}}}finally{i.releaseLock()}})}makeRequest(e,i,o){return t.__awaiter(this,arguments,void 0,function*(t,e,i,o=1,n="POST"){if(!t.startsWith("/"))throw new r("Invalid endpoint: must start with /");const s=new URL(t,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${o}/${this.retryConfig.attempts}: ${s}`);const a=new AbortController,l=setTimeout(()=>a.abort(),this.timeout),c=()=>a.abort();i&&i.addEventListener("abort",c);try{const l=yield fetch(s,Object.assign({method:n,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:a.signal},"POST"===n&&{body:JSON.stringify(e)}));if(!l.ok){const s=l.status>=500||429===l.status;let a,c=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?c=e.message:"string"==typeof e.error&&(c=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new r(c,{status:l.status,code:a,retryable:s});if(s&&o<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${r}ms (attempt ${o+1})`),yield this.sleep(r),this.makeRequest(t,e,i,o+1,n)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${c}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),l}catch(s){if(s instanceof r)throw s;if(s instanceof Error&&"AbortError"===s.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),s;if(o<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${r}ms`),yield this.sleep(r),this.makeRequest(t,e,i,o+1,n)}throw this.logger.error(`${this.tag} Network error: ${t}`,s),new r("Network error",{retryable:!0})}finally{clearTimeout(l),i&&i.removeEventListener("abort",c)}})}}const a=e.z.enum(["EN_GB","EN_US"]),l=e.z.custom(t=>null!=t&&"object"==typeof t),c=e.z.enum(["none","low","medium","high"]),g=e.z.object({maxWallClockMs:e.z.number().positive().optional(),maxTotalTokens:e.z.number().int().positive().optional(),maxCostUsd:e.z.number().positive().optional()}),h=e.z.object({callId:e.z.string().max(256),locale:a.optional(),storytellingEffort:c.optional().default("low"),budget:g.optional()}),d=e.z.object({config:l,userPrompt:e.z.string().max(1e4).optional().default(""),metadata:h.optional()}),p=e.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),u=e.z.object({dataPrepPrompt:e.z.string(),chartType:p,summary:e.z.string()}),y=e.z.object({response:e.z.object({message:e.z.string()}),config:l}),m=e.z.object({suggestions:e.z.array(u)}),f=e.z.object({answer:e.z.string().describe("Direct answer for this finding."),confidence:e.z.number().min(0).max(1).describe("Confidence between 0 and 1."),evidenceSummary:e.z.string().max(300).describe("Short prose summary of the statistical evidence.")}),b=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),findings:e.z.array(f)}),w=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),config:l}),v=e.z.object({config:l,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())})}),_="/api/v0";exports.AiChartTypeEnum=p,exports.ExploreFindingSchema=f,exports.GenerateAnnotationsResponseSchema=w,exports.GenerateExplorationResponseSchema=b,exports.GenerateGraphResponseSchema=v,exports.GenerateNarrativeResponseSchema=y,exports.GenerateSuggestionsResponseSchema=m,exports.GraphGenerationRequestSchema=d,exports.GraphyAiSdk=class{constructor(t){this.client=new s(t)}generateGraph(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:o}=e,n=t.__rest(e,["storytellingOptions"]),s=yield this.client.fetch(`${_}/generate`,n,r,i),a=v.parse(s);return this.stripStorytelling(a,o)})}generateGraphStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=e,o=t.__rest(e,["storytellingOptions"]),n=yield this.client.stream(`${_}/generate`,o,r);return this.wrapStreamWithStorytellingStripping(n,i)})}generateNarrative(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${_}/narrate`,e,r,i);return y.parse(t)})}generateNarrativeStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${_}/narrate`,e,r)})}generateSuggestions(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${_}/suggestions`,e,r,i);return m.parse(t)})}generateSuggestionsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${_}/suggestions`,e,r)})}generateExploration(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${_}/explore`,e,r,i);return b.parse(t)})}generateExplorationStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${_}/explore`,e,r)})}generateAnnotations(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${_}/annotate`,e,r,i);return w.parse(t)})}generateAnnotationsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${_}/annotate`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(e,r){return t.__asyncGenerator(this,arguments,function*(){var i,n,s,a;try{for(var l,c=!0,g=t.__asyncValues(e);!(i=(l=yield t.__await(g.next())).done);c=!0){a=l.value,c=!1;const e=a;if(o(e)){const i=this.stripStorytelling(e.data,r);yield yield t.__await(Object.assign(Object.assign({},e),{data:i}))}else yield yield t.__await(e)}}catch(t){n={error:t}}finally{try{c||i||!(s=g.return)||(yield t.__await(s.call(g)))}finally{if(n)throw n.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=h,exports.StorytellingEffortSchema=c,exports.SuggestionSchema=u,exports.isCompleteEvent=o,exports.isErrorEvent=n,exports.isGraphyApiError=t=>t instanceof r,exports.isProgressEvent=i;
|
package/dist/index.d.ts
CHANGED
|
@@ -214,6 +214,21 @@ declare const StorytellingEffortSchema: z.ZodEnum<{
|
|
|
214
214
|
high: "high";
|
|
215
215
|
}>;
|
|
216
216
|
type StorytellingEffort = z.infer<typeof StorytellingEffortSchema>;
|
|
217
|
+
/**
|
|
218
|
+
* Optional per-request invocation budget. Mirrors `InvocationBudgetSchema` in
|
|
219
|
+
* `apps/agents-api/src/modules/api/api.types.ts`. All fields are optional — the
|
|
220
|
+
* server merges whatever is provided with its own defaults.
|
|
221
|
+
*/
|
|
222
|
+
declare const InvocationBudgetSchema: z.ZodObject<{
|
|
223
|
+
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
224
|
+
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
225
|
+
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
226
|
+
}, z.core.$strip>;
|
|
227
|
+
type InvocationBudget = z.infer<typeof InvocationBudgetSchema>;
|
|
228
|
+
/**
|
|
229
|
+
* Per-request metadata accepted by every agent endpoint. Kept in sync with
|
|
230
|
+
* `MetadataSchema` in `apps/agents-api/src/modules/api/api.types.ts`.
|
|
231
|
+
*/
|
|
217
232
|
declare const MetadataSchema: z.ZodObject<{
|
|
218
233
|
callId: z.ZodString;
|
|
219
234
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
@@ -226,8 +241,43 @@ declare const MetadataSchema: z.ZodObject<{
|
|
|
226
241
|
medium: "medium";
|
|
227
242
|
high: "high";
|
|
228
243
|
}>>>;
|
|
244
|
+
budget: z.ZodOptional<z.ZodObject<{
|
|
245
|
+
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
246
|
+
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
247
|
+
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
248
|
+
}, z.core.$strip>>;
|
|
229
249
|
}, z.core.$strip>;
|
|
230
250
|
type Metadata = z.infer<typeof MetadataSchema>;
|
|
251
|
+
/** Mirrors `MAX_USER_PROMPT_LENGTH` in the agents-api request schema. */
|
|
252
|
+
declare const MAX_USER_PROMPT_LENGTH = 10000;
|
|
253
|
+
/**
|
|
254
|
+
* Shared request body for every agent endpoint (`/v0/generate`, `/v0/narrate`,
|
|
255
|
+
* `/v0/explore`, `/v0/annotate`, etc.). Mirrors `GraphGenerationRequestSchema`
|
|
256
|
+
* in `apps/agents-api/src/modules/api/api.types.ts`.
|
|
257
|
+
*/
|
|
258
|
+
declare const GraphGenerationRequestSchema: z.ZodObject<{
|
|
259
|
+
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
260
|
+
userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
261
|
+
metadata: z.ZodOptional<z.ZodObject<{
|
|
262
|
+
callId: z.ZodString;
|
|
263
|
+
locale: z.ZodOptional<z.ZodEnum<{
|
|
264
|
+
EN_GB: "EN_GB";
|
|
265
|
+
EN_US: "EN_US";
|
|
266
|
+
}>>;
|
|
267
|
+
storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
|
|
268
|
+
none: "none";
|
|
269
|
+
low: "low";
|
|
270
|
+
medium: "medium";
|
|
271
|
+
high: "high";
|
|
272
|
+
}>>>;
|
|
273
|
+
budget: z.ZodOptional<z.ZodObject<{
|
|
274
|
+
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
275
|
+
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
276
|
+
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
277
|
+
}, z.core.$strip>>;
|
|
278
|
+
}, z.core.$strip>>;
|
|
279
|
+
}, z.core.$strip>;
|
|
280
|
+
type GraphGenerationRequest = z.input<typeof GraphGenerationRequestSchema>;
|
|
231
281
|
declare const AiChartTypeEnum: z.ZodEnum<{
|
|
232
282
|
line: "line";
|
|
233
283
|
bar: "bar";
|
|
@@ -244,6 +294,7 @@ declare const AiChartTypeEnum: z.ZodEnum<{
|
|
|
244
294
|
funnel: "funnel";
|
|
245
295
|
heatmap: "heatmap";
|
|
246
296
|
scatter: "scatter";
|
|
297
|
+
bubble: "bubble";
|
|
247
298
|
waterfall: "waterfall";
|
|
248
299
|
table: "table";
|
|
249
300
|
}>;
|
|
@@ -266,29 +317,23 @@ declare const SuggestionSchema: z.ZodObject<{
|
|
|
266
317
|
funnel: "funnel";
|
|
267
318
|
heatmap: "heatmap";
|
|
268
319
|
scatter: "scatter";
|
|
320
|
+
bubble: "bubble";
|
|
269
321
|
waterfall: "waterfall";
|
|
270
322
|
table: "table";
|
|
271
323
|
}>;
|
|
272
324
|
summary: z.ZodString;
|
|
273
325
|
}, z.core.$strip>;
|
|
274
326
|
type Suggestion = z.infer<typeof SuggestionSchema>;
|
|
275
|
-
type
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
title: z.ZodString;
|
|
282
|
-
subtitle: z.ZodString;
|
|
283
|
-
caption: z.ZodNullable<z.ZodString>;
|
|
327
|
+
type GenerateNarrativeParams = GraphGenerationRequest;
|
|
328
|
+
declare const GenerateNarrativeResponseSchema: z.ZodObject<{
|
|
329
|
+
response: z.ZodObject<{
|
|
330
|
+
message: z.ZodString;
|
|
331
|
+
}, z.core.$strip>;
|
|
332
|
+
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
284
333
|
}, z.core.$strip>;
|
|
285
|
-
type
|
|
286
|
-
type
|
|
287
|
-
|
|
288
|
-
userPrompt: string;
|
|
289
|
-
metadata?: Metadata;
|
|
290
|
-
};
|
|
291
|
-
declare const GenerateGraphSuggestionsResponseSchema: z.ZodObject<{
|
|
334
|
+
type GenerateNarrativeResponse = z.infer<typeof GenerateNarrativeResponseSchema>;
|
|
335
|
+
type GenerateSuggestionsParams = GraphGenerationRequest;
|
|
336
|
+
declare const GenerateSuggestionsResponseSchema: z.ZodObject<{
|
|
292
337
|
suggestions: z.ZodArray<z.ZodObject<{
|
|
293
338
|
dataPrepPrompt: z.ZodString;
|
|
294
339
|
chartType: z.ZodEnum<{
|
|
@@ -307,29 +352,56 @@ declare const GenerateGraphSuggestionsResponseSchema: z.ZodObject<{
|
|
|
307
352
|
funnel: "funnel";
|
|
308
353
|
heatmap: "heatmap";
|
|
309
354
|
scatter: "scatter";
|
|
355
|
+
bubble: "bubble";
|
|
310
356
|
waterfall: "waterfall";
|
|
311
357
|
table: "table";
|
|
312
358
|
}>;
|
|
313
359
|
summary: z.ZodString;
|
|
314
360
|
}, z.core.$strip>>;
|
|
315
361
|
}, z.core.$strip>;
|
|
316
|
-
type
|
|
362
|
+
type GenerateSuggestionsResponse = z.infer<typeof GenerateSuggestionsResponseSchema>;
|
|
363
|
+
type GenerateExplorationParams = GraphGenerationRequest;
|
|
364
|
+
/** A single structured finding produced by the explore agent. */
|
|
365
|
+
declare const ExploreFindingSchema: z.ZodObject<{
|
|
366
|
+
answer: z.ZodString;
|
|
367
|
+
confidence: z.ZodNumber;
|
|
368
|
+
evidenceSummary: z.ZodString;
|
|
369
|
+
}, z.core.$strip>;
|
|
370
|
+
type ExploreFinding = z.infer<typeof ExploreFindingSchema>;
|
|
371
|
+
declare const GenerateExplorationResponseSchema: z.ZodObject<{
|
|
372
|
+
response: z.ZodObject<{
|
|
373
|
+
message: z.ZodString;
|
|
374
|
+
steps: z.ZodArray<z.ZodString>;
|
|
375
|
+
}, z.core.$strip>;
|
|
376
|
+
findings: z.ZodArray<z.ZodObject<{
|
|
377
|
+
answer: z.ZodString;
|
|
378
|
+
confidence: z.ZodNumber;
|
|
379
|
+
evidenceSummary: z.ZodString;
|
|
380
|
+
}, z.core.$strip>>;
|
|
381
|
+
}, z.core.$strip>;
|
|
382
|
+
type GenerateExplorationResponse = z.infer<typeof GenerateExplorationResponseSchema>;
|
|
383
|
+
type GenerateAnnotationsParams = GraphGenerationRequest;
|
|
384
|
+
declare const GenerateAnnotationsResponseSchema: z.ZodObject<{
|
|
385
|
+
response: z.ZodObject<{
|
|
386
|
+
message: z.ZodString;
|
|
387
|
+
steps: z.ZodArray<z.ZodString>;
|
|
388
|
+
}, z.core.$strip>;
|
|
389
|
+
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
390
|
+
}, z.core.$strip>;
|
|
391
|
+
type GenerateAnnotationsResponse = z.infer<typeof GenerateAnnotationsResponseSchema>;
|
|
317
392
|
interface StorytellingOptions {
|
|
318
393
|
excludeTitle?: boolean;
|
|
319
394
|
excludeSubtitle?: boolean;
|
|
320
395
|
excludeCaption?: boolean;
|
|
321
396
|
}
|
|
322
|
-
type GenerateGraphParams = {
|
|
323
|
-
config: GraphConfig;
|
|
324
|
-
userPrompt: string;
|
|
325
|
-
metadata?: Metadata;
|
|
397
|
+
type GenerateGraphParams = GraphGenerationRequest & {
|
|
326
398
|
storytellingOptions?: StorytellingOptions;
|
|
327
399
|
};
|
|
328
400
|
declare const GenerateGraphResponseSchema: z.ZodObject<{
|
|
329
401
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
330
402
|
response: z.ZodObject<{
|
|
331
403
|
message: z.ZodString;
|
|
332
|
-
steps: z.
|
|
404
|
+
steps: z.ZodArray<z.ZodString>;
|
|
333
405
|
}, z.core.$strip>;
|
|
334
406
|
}, z.core.$strip>;
|
|
335
407
|
type GenerateGraphResponse = z.infer<typeof GenerateGraphResponseSchema>;
|
|
@@ -374,7 +446,7 @@ declare class GraphyAiSdk {
|
|
|
374
446
|
config: _graphysdk_core_node.GraphConfig;
|
|
375
447
|
response: {
|
|
376
448
|
message: string;
|
|
377
|
-
steps
|
|
449
|
+
steps: string[];
|
|
378
450
|
};
|
|
379
451
|
}>;
|
|
380
452
|
/**
|
|
@@ -389,22 +461,25 @@ declare class GraphyAiSdk {
|
|
|
389
461
|
config: _graphysdk_core_node.GraphConfig;
|
|
390
462
|
response: {
|
|
391
463
|
message: string;
|
|
392
|
-
steps
|
|
464
|
+
steps: string[];
|
|
393
465
|
};
|
|
394
466
|
}>>>;
|
|
395
467
|
/**
|
|
396
|
-
* Generates narrative
|
|
468
|
+
* Generates a narrative for a chart. The agent updates `config.content.title`,
|
|
469
|
+
* `config.content.subtitle`, and `config.content.caption` based on the chart's
|
|
470
|
+
* data and the user prompt; the returned config is the merged result.
|
|
397
471
|
*
|
|
398
472
|
* @param data - Parameters including the chart config and a descriptive prompt.
|
|
399
473
|
* @param onProgress - Optional callback invoked with progress updates.
|
|
400
474
|
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
401
|
-
* @returns The
|
|
475
|
+
* @returns The agent response message and the updated chart config.
|
|
402
476
|
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
403
477
|
*/
|
|
404
|
-
generateNarrative(data:
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
478
|
+
generateNarrative(data: GenerateNarrativeParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
|
|
479
|
+
response: {
|
|
480
|
+
message: string;
|
|
481
|
+
};
|
|
482
|
+
config: _graphysdk_core_node.GraphConfig;
|
|
408
483
|
}>;
|
|
409
484
|
/**
|
|
410
485
|
* Streams narrative generation events via SSE.
|
|
@@ -414,10 +489,11 @@ declare class GraphyAiSdk {
|
|
|
414
489
|
* @returns An async iterator yielding {@link SSEEvent} objects.
|
|
415
490
|
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
416
491
|
*/
|
|
417
|
-
generateNarrativeStream(data:
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
492
|
+
generateNarrativeStream(data: GenerateNarrativeParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
|
|
493
|
+
response: {
|
|
494
|
+
message: string;
|
|
495
|
+
};
|
|
496
|
+
config: _graphysdk_core_node.GraphConfig;
|
|
421
497
|
}>>>;
|
|
422
498
|
/**
|
|
423
499
|
* Generates chart type and prompt suggestions for a given chart configuration.
|
|
@@ -428,10 +504,10 @@ declare class GraphyAiSdk {
|
|
|
428
504
|
* @returns Suggested chart types and data preparation prompts.
|
|
429
505
|
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
430
506
|
*/
|
|
431
|
-
generateSuggestions(data:
|
|
507
|
+
generateSuggestions(data: GenerateSuggestionsParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
|
|
432
508
|
suggestions: {
|
|
433
509
|
dataPrepPrompt: string;
|
|
434
|
-
chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "waterfall" | "table";
|
|
510
|
+
chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table";
|
|
435
511
|
summary: string;
|
|
436
512
|
}[];
|
|
437
513
|
}>;
|
|
@@ -443,16 +519,86 @@ declare class GraphyAiSdk {
|
|
|
443
519
|
* @returns An async iterator yielding {@link SSEEvent} objects.
|
|
444
520
|
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
445
521
|
*/
|
|
446
|
-
generateSuggestionsStream(data:
|
|
522
|
+
generateSuggestionsStream(data: GenerateSuggestionsParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
|
|
447
523
|
suggestions: {
|
|
448
524
|
dataPrepPrompt: string;
|
|
449
|
-
chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "waterfall" | "table";
|
|
525
|
+
chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table";
|
|
450
526
|
summary: string;
|
|
451
527
|
}[];
|
|
452
528
|
}>>>;
|
|
529
|
+
/**
|
|
530
|
+
* Runs the exploration agent against a chart's dataset.
|
|
531
|
+
*
|
|
532
|
+
* @param data - Parameters including the chart config and an optional user prompt.
|
|
533
|
+
* @param onProgress - Optional callback invoked with progress updates.
|
|
534
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
535
|
+
* @returns The agent response, the dataset findings, and the updated chart config.
|
|
536
|
+
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
537
|
+
*/
|
|
538
|
+
generateExploration(data: GenerateExplorationParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
|
|
539
|
+
response: {
|
|
540
|
+
message: string;
|
|
541
|
+
steps: string[];
|
|
542
|
+
};
|
|
543
|
+
findings: {
|
|
544
|
+
answer: string;
|
|
545
|
+
confidence: number;
|
|
546
|
+
evidenceSummary: string;
|
|
547
|
+
}[];
|
|
548
|
+
}>;
|
|
549
|
+
/**
|
|
550
|
+
* Streams exploration agent events via SSE.
|
|
551
|
+
*
|
|
552
|
+
* @param data - Parameters including the chart config and an optional user prompt.
|
|
553
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
554
|
+
* @returns An async iterator yielding {@link SSEEvent} objects.
|
|
555
|
+
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
556
|
+
*/
|
|
557
|
+
generateExplorationStream(data: GenerateExplorationParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
|
|
558
|
+
response: {
|
|
559
|
+
message: string;
|
|
560
|
+
steps: string[];
|
|
561
|
+
};
|
|
562
|
+
findings: {
|
|
563
|
+
answer: string;
|
|
564
|
+
confidence: number;
|
|
565
|
+
evidenceSummary: string;
|
|
566
|
+
}[];
|
|
567
|
+
}>>>;
|
|
568
|
+
/**
|
|
569
|
+
* Runs the annotation-tools agent to add annotations to a chart.
|
|
570
|
+
*
|
|
571
|
+
* @param data - Parameters including the chart config and an optional user prompt.
|
|
572
|
+
* @param onProgress - Optional callback invoked with progress updates.
|
|
573
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
574
|
+
* @returns The agent response message and the updated chart config (with annotations).
|
|
575
|
+
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
576
|
+
*/
|
|
577
|
+
generateAnnotations(data: GenerateAnnotationsParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
|
|
578
|
+
response: {
|
|
579
|
+
message: string;
|
|
580
|
+
steps: string[];
|
|
581
|
+
};
|
|
582
|
+
config: _graphysdk_core_node.GraphConfig;
|
|
583
|
+
}>;
|
|
584
|
+
/**
|
|
585
|
+
* Streams annotation-tools agent events via SSE.
|
|
586
|
+
*
|
|
587
|
+
* @param data - Parameters including the chart config and an optional user prompt.
|
|
588
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
589
|
+
* @returns An async iterator yielding {@link SSEEvent} objects.
|
|
590
|
+
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
591
|
+
*/
|
|
592
|
+
generateAnnotationsStream(data: GenerateAnnotationsParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
|
|
593
|
+
response: {
|
|
594
|
+
message: string;
|
|
595
|
+
steps: string[];
|
|
596
|
+
};
|
|
597
|
+
config: _graphysdk_core_node.GraphConfig;
|
|
598
|
+
}>>>;
|
|
453
599
|
private stripStorytelling;
|
|
454
600
|
private wrapStreamWithStorytellingStripping;
|
|
455
601
|
}
|
|
456
602
|
|
|
457
|
-
export { AiChartTypeEnum,
|
|
458
|
-
export type { AiChartType, ClientConfig, CompleteEvent, ErrorEvent,
|
|
603
|
+
export { AiChartTypeEnum, ExploreFindingSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, isCompleteEvent, isErrorEvent, isGraphyApiError, isProgressEvent };
|
|
604
|
+
export type { AiChartType, ClientConfig, CompleteEvent, ErrorEvent, ExploreFinding, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, Logger, Metadata, ProgressEvent, ProgressHandler, RetryConfig, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as o,__rest as i}from"tslib";import{z as n}from"zod";class s extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const a=t=>t instanceof s,l=t=>"progress"===t.type,c=t=>"complete"===t.type,g=t=>"error"===t.type;class
|
|
1
|
+
import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as o,__rest as i}from"tslib";import{z as n}from"zod";class s extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const a=t=>t instanceof s,l=t=>"progress"===t.type,c=t=>"complete"===t.type,g=t=>"error"===t.type;class d{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return l(t)}static isCompleteEvent(t){return c(t)}static isErrorEvent(t){return g(t)}stream(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,o);return this.parseSSE(t)})}fetch(r,o,i,n){return t(this,void 0,void 0,function*(){var t,a,d,h,u;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${r}`);try{const b=yield this.makeRequest(r,o,n),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var y,f=!0,m=e(this.parseSSE(b));!(t=(y=yield m.next()).done);f=!0){h=y.value,f=!1;const t=h;if(l(t)&&i&&i(t),c(t))return t.data;if(g(t)){const e=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${r} ${e}ms`,t.error),new s(t.error,{code:t.code,retryable:null!==(u=t.retryable)&&void 0!==u&&u})}}}catch(t){a={error:t}}finally{try{f||t||!(d=m.return)||(yield d.call(m))}finally{if(a)throw a.error}}const o=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${o}ms`),new s("Stream ended without completion")}return yield b.json()}catch(t){const e=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${r} ${e}ms`,t),t instanceof s)throw t;throw t}finally{const t=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${r} ${t}ms`)}})}ping(){return t(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(t){return r(this,arguments,function*(){if(!t.body)throw new s("Response body is null");const e=t.body.getReader(),r=new TextDecoder;let i="",n="",a="";try{for(;;){const{done:t,value:s}=yield o(e.read());if(t)break;i+=r.decode(s,{stream:!0});const l=i.split(/\r?\n/);i=l.pop()||"";for(const t of l)if(t.startsWith("event: "))n=t.slice(7).trim();else if(t.startsWith("data: "))a+=(a?"\n":"")+t.slice(6);else if(""===t.trim()&&a){try{const t=JSON.parse(a);let e;if("progress"===n){const r=t;e=Object.assign({type:"progress"},r)}else if("complete"===n)e={type:"complete",data:t};else{if("error"!==n){n="",a="";continue}{const r=t;e=Object.assign({type:"error"},r)}}if(yield yield o(e),"complete"===n||"error"===n)return yield o(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}n="",a=""}}}finally{e.releaseLock()}})}makeRequest(e,r,o){return t(this,arguments,void 0,function*(t,e,r,o=1,i="POST"){if(!t.startsWith("/"))throw new s("Invalid endpoint: must start with /");const n=new URL(t,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new s("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${o}/${this.retryConfig.attempts}: ${n}`);const a=new AbortController,l=setTimeout(()=>a.abort(),this.timeout),c=()=>a.abort();r&&r.addEventListener("abort",c);try{const l=yield fetch(n,Object.assign({method:i,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:a.signal},"POST"===i&&{body:JSON.stringify(e)}));if(!l.ok){const n=l.status>=500||429===l.status;let a,c=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?c=e.message:"string"==typeof e.error&&(c=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new s(c,{status:l.status,code:a,retryable:n});if(n&&o<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${n}ms (attempt ${o+1})`),yield this.sleep(n),this.makeRequest(t,e,r,o+1,i)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${c}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),l}catch(n){if(n instanceof s)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),n;if(o<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${n}ms`),yield this.sleep(n),this.makeRequest(t,e,r,o+1,i)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new s("Network error",{retryable:!0})}finally{clearTimeout(l),r&&r.removeEventListener("abort",c)}})}}const h=n.enum(["EN_GB","EN_US"]),u=n.custom(t=>null!=t&&"object"==typeof t),p=n.enum(["none","low","medium","high"]),y=n.object({maxWallClockMs:n.number().positive().optional(),maxTotalTokens:n.number().int().positive().optional(),maxCostUsd:n.number().positive().optional()}),f=n.object({callId:n.string().max(256),locale:h.optional(),storytellingEffort:p.optional().default("low"),budget:y.optional()}),m=1e4,b=n.object({config:u,userPrompt:n.string().max(1e4).optional().default(""),metadata:f.optional()}),v=n.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),w=n.object({dataPrepPrompt:n.string(),chartType:v,summary:n.string()}),$=n.object({response:n.object({message:n.string()}),config:u}),S=n.object({suggestions:n.array(w)}),j=n.object({answer:n.string().describe("Direct answer for this finding."),confidence:n.number().min(0).max(1).describe("Confidence between 0 and 1."),evidenceSummary:n.string().max(300).describe("Short prose summary of the statistical evidence.")}),O=n.object({response:n.object({message:n.string(),steps:n.array(n.string())}),findings:n.array(j)}),k=n.object({response:n.object({message:n.string(),steps:n.array(n.string())}),config:u}),C=n.object({config:u,response:n.object({message:n.string(),steps:n.array(n.string())})}),E="/api/v0";class x{constructor(t){this.client=new d(t)}generateGraph(e,r,o){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,n=i(e,["storytellingOptions"]),s=yield this.client.fetch(`${E}/generate`,n,r,o),a=C.parse(s);return this.stripStorytelling(a,t)})}generateGraphStream(e,r){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,o=i(e,["storytellingOptions"]),n=yield this.client.stream(`${E}/generate`,o,r);return this.wrapStreamWithStorytellingStripping(n,t)})}generateNarrative(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${E}/narrate`,e,r,o);return $.parse(t)})}generateNarrativeStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${E}/narrate`,e,r)})}generateSuggestions(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${E}/suggestions`,e,r,o);return S.parse(t)})}generateSuggestionsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${E}/suggestions`,e,r)})}generateExploration(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${E}/explore`,e,r,o);return O.parse(t)})}generateExplorationStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${E}/explore`,e,r)})}generateAnnotations(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${E}/annotate`,e,r,o);return k.parse(t)})}generateAnnotationsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${E}/annotate`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(t,i){return r(this,arguments,function*(){var r,n,s,a;try{for(var l,g=!0,d=e(t);!(r=(l=yield o(d.next())).done);g=!0){a=l.value,g=!1;const t=a;if(c(t)){const e=this.stripStorytelling(t.data,i);yield yield o(Object.assign(Object.assign({},t),{data:e}))}else yield yield o(t)}}catch(t){n={error:t}}finally{try{g||r||!(s=d.return)||(yield o(s.call(d)))}finally{if(n)throw n.error}}})}}export{v as AiChartTypeEnum,j as ExploreFindingSchema,k as GenerateAnnotationsResponseSchema,O as GenerateExplorationResponseSchema,C as GenerateGraphResponseSchema,$ as GenerateNarrativeResponseSchema,S as GenerateSuggestionsResponseSchema,b as GraphGenerationRequestSchema,x as GraphyAiSdk,s as GraphyApiError,y as InvocationBudgetSchema,m as MAX_USER_PROMPT_LENGTH,f as MetadataSchema,p as StorytellingEffortSchema,w as SuggestionSchema,c as isCompleteEvent,g as isErrorEvent,a as isGraphyApiError,l as isProgressEvent};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@graphysdk/agents-sdk",
|
|
3
3
|
"author": "Graphy",
|
|
4
|
-
"version": "1.3.0-beta.
|
|
4
|
+
"version": "1.3.0-beta.1776177078818",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"files": [
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
20
|
"zod": "^4.3.6",
|
|
21
|
-
"@graphysdk/core": "1.3.0-beta.
|
|
21
|
+
"@graphysdk/core": "1.3.0-beta.1776177078818"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|