@graphysdk/agents-sdk 1.1.1-beta.1773223389258 → 1.2.0-beta.1773239653763

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 CHANGED
@@ -1 +1 @@
1
- "use strict";var t=require("tslib"),e=require("zod");class r extends Error{constructor(t){super(t),this.name="GraphyApiError"}}class o{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"progress"===t.type}static isCompleteEvent(t){return"complete"===t.type}static isErrorEvent(t){return"error"===t.type}stream(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,o);return this.parseSSE(t)})}fetch(e,i,s,n){return t.__awaiter(this,void 0,void 0,function*(){var a,c,l,h;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${e}`);try{const y=yield this.makeRequest(e,i,n),f=y.headers.get("content-type");if(null==f?void 0:f.includes("text/event-stream")){try{for(var u,d=!0,p=t.__asyncValues(this.parseSSE(y));!(a=(u=yield p.next()).done);d=!0){h=u.value,d=!1;const t=h;if(o.isProgressEvent(t)&&s&&s(t),o.isCompleteEvent(t))return t.data;if(o.isErrorEvent(t)){const o=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${e} ${o}ms`,t.error),new r(t.error)}}}catch(t){c={error:t}}finally{try{d||a||!(l=p.return)||(yield l.call(p))}finally{if(c)throw c.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${e} ${i}ms`),new r("Stream ended without completion")}return yield y.json()}catch(t){const o=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${e} ${o}ms`,t),t instanceof r)throw t;throw t}finally{const t=Date.now()-g;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 o=e.body.getReader(),i=new TextDecoder;let s="",n="",a="";try{for(;;){const{done:e,value:r}=yield t.__await(o.read());if(e)break;s+=i.decode(r,{stream:!0});const c=s.split(/\r?\n/);s=c.pop()||"";for(const e of c)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{o.releaseLock()}})}makeRequest(e,o,i){return t.__awaiter(this,arguments,void 0,function*(t,e,o,i=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 ${i}/${this.retryConfig.attempts}: ${n}`);const a=new AbortController,c=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();o&&o.addEventListener("abort",l);try{const c=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(!c.ok){const n=c.status>=500||429===c.status;let a=`HTTP ${c.status}`;try{const t=yield c.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?a=e.message:"string"==typeof e.error&&(a=e.error)}}catch(t){}const l=new r(a);if(n&&i<this.retryConfig.attempts&&!(null==o?void 0:o.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(t,e,o,i+1,s)}throw this.logger.error(`${this.tag} Request failed: ${t} (${c.status}) - ${a}`),l}return this.logger.debug(`${this.tag} Connected: ${t}`),c}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(i<this.retryConfig.attempts&&!(null==o?void 0:o.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${r}ms`),yield this.sleep(r),this.makeRequest(t,e,o,i+1,s)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new r("Network error")}finally{clearTimeout(c),o&&o.removeEventListener("abort",l)}})}}const i=e.z.enum(["EN_GB","EN_US"]),s=e.z.custom(t=>null!=t&&"object"==typeof t);e.z.object({callId:e.z.string(),locale:i.optional()});const n=e.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),a=e.z.object({dataPrepPrompt:e.z.string(),chartType:n,summary:e.z.string()}),c=e.z.object({title:e.z.string(),subtitle:e.z.string(),caption:e.z.string().nullable()}),l=e.z.object({config:s,suggestions:e.z.array(a),description:e.z.string().nullable()}),h=e.z.object({config:s,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string()).optional()})}),g="/api/v0";exports.AiChartTypeEnum=n,exports.GenerateGraphNarrativeResponseSchema=c,exports.GenerateGraphResponseSchema=h,exports.GenerateGraphSuggestionsResponseSchema=l,exports.GraphyAiSdk=class{constructor(t){this.client=new o(t)}generateGraph(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${g}/generate`,e,r,o);return h.parse(t)})}generateGraphStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${g}/generate`,e,r)})}generateNarrative(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${g}/narrative`,e,r,o);return c.parse(t)})}generateNarrativeStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${g}/narrative`,e,r)})}generateSuggestions(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${g}/suggestions`,e,r,o);return l.parse(t)})}generateSuggestionsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${g}/suggestions`,e,r)})}},exports.GraphyApiError=r,exports.SuggestionSchema=a;
1
+ "use strict";var t=require("tslib"),e=require("zod");class r extends Error{constructor(t){super(t),this.name="GraphyApiError"}}class i{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"progress"===t.type}static isCompleteEvent(t){return"complete"===t.type}static isErrorEvent(t){return"error"===t.type}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,o,s){return t.__awaiter(this,void 0,void 0,function*(){var a,l,c,h;const u=Date.now();this.logger.debug(`${this.tag} Fetch: ${e}`);try{const y=yield this.makeRequest(e,n,s),f=y.headers.get("content-type");if(null==f?void 0:f.includes("text/event-stream")){try{for(var g,p=!0,d=t.__asyncValues(this.parseSSE(y));!(a=(g=yield d.next()).done);p=!0){h=g.value,p=!1;const t=h;if(i.isProgressEvent(t)&&o&&o(t),i.isCompleteEvent(t))return t.data;if(i.isErrorEvent(t)){const i=Date.now()-u;throw this.logger.error(`${this.tag} Server error: ${e} ${i}ms`,t.error),new r(t.error)}}}catch(t){l={error:t}}finally{try{p||a||!(c=d.return)||(yield c.call(d))}finally{if(l)throw l.error}}const n=Date.now()-u;throw this.logger.error(`${this.tag} Stream incomplete: ${e} ${n}ms`),new r("Stream ended without completion")}return yield y.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(),n=new TextDecoder;let o="",s="",a="";try{for(;;){const{done:e,value:r}=yield t.__await(i.read());if(e)break;o+=n.decode(r,{stream:!0});const l=o.split(/\r?\n/);o=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,n){return t.__awaiter(this,arguments,void 0,function*(t,e,i,n=1,o="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 ${n}/${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:o,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"===o&&{body:JSON.stringify(e)}));if(!l.ok){const s=l.status>=500||429===l.status;let a=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?a=e.message:"string"==typeof e.error&&(a=e.error)}}catch(t){}const c=new r(a);if(s&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${r}ms (attempt ${n+1})`),yield this.sleep(r),this.makeRequest(t,e,i,n+1,o)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${a}`),c}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(n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${r}ms`),yield this.sleep(r),this.makeRequest(t,e,i,n+1,o)}throw this.logger.error(`${this.tag} Network error: ${t}`,s),new r("Network error")}finally{clearTimeout(l),i&&i.removeEventListener("abort",c)}})}}const n=e.z.enum(["EN_GB","EN_US"]),o=e.z.custom(t=>null!=t&&"object"==typeof t),s=e.z.enum(["none","low","medium","high"]);e.z.object({callId:e.z.string(),locale:n.optional(),storytellingEffort:s.optional().default("low")});const a=e.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),l=e.z.object({dataPrepPrompt:e.z.string(),chartType:a,summary:e.z.string()}),c=e.z.object({title:e.z.string(),subtitle:e.z.string(),caption:e.z.string().nullable()}),h=e.z.object({config:o,suggestions:e.z.array(l),description:e.z.string().nullable()}),u=e.z.object({title:e.z.string().nullish(),subtitle:e.z.string().nullish(),caption:e.z.string().nullish()}),g=e.z.object({config:o,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string()).optional()}),narrative:u.nullish()}),p="/api/v0";exports.AiChartTypeEnum=a,exports.ChartNarrativeSchema=u,exports.GenerateGraphNarrativeResponseSchema=c,exports.GenerateGraphResponseSchema=g,exports.GenerateGraphSuggestionsResponseSchema=h,exports.GraphyAiSdk=class{constructor(t){this.client=new i(t)}generateGraph(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const{narrativeOptions:n}=e,o=t.__rest(e,["narrativeOptions"]),s=yield this.client.fetch(`${p}/generate`,o,r,i),a=g.parse(s);return this.stripNarrative(a,n)})}generateGraphStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){const{narrativeOptions:i}=e,n=t.__rest(e,["narrativeOptions"]),o=yield this.client.stream(`${p}/generate`,n,r);return this.wrapStreamWithNarrativeStripping(o,i)})}generateNarrative(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${p}/narrative`,e,r,i);return c.parse(t)})}generateNarrativeStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${p}/narrative`,e,r)})}generateSuggestions(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${p}/suggestions`,e,r,i);return h.parse(t)})}generateSuggestionsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${p}/suggestions`,e,r)})}stripNarrative(t,e){return e&&t.narrative?Object.assign(Object.assign({},t),{narrative:{title:e.excludeTitle?null:t.narrative.title,subtitle:e.excludeSubtitle?null:t.narrative.subtitle,caption:e.excludeCaption?null:t.narrative.caption}}):t}wrapStreamWithNarrativeStripping(e,r){return t.__asyncGenerator(this,arguments,function*(){var n,o,s,a;try{for(var l,c=!0,h=t.__asyncValues(e);!(n=(l=yield t.__await(h.next())).done);c=!0){a=l.value,c=!1;const e=a;if(i.isCompleteEvent(e)){const i=this.stripNarrative(e.data,r);yield yield t.__await(Object.assign(Object.assign({},e),{data:i}))}else yield yield t.__await(e)}}catch(t){o={error:t}}finally{try{c||n||!(s=h.return)||(yield t.__await(s.call(h)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=r,exports.StorytellingEffortSchema=s,exports.SuggestionSchema=l;
package/dist/index.d.ts CHANGED
@@ -45,12 +45,25 @@ type JsonArray = JsonValue[];
45
45
 
46
46
  type ProgressHandler = (progress: ProgressEvent) => void;
47
47
 
48
+ declare const StorytellingEffortSchema: z.ZodEnum<{
49
+ none: "none";
50
+ low: "low";
51
+ medium: "medium";
52
+ high: "high";
53
+ }>;
54
+ type StorytellingEffort = z.infer<typeof StorytellingEffortSchema>;
48
55
  declare const MetadataSchema: z.ZodObject<{
49
56
  callId: z.ZodString;
50
57
  locale: z.ZodOptional<z.ZodEnum<{
51
58
  EN_GB: "EN_GB";
52
59
  EN_US: "EN_US";
53
60
  }>>;
61
+ storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
62
+ none: "none";
63
+ low: "low";
64
+ medium: "medium";
65
+ high: "high";
66
+ }>>>;
54
67
  }, z.core.$strip>;
55
68
  type Metadata = z.infer<typeof MetadataSchema>;
56
69
  declare const AiChartTypeEnum: z.ZodEnum<{
@@ -140,17 +153,34 @@ declare const GenerateGraphSuggestionsResponseSchema: z.ZodObject<{
140
153
  description: z.ZodNullable<z.ZodString>;
141
154
  }, z.core.$strip>;
142
155
  type GenerateGraphSuggestionsResponse = z.infer<typeof GenerateGraphSuggestionsResponseSchema>;
156
+ interface NarrativeOptions {
157
+ excludeTitle?: boolean;
158
+ excludeSubtitle?: boolean;
159
+ excludeCaption?: boolean;
160
+ }
143
161
  type GenerateGraphParams = {
144
162
  config: GraphConfig;
145
163
  userPrompt: string;
146
164
  metadata?: Metadata;
165
+ narrativeOptions?: NarrativeOptions;
147
166
  };
167
+ declare const ChartNarrativeSchema: z.ZodObject<{
168
+ title: z.ZodOptional<z.ZodNullable<z.ZodString>>;
169
+ subtitle: z.ZodOptional<z.ZodNullable<z.ZodString>>;
170
+ caption: z.ZodOptional<z.ZodNullable<z.ZodString>>;
171
+ }, z.core.$strip>;
172
+ type ChartNarrative = z.infer<typeof ChartNarrativeSchema>;
148
173
  declare const GenerateGraphResponseSchema: z.ZodObject<{
149
174
  config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
150
175
  response: z.ZodObject<{
151
176
  message: z.ZodString;
152
177
  steps: z.ZodOptional<z.ZodArray<z.ZodString>>;
153
178
  }, z.core.$strip>;
179
+ narrative: z.ZodOptional<z.ZodNullable<z.ZodObject<{
180
+ title: z.ZodOptional<z.ZodNullable<z.ZodString>>;
181
+ subtitle: z.ZodOptional<z.ZodNullable<z.ZodString>>;
182
+ caption: z.ZodOptional<z.ZodNullable<z.ZodString>>;
183
+ }, z.core.$strip>>>;
154
184
  }, z.core.$strip>;
155
185
  type GenerateGraphResponse = z.infer<typeof GenerateGraphResponseSchema>;
156
186
 
@@ -163,6 +193,11 @@ declare class GraphyAiSdk {
163
193
  message: string;
164
194
  steps?: string[] | undefined;
165
195
  };
196
+ narrative?: {
197
+ title?: string | null | undefined;
198
+ subtitle?: string | null | undefined;
199
+ caption?: string | null | undefined;
200
+ } | null | undefined;
166
201
  }>;
167
202
  generateGraphStream(data: GenerateGraphParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
168
203
  config: _graphysdk_core_node.GraphConfig;
@@ -170,6 +205,11 @@ declare class GraphyAiSdk {
170
205
  message: string;
171
206
  steps?: string[] | undefined;
172
207
  };
208
+ narrative?: {
209
+ title?: string | null | undefined;
210
+ subtitle?: string | null | undefined;
211
+ caption?: string | null | undefined;
212
+ } | null | undefined;
173
213
  }>>>;
174
214
  generateNarrative(data: GenerateGraphNarrativeParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
175
215
  title: string;
@@ -199,11 +239,13 @@ declare class GraphyAiSdk {
199
239
  }[];
200
240
  description: string | null;
201
241
  }>>>;
242
+ private stripNarrative;
243
+ private wrapStreamWithNarrativeStripping;
202
244
  }
203
245
 
204
246
  declare class GraphyApiError extends Error {
205
247
  constructor(message: string);
206
248
  }
207
249
 
208
- export { AiChartTypeEnum, GenerateGraphNarrativeResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GraphyAiSdk, GraphyApiError, SuggestionSchema };
209
- export type { AiChartType, ClientConfig, CompleteEvent, ErrorEvent, GenerateGraphNarrativeParams, GenerateGraphNarrativeResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, Logger, ProgressEvent, ProgressHandler, RetryConfig, SSEEvent, Suggestion };
250
+ export { AiChartTypeEnum, ChartNarrativeSchema, GenerateGraphNarrativeResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GraphyAiSdk, GraphyApiError, StorytellingEffortSchema, SuggestionSchema };
251
+ export type { AiChartType, ChartNarrative, ClientConfig, CompleteEvent, ErrorEvent, GenerateGraphNarrativeParams, GenerateGraphNarrativeResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, Logger, NarrativeOptions, ProgressEvent, ProgressHandler, RetryConfig, SSEEvent, StorytellingEffort, Suggestion };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as o}from"tslib";import{z as i}from"zod";class s extends Error{constructor(t){super(t),this.name="GraphyApiError"}}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"progress"===t.type}static isCompleteEvent(t){return"complete"===t.type}static isErrorEvent(t){return"error"===t.type}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,a){return t(this,void 0,void 0,function*(){var t,l,c,h;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${r}`);try{const f=yield this.makeRequest(r,o,a),y=f.headers.get("content-type");if(null==y?void 0:y.includes("text/event-stream")){try{for(var u,d=!0,p=e(this.parseSSE(f));!(t=(u=yield p.next()).done);d=!0){h=u.value,d=!1;const t=h;if(n.isProgressEvent(t)&&i&&i(t),n.isCompleteEvent(t))return t.data;if(n.isErrorEvent(t)){const e=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${r} ${e}ms`,t.error),new s(t.error)}}}catch(t){l={error:t}}finally{try{d||t||!(c=p.return)||(yield c.call(p))}finally{if(l)throw l.error}}const o=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${o}ms`),new s("Stream ended without completion")}return yield f.json()}catch(t){const e=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${r} ${e}ms`,t),t instanceof s)throw t;throw t}finally{const t=Date.now()-g;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=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?a=e.message:"string"==typeof e.error&&(a=e.error)}}catch(t){}const c=new s(a);if(n&&o<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${s}ms (attempt ${o+1})`),yield this.sleep(s),this.makeRequest(t,e,r,o+1,i)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${a}`),c}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 s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${s}ms`),yield this.sleep(s),this.makeRequest(t,e,r,o+1,i)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new s("Network error")}finally{clearTimeout(l),r&&r.removeEventListener("abort",c)}})}}const a=i.enum(["EN_GB","EN_US"]),l=i.custom(t=>null!=t&&"object"==typeof t);i.object({callId:i.string(),locale:a.optional()});const c=i.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),h=i.object({dataPrepPrompt:i.string(),chartType:c,summary:i.string()}),g=i.object({title:i.string(),subtitle:i.string(),caption:i.string().nullable()}),u=i.object({config:l,suggestions:i.array(h),description:i.string().nullable()}),d=i.object({config:l,response:i.object({message:i.string(),steps:i.array(i.string()).optional()})}),p="/api/v0";class f{constructor(t){this.client=new n(t)}generateGraph(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${p}/generate`,e,r,o);return d.parse(t)})}generateGraphStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${p}/generate`,e,r)})}generateNarrative(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${p}/narrative`,e,r,o);return g.parse(t)})}generateNarrativeStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${p}/narrative`,e,r)})}generateSuggestions(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${p}/suggestions`,e,r,o);return u.parse(t)})}generateSuggestionsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${p}/suggestions`,e,r)})}}export{c as AiChartTypeEnum,g as GenerateGraphNarrativeResponseSchema,d as GenerateGraphResponseSchema,u as GenerateGraphSuggestionsResponseSchema,f as GraphyAiSdk,s as GraphyApiError,h as SuggestionSchema};
1
+ import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as i,__rest as o}from"tslib";import{z as n}from"zod";class s extends Error{constructor(t){super(t),this.name="GraphyApiError"}}class a{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"progress"===t.type}static isCompleteEvent(t){return"complete"===t.type}static isErrorEvent(t){return"error"===t.type}stream(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,i);return this.parseSSE(t)})}fetch(r,i,o,n){return t(this,void 0,void 0,function*(){var t,l,c,h;const u=Date.now();this.logger.debug(`${this.tag} Fetch: ${r}`);try{const f=yield this.makeRequest(r,i,n),y=f.headers.get("content-type");if(null==y?void 0:y.includes("text/event-stream")){try{for(var g,d=!0,p=e(this.parseSSE(f));!(t=(g=yield p.next()).done);d=!0){h=g.value,d=!1;const t=h;if(a.isProgressEvent(t)&&o&&o(t),a.isCompleteEvent(t))return t.data;if(a.isErrorEvent(t)){const e=Date.now()-u;throw this.logger.error(`${this.tag} Server error: ${r} ${e}ms`,t.error),new s(t.error)}}}catch(t){l={error:t}}finally{try{d||t||!(c=p.return)||(yield c.call(p))}finally{if(l)throw l.error}}const i=Date.now()-u;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${i}ms`),new s("Stream ended without completion")}return yield f.json()}catch(t){const e=Date.now()-u;if(this.logger.error(`${this.tag} Fetch failed: ${r} ${e}ms`,t),t instanceof s)throw t;throw t}finally{const t=Date.now()-u;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 o="",n="",a="";try{for(;;){const{done:t,value:s}=yield i(e.read());if(t)break;o+=r.decode(s,{stream:!0});const l=o.split(/\r?\n/);o=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 i(e),"complete"===n||"error"===n)return yield i(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}n="",a=""}}}finally{e.releaseLock()}})}makeRequest(e,r,i){return t(this,arguments,void 0,function*(t,e,r,i=1,o="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 ${i}/${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:o,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"===o&&{body:JSON.stringify(e)}));if(!l.ok){const n=l.status>=500||429===l.status;let a=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?a=e.message:"string"==typeof e.error&&(a=e.error)}}catch(t){}const c=new s(a);if(n&&i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${n}ms (attempt ${i+1})`),yield this.sleep(n),this.makeRequest(t,e,r,i+1,o)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${a}`),c}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(i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${n}ms`),yield this.sleep(n),this.makeRequest(t,e,r,i+1,o)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new s("Network error")}finally{clearTimeout(l),r&&r.removeEventListener("abort",c)}})}}const l=n.enum(["EN_GB","EN_US"]),c=n.custom(t=>null!=t&&"object"==typeof t),h=n.enum(["none","low","medium","high"]);n.object({callId:n.string(),locale:l.optional(),storytellingEffort:h.optional().default("low")});const u=n.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),g=n.object({dataPrepPrompt:n.string(),chartType:u,summary:n.string()}),d=n.object({title:n.string(),subtitle:n.string(),caption:n.string().nullable()}),p=n.object({config:c,suggestions:n.array(g),description:n.string().nullable()}),f=n.object({title:n.string().nullish(),subtitle:n.string().nullish(),caption:n.string().nullish()}),y=n.object({config:c,response:n.object({message:n.string(),steps:n.array(n.string()).optional()}),narrative:f.nullish()}),m="/api/v0";class v{constructor(t){this.client=new a(t)}generateGraph(e,r,i){return t(this,void 0,void 0,function*(){const{narrativeOptions:t}=e,n=o(e,["narrativeOptions"]),s=yield this.client.fetch(`${m}/generate`,n,r,i),a=y.parse(s);return this.stripNarrative(a,t)})}generateGraphStream(e,r){return t(this,void 0,void 0,function*(){const{narrativeOptions:t}=e,i=o(e,["narrativeOptions"]),n=yield this.client.stream(`${m}/generate`,i,r);return this.wrapStreamWithNarrativeStripping(n,t)})}generateNarrative(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${m}/narrative`,e,r,i);return d.parse(t)})}generateNarrativeStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${m}/narrative`,e,r)})}generateSuggestions(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${m}/suggestions`,e,r,i);return p.parse(t)})}generateSuggestionsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${m}/suggestions`,e,r)})}stripNarrative(t,e){return e&&t.narrative?Object.assign(Object.assign({},t),{narrative:{title:e.excludeTitle?null:t.narrative.title,subtitle:e.excludeSubtitle?null:t.narrative.subtitle,caption:e.excludeCaption?null:t.narrative.caption}}):t}wrapStreamWithNarrativeStripping(t,o){return r(this,arguments,function*(){var r,n,s,l;try{for(var c,h=!0,u=e(t);!(r=(c=yield i(u.next())).done);h=!0){l=c.value,h=!1;const t=l;if(a.isCompleteEvent(t)){const e=this.stripNarrative(t.data,o);yield yield i(Object.assign(Object.assign({},t),{data:e}))}else yield yield i(t)}}catch(t){n={error:t}}finally{try{h||r||!(s=u.return)||(yield i(s.call(u)))}finally{if(n)throw n.error}}})}}export{u as AiChartTypeEnum,f as ChartNarrativeSchema,d as GenerateGraphNarrativeResponseSchema,y as GenerateGraphResponseSchema,p as GenerateGraphSuggestionsResponseSchema,v as GraphyAiSdk,s as GraphyApiError,h as StorytellingEffortSchema,g as SuggestionSchema};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@graphysdk/agents-sdk",
3
3
  "author": "Graphy",
4
- "version": "1.1.1-beta.1773223389258",
4
+ "version": "1.2.0-beta.1773239653763",
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.1.1-beta.1773223389258"
21
+ "@graphysdk/core": "1.2.0-beta.1773239653763"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@rollup/plugin-commonjs": "^28.0.6",