@graphysdk/agents-sdk 1.3.0-beta.1776247596231 → 1.3.0-beta.1776786180132
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 +370 -27
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
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 o=t=>"progress"===t.type,i=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 o(t)}static isCompleteEvent(t){return i(t)}static isErrorEvent(t){return n(t)}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,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(o(t)&&a&&a(t),i(t))return t.data;if(n(t)){const o=Date.now()-u;throw this.logger.error(`${this.tag} Server error: ${e} ${o}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 o=Date.now()-u;if(this.logger.error(`${this.tag} Fetch failed: ${e} ${o}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 o=e.body.getReader(),i=new TextDecoder;let n="",s="",a="";try{for(;;){const{done:e,value:r}=yield t.__await(o.read());if(e)break;n+=i.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{o.releaseLock()}})}makeRequest(e,o,i){return t.__awaiter(this,arguments,void 0,function*(t,e,o,i=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 ${i}/${this.retryConfig.attempts}: ${s}`);const a=new AbortController,l=setTimeout(()=>a.abort(),this.timeout),c=()=>a.abort();o&&o.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&&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,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(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,n)}throw this.logger.error(`${this.tag} Network error: ${t}`,s),new r("Network error",{retryable:!0})}finally{clearTimeout(l),o&&o.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=d.extend({maxSuggestionCount:e.z.number().int().min(1).max(4).optional()}),u=e.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),y=e.z.object({dataPrepPrompt:e.z.string(),chartType:u,summary:e.z.string()}),m=e.z.object({response:e.z.object({message:e.z.string()}),config:l}),f=e.z.object({suggestions:e.z.array(y)}),b=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.")}),w=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),findings:e.z.array(b)}),v=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),config:l}),_=e.z.object({config:l,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())})}),S="/api/v0";exports.AiChartTypeEnum=u,exports.ExploreFindingSchema=b,exports.GenerateAnnotationsResponseSchema=v,exports.GenerateExplorationResponseSchema=w,exports.GenerateGraphResponseSchema=_,exports.GenerateNarrativeResponseSchema=m,exports.GenerateSuggestionsParamsSchema=p,exports.GenerateSuggestionsResponseSchema=f,exports.GraphGenerationRequestSchema=d,exports.GraphyAiSdk=class{constructor(t){this.client=new s(t)}generateGraph(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=e,n=t.__rest(e,["storytellingOptions"]),s=yield this.client.fetch(`${S}/generate`,n,r,o),a=_.parse(s);return this.stripStorytelling(a,i)})}generateGraphStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:o}=e,i=t.__rest(e,["storytellingOptions"]),n=yield this.client.stream(`${S}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(n,o)})}generateNarrative(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${S}/narrate`,e,r,o);return m.parse(t)})}generateNarrativeStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${S}/narrate`,e,r)})}generateSuggestions(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${S}/suggestions`,e,r,o);return f.parse(t)})}generateSuggestionsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${S}/suggestions`,e,r)})}generateExploration(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${S}/explore`,e,r,o);return w.parse(t)})}generateExplorationStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${S}/explore`,e,r)})}generateAnnotations(e,r,o){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${S}/annotate`,e,r,o);return v.parse(t)})}generateAnnotationsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${S}/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 o,n,s,a;try{for(var l,c=!0,g=t.__asyncValues(e);!(o=(l=yield t.__await(g.next())).done);c=!0){a=l.value,c=!1;const e=a;if(i(e)){const o=this.stripStorytelling(e.data,r);yield yield t.__await(Object.assign(Object.assign({},e),{data:o}))}else yield yield t.__await(e)}}catch(t){n={error:t}}finally{try{c||o||!(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=y,exports.isCompleteEvent=i,exports.isErrorEvent=n,exports.isGraphyApiError=t=>t instanceof r,exports.isProgressEvent=o;
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("zod");class r extends Error{constructor(e,t){var r;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(r=null==t?void 0:t.retryable)&&void 0!==r&&r}}const i=e=>"progress"===e.type,n=e=>"complete"===e.type,o=e=>"error"===e.type;class s{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return i(e)}static isCompleteEvent(e){return n(e)}static isErrorEvent(e){return o(e)}stream(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,i);return this.parseSSE(e)})}fetch(t,s,a,c){return e.__awaiter(this,void 0,void 0,function*(){var l,g,d,h,u;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,s,c),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var m,y=!0,f=e.__asyncValues(this.parseSSE(b));!(l=(m=yield f.next()).done);y=!0){h=m.value,y=!1;const e=h;if(i(e)&&a&&a(e),n(e))return e.data;if(o(e)){const i=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${t} ${i}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){g={error:e}}finally{try{y||l||!(d=f.return)||(yield d.call(f))}finally{if(g)throw g.error}}const s=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${s}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const i=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${i}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new r("Response body is null");const i=t.body.getReader(),n=new TextDecoder;let o="",s="",a="";try{for(;;){const{done:t,value:r}=yield e.__await(i.read());if(t)break;o+=n.decode(r,{stream:!0});const c=o.split(/\r?\n/);o=c.pop()||"";for(const t of c)if(t.startsWith("event: "))s=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 r;if("progress"===s){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===s)r={type:"complete",data:t};else if("error"===s){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===s){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==s){s="",a="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",a)}s="",a=""}}}finally{i.releaseLock()}})}makeRequest(t,i,n){return e.__awaiter(this,arguments,void 0,function*(e,t,i,n=1,o="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const s=new URL(e,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,c=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();i&&i.addEventListener("abort",l);try{const c=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(t)}));if(!c.ok){const s=c.status>=500||429===c.status;let a,l=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?l=t.message:"string"==typeof t.error&&(l=t.error),"string"==typeof t.code&&(a=t.code)}}catch(e){}const g=new r(l,{status:c.status,code:a,retryable:s});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 ${e} in ${r}ms (attempt ${n+1})`),yield this.sleep(r),this.makeRequest(e,t,i,n+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),g}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(s){if(s instanceof r)throw s;if(s instanceof Error&&"AbortError"===s.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),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 ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,i,n+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new r("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const a=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),l=t.z.enum(["none","low","medium","high"]),g=t.z.object({maxWallClockMs:t.z.number().positive().optional(),maxTotalTokens:t.z.number().int().positive().optional(),maxCostUsd:t.z.number().positive().optional()}),d=t.z.object({callId:t.z.string().max(256),locale:a.optional(),storytellingEffort:l.optional().default("low"),budget:g.optional()}),h=t.z.object({config:c,userPrompt:t.z.string().max(1e4).optional().default(""),metadata:d.optional()}),u=h.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),p=t.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),m=t.z.object({dataPrepPrompt:t.z.string(),chartType:p,summary:t.z.string()}),y=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),f=t.z.object({suggestions:t.z.array(m)}),b=t.z.enum(["comparison","relationship","distribution","composition"]),v=t.z.object({finding:t.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:t.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:t.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:t.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:t.z.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:b.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),w=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(v).describe("Child findings, sorted by quadrant score desc.")}),z=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(w)}),x=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),_=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),S=t.z.enum(["high","medium","low"]),$=t.z.object({confidence:S,needsUserInput:t.z.boolean(),warnings:t.z.array(t.z.string()),cellConfidence:t.z.array(t.z.object({rowIndex:t.z.number().int().nonnegative(),columnKey:t.z.string(),confidence:S,quote:t.z.string().optional()})).optional()}),E=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),j=5e5,C=t.z.object({sourceText:t.z.string().min(1).max(j),metadata:d.optional()}),O=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:$.nullable(),lastAccuracyEvaluation:E.optional()}),R=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),k="/api/v0";exports.AiChartTypeEnum=p,exports.ChartFamilySchema=b,exports.ExploreFindingSchema=v,exports.ExploreStorySchema=w,exports.ExtractAccuracyEvaluationSchema=E,exports.ExtractConfidenceSchema=S,exports.ExtractFromProseParamsSchema=C,exports.ExtractFromProseResponseSchema=O,exports.ExtractMetaSchema=$,exports.GenerateAnnotationsResponseSchema=x,exports.GenerateExplorationResponseSchema=z,exports.GenerateGraphResponseSchema=R,exports.GenerateMutationResponseSchema=_,exports.GenerateNarrativeResponseSchema=y,exports.GenerateSuggestionsParamsSchema=u,exports.GenerateSuggestionsResponseSchema=f,exports.GraphGenerationRequestSchema=h,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:n}=t,o=e.__rest(t,["storytellingOptions"]),s=yield this.client.fetch(`${k}/generate`,o,r,i),a=R.parse(s);return this.stripStorytelling(a,n)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,n=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${k}/generate`,n,r);return this.wrapStreamWithStorytellingStripping(o,i)})}generateNarrative(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${k}/narrate`,t,r,i);return y.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${k}/narrate`,t,r)})}generateSuggestions(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${k}/suggestions`,t,r,i);return f.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${k}/suggestions`,t,r)})}generateExploration(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${k}/explore`,t,r,i);return z.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${k}/explore`,t,r)})}generateAnnotations(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${k}/annotate`,t,r,i);return x.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${k}/annotate`,t,r)})}generateMutation(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${k}/mutate`,t,r,i);return _.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${k}/mutate`,t,r)})}extractFromProse(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${k}/extract`,t,r,i);return O.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${k}/extract`,t,r)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,r){return e.__asyncGenerator(this,arguments,function*(){var i,o,s,a;try{for(var c,l=!0,g=e.__asyncValues(t);!(i=(c=yield e.__await(g.next())).done);l=!0){a=c.value,l=!1;const t=a;if(n(t)){const i=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:i}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||i||!(s=g.return)||(yield e.__await(s.call(g)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.MAX_SOURCE_TEXT_LENGTH=j,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=d,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=m,exports.isCompleteEvent=n,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=i,exports.isReasoningEvent=e=>"reasoning"===e.type;
|
package/dist/index.d.ts
CHANGED
|
@@ -4,15 +4,22 @@ import { z } from 'zod';
|
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* A progress update emitted during an SSE stream.
|
|
7
|
-
*
|
|
7
|
+
*
|
|
8
|
+
* Emitted from two sources:
|
|
9
|
+
* - **Handler kickoff** (e.g. `"Generating..."`) — only carries `message`.
|
|
10
|
+
* - **Agent/tool loop** (via `emitProgress()`) — also carries `agentId`, `executionId`, `iteration`, and optional `metadata`.
|
|
8
11
|
*/
|
|
9
12
|
interface ProgressEvent {
|
|
10
13
|
/** Discriminant literal identifying this as a progress event. */
|
|
11
14
|
type: 'progress';
|
|
12
|
-
/**
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
|
|
15
|
+
/** Human-readable progress message. */
|
|
16
|
+
message: string;
|
|
17
|
+
/** Identifier of the agent emitting the progress (only on agent-emitted events). */
|
|
18
|
+
agentId?: string;
|
|
19
|
+
/** Identifier for the top-level invocation (only on agent-emitted events). */
|
|
20
|
+
executionId?: string;
|
|
21
|
+
/** Agent loop iteration (only on agent-emitted events). */
|
|
22
|
+
iteration?: number;
|
|
16
23
|
/** Optional arbitrary metadata attached by the server. */
|
|
17
24
|
metadata?: Record<string, JsonValue>;
|
|
18
25
|
}
|
|
@@ -39,12 +46,38 @@ interface ErrorEvent {
|
|
|
39
46
|
/** Whether the consumer should retry the request. */
|
|
40
47
|
retryable?: boolean;
|
|
41
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* A preview of the current agent state, emitted incrementally while work is in progress.
|
|
51
|
+
*
|
|
52
|
+
* The business payload is spread at the top level — its shape depends on the endpoint
|
|
53
|
+
* (e.g. `{ config }` for generate/mutate, `{ stories }` for explore).
|
|
54
|
+
*/
|
|
55
|
+
interface PreviewEvent {
|
|
56
|
+
/** Agent-specific fields are spread at the top level. */
|
|
57
|
+
[key: string]: unknown;
|
|
58
|
+
/** Discriminant literal identifying this as a preview event. */
|
|
59
|
+
type: 'preview';
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A reasoning/thinking message emitted by an agent or tool as it works.
|
|
63
|
+
*/
|
|
64
|
+
interface ReasoningEvent {
|
|
65
|
+
/** Discriminant literal identifying this as a reasoning event. */
|
|
66
|
+
type: 'reasoning';
|
|
67
|
+
/** Identifier of the agent emitting the reasoning. */
|
|
68
|
+
agentId: string;
|
|
69
|
+
/** Identifier for the top-level invocation this event belongs to. */
|
|
70
|
+
executionId: string;
|
|
71
|
+
/** The reasoning message produced by the model. */
|
|
72
|
+
message: string;
|
|
73
|
+
}
|
|
42
74
|
/**
|
|
43
75
|
* Discriminated union of all SSE event types emitted during streaming operations.
|
|
44
|
-
* Use the type guards {@link isProgressEvent}, {@link isCompleteEvent},
|
|
45
|
-
* {@link isErrorEvent}
|
|
76
|
+
* Use the type guards {@link isProgressEvent}, {@link isCompleteEvent},
|
|
77
|
+
* {@link isErrorEvent}, {@link isPreviewEvent}, and {@link isReasoningEvent}
|
|
78
|
+
* to narrow the event type.
|
|
46
79
|
*/
|
|
47
|
-
type SSEEvent<T> = ProgressEvent | CompleteEvent<T> | ErrorEvent;
|
|
80
|
+
type SSEEvent<T> = ProgressEvent | CompleteEvent<T> | ErrorEvent | PreviewEvent | ReasoningEvent;
|
|
48
81
|
/**
|
|
49
82
|
* Logger interface for SDK diagnostic output.
|
|
50
83
|
* Falls back to `console` methods when not provided in {@link ClientConfig}.
|
|
@@ -162,13 +195,13 @@ declare const isGraphyApiError: (error: unknown) => error is GraphyApiError;
|
|
|
162
195
|
* Narrows an SSE event to a {@link ProgressEvent}.
|
|
163
196
|
*
|
|
164
197
|
* @param event - The SSE event to check.
|
|
165
|
-
* @returns `true` if the event is a progress event
|
|
198
|
+
* @returns `true` if the event is a progress event.
|
|
166
199
|
*
|
|
167
200
|
* @example
|
|
168
201
|
* ```typescript
|
|
169
202
|
* for await (const event of stream) {
|
|
170
203
|
* if (isProgressEvent(event)) {
|
|
171
|
-
*
|
|
204
|
+
* log(event.message);
|
|
172
205
|
* }
|
|
173
206
|
* }
|
|
174
207
|
* ```
|
|
@@ -206,6 +239,39 @@ declare const isCompleteEvent: <T>(event: SSEEvent<T>) => event is CompleteEvent
|
|
|
206
239
|
* ```
|
|
207
240
|
*/
|
|
208
241
|
declare const isErrorEvent: <T>(event: SSEEvent<T>) => event is ErrorEvent;
|
|
242
|
+
/**
|
|
243
|
+
* Narrows an SSE event to a {@link PreviewEvent} containing an incremental agent state preview.
|
|
244
|
+
*
|
|
245
|
+
* @param event - The SSE event to check.
|
|
246
|
+
* @returns `true` if the event is a preview event.
|
|
247
|
+
*
|
|
248
|
+
* @example
|
|
249
|
+
* ```typescript
|
|
250
|
+
* for await (const event of stream) {
|
|
251
|
+
* if (isPreviewEvent(event)) {
|
|
252
|
+
* // Business data is spread at the top level, e.g. event.config or event.stories
|
|
253
|
+
* renderPartialState(event);
|
|
254
|
+
* }
|
|
255
|
+
* }
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
258
|
+
declare const isPreviewEvent: <T>(event: SSEEvent<T>) => event is PreviewEvent;
|
|
259
|
+
/**
|
|
260
|
+
* Narrows an SSE event to a {@link ReasoningEvent} containing an agent's reasoning message.
|
|
261
|
+
*
|
|
262
|
+
* @param event - The SSE event to check.
|
|
263
|
+
* @returns `true` if the event is a reasoning event.
|
|
264
|
+
*
|
|
265
|
+
* @example
|
|
266
|
+
* ```typescript
|
|
267
|
+
* for await (const event of stream) {
|
|
268
|
+
* if (isReasoningEvent(event)) {
|
|
269
|
+
* appendReasoning(event.message);
|
|
270
|
+
* }
|
|
271
|
+
* }
|
|
272
|
+
* ```
|
|
273
|
+
*/
|
|
274
|
+
declare const isReasoningEvent: <T>(event: SSEEvent<T>) => event is ReasoningEvent;
|
|
209
275
|
|
|
210
276
|
declare const StorytellingEffortSchema: z.ZodEnum<{
|
|
211
277
|
none: "none";
|
|
@@ -385,22 +451,82 @@ declare const GenerateSuggestionsResponseSchema: z.ZodObject<{
|
|
|
385
451
|
}, z.core.$strip>;
|
|
386
452
|
type GenerateSuggestionsResponse = z.infer<typeof GenerateSuggestionsResponseSchema>;
|
|
387
453
|
type GenerateExplorationParams = GraphGenerationRequest;
|
|
454
|
+
/**
|
|
455
|
+
* Abela chart family — classifies the question-shape a finding is answering. Downstream
|
|
456
|
+
* chart-generator picks the concrete chart type from this family + the data shape.
|
|
457
|
+
*/
|
|
458
|
+
declare const ChartFamilySchema: z.ZodEnum<{
|
|
459
|
+
comparison: "comparison";
|
|
460
|
+
relationship: "relationship";
|
|
461
|
+
distribution: "distribution";
|
|
462
|
+
composition: "composition";
|
|
463
|
+
}>;
|
|
464
|
+
type ChartFamily = z.infer<typeof ChartFamilySchema>;
|
|
388
465
|
/** A single structured finding produced by the explore agent. */
|
|
389
466
|
declare const ExploreFindingSchema: z.ZodObject<{
|
|
390
|
-
|
|
467
|
+
finding: z.ZodString;
|
|
391
468
|
confidence: z.ZodNumber;
|
|
469
|
+
relevance: z.ZodNumber;
|
|
470
|
+
topic: z.ZodString;
|
|
471
|
+
chartHint: z.ZodString;
|
|
472
|
+
chartFamily: z.ZodEnum<{
|
|
473
|
+
comparison: "comparison";
|
|
474
|
+
relationship: "relationship";
|
|
475
|
+
distribution: "distribution";
|
|
476
|
+
composition: "composition";
|
|
477
|
+
}>;
|
|
392
478
|
evidenceSummary: z.ZodString;
|
|
393
479
|
}, z.core.$strip>;
|
|
394
480
|
type ExploreFinding = z.infer<typeof ExploreFindingSchema>;
|
|
481
|
+
/**
|
|
482
|
+
* A story is a group of {@link ExploreFinding}s that share the same `topic`. The server
|
|
483
|
+
* builds this view from the flat findings array; the agent itself only emits the flat
|
|
484
|
+
* list. Stories are sorted by `score` (max child quadrant score) desc, tiebreak on
|
|
485
|
+
* `count` desc. Findings inside a story are sorted by their own quadrant score desc.
|
|
486
|
+
*/
|
|
487
|
+
declare const ExploreStorySchema: z.ZodObject<{
|
|
488
|
+
topic: z.ZodString;
|
|
489
|
+
score: z.ZodNumber;
|
|
490
|
+
count: z.ZodNumber;
|
|
491
|
+
findings: z.ZodArray<z.ZodObject<{
|
|
492
|
+
finding: z.ZodString;
|
|
493
|
+
confidence: z.ZodNumber;
|
|
494
|
+
relevance: z.ZodNumber;
|
|
495
|
+
topic: z.ZodString;
|
|
496
|
+
chartHint: z.ZodString;
|
|
497
|
+
chartFamily: z.ZodEnum<{
|
|
498
|
+
comparison: "comparison";
|
|
499
|
+
relationship: "relationship";
|
|
500
|
+
distribution: "distribution";
|
|
501
|
+
composition: "composition";
|
|
502
|
+
}>;
|
|
503
|
+
evidenceSummary: z.ZodString;
|
|
504
|
+
}, z.core.$strip>>;
|
|
505
|
+
}, z.core.$strip>;
|
|
506
|
+
type ExploreStory = z.infer<typeof ExploreStorySchema>;
|
|
395
507
|
declare const GenerateExplorationResponseSchema: z.ZodObject<{
|
|
396
508
|
response: z.ZodObject<{
|
|
397
509
|
message: z.ZodString;
|
|
398
510
|
steps: z.ZodArray<z.ZodString>;
|
|
399
511
|
}, z.core.$strip>;
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
512
|
+
stories: z.ZodArray<z.ZodObject<{
|
|
513
|
+
topic: z.ZodString;
|
|
514
|
+
score: z.ZodNumber;
|
|
515
|
+
count: z.ZodNumber;
|
|
516
|
+
findings: z.ZodArray<z.ZodObject<{
|
|
517
|
+
finding: z.ZodString;
|
|
518
|
+
confidence: z.ZodNumber;
|
|
519
|
+
relevance: z.ZodNumber;
|
|
520
|
+
topic: z.ZodString;
|
|
521
|
+
chartHint: z.ZodString;
|
|
522
|
+
chartFamily: z.ZodEnum<{
|
|
523
|
+
comparison: "comparison";
|
|
524
|
+
relationship: "relationship";
|
|
525
|
+
distribution: "distribution";
|
|
526
|
+
composition: "composition";
|
|
527
|
+
}>;
|
|
528
|
+
evidenceSummary: z.ZodString;
|
|
529
|
+
}, z.core.$strip>>;
|
|
404
530
|
}, z.core.$strip>>;
|
|
405
531
|
}, z.core.$strip>;
|
|
406
532
|
type GenerateExplorationResponse = z.infer<typeof GenerateExplorationResponseSchema>;
|
|
@@ -413,6 +539,108 @@ declare const GenerateAnnotationsResponseSchema: z.ZodObject<{
|
|
|
413
539
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
414
540
|
}, z.core.$strip>;
|
|
415
541
|
type GenerateAnnotationsResponse = z.infer<typeof GenerateAnnotationsResponseSchema>;
|
|
542
|
+
type GenerateMutationParams = GraphGenerationRequest;
|
|
543
|
+
declare const GenerateMutationResponseSchema: z.ZodObject<{
|
|
544
|
+
response: z.ZodObject<{
|
|
545
|
+
message: z.ZodString;
|
|
546
|
+
steps: z.ZodArray<z.ZodString>;
|
|
547
|
+
}, z.core.$strip>;
|
|
548
|
+
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
549
|
+
}, z.core.$strip>;
|
|
550
|
+
type GenerateMutationResponse = z.infer<typeof GenerateMutationResponseSchema>;
|
|
551
|
+
/** Mirrors agents-api `extractConfidenceSchema`. */
|
|
552
|
+
declare const ExtractConfidenceSchema: z.ZodEnum<{
|
|
553
|
+
low: "low";
|
|
554
|
+
medium: "medium";
|
|
555
|
+
high: "high";
|
|
556
|
+
}>;
|
|
557
|
+
type ExtractConfidence = z.infer<typeof ExtractConfidenceSchema>;
|
|
558
|
+
/** Mirrors agents-api `ExtractMeta` (trust fields after `set_dataset_rows`). */
|
|
559
|
+
declare const ExtractMetaSchema: z.ZodObject<{
|
|
560
|
+
confidence: z.ZodEnum<{
|
|
561
|
+
low: "low";
|
|
562
|
+
medium: "medium";
|
|
563
|
+
high: "high";
|
|
564
|
+
}>;
|
|
565
|
+
needsUserInput: z.ZodBoolean;
|
|
566
|
+
warnings: z.ZodArray<z.ZodString>;
|
|
567
|
+
cellConfidence: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
568
|
+
rowIndex: z.ZodNumber;
|
|
569
|
+
columnKey: z.ZodString;
|
|
570
|
+
confidence: z.ZodEnum<{
|
|
571
|
+
low: "low";
|
|
572
|
+
medium: "medium";
|
|
573
|
+
high: "high";
|
|
574
|
+
}>;
|
|
575
|
+
quote: z.ZodOptional<z.ZodString>;
|
|
576
|
+
}, z.core.$strip>>>;
|
|
577
|
+
}, z.core.$strip>;
|
|
578
|
+
type ExtractMeta = z.infer<typeof ExtractMetaSchema>;
|
|
579
|
+
/** Mirrors agents-api `ExtractAccuracyLlmSchema`. */
|
|
580
|
+
declare const ExtractAccuracyEvaluationSchema: z.ZodObject<{
|
|
581
|
+
score: z.ZodNumber;
|
|
582
|
+
issues: z.ZodArray<z.ZodString>;
|
|
583
|
+
sufficient: z.ZodBoolean;
|
|
584
|
+
summary: z.ZodString;
|
|
585
|
+
}, z.core.$strip>;
|
|
586
|
+
type ExtractAccuracyEvaluation = z.infer<typeof ExtractAccuracyEvaluationSchema>;
|
|
587
|
+
/** Mirrors `MAX_SOURCE_TEXT_LENGTH` in agents-api `extract/extract.types.ts`. */
|
|
588
|
+
declare const MAX_SOURCE_TEXT_LENGTH = 500000;
|
|
589
|
+
/** Request body for `POST /v0/extract`. Mirrors `ExtractFromProseRequestSchema`. */
|
|
590
|
+
declare const ExtractFromProseParamsSchema: z.ZodObject<{
|
|
591
|
+
sourceText: z.ZodString;
|
|
592
|
+
metadata: z.ZodOptional<z.ZodObject<{
|
|
593
|
+
callId: z.ZodString;
|
|
594
|
+
locale: z.ZodOptional<z.ZodEnum<{
|
|
595
|
+
EN_GB: "EN_GB";
|
|
596
|
+
EN_US: "EN_US";
|
|
597
|
+
}>>;
|
|
598
|
+
storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
|
|
599
|
+
none: "none";
|
|
600
|
+
low: "low";
|
|
601
|
+
medium: "medium";
|
|
602
|
+
high: "high";
|
|
603
|
+
}>>>;
|
|
604
|
+
budget: z.ZodOptional<z.ZodObject<{
|
|
605
|
+
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
606
|
+
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
607
|
+
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
608
|
+
}, z.core.$strip>>;
|
|
609
|
+
}, z.core.$strip>>;
|
|
610
|
+
}, z.core.$strip>;
|
|
611
|
+
type ExtractFromProseParams = z.input<typeof ExtractFromProseParamsSchema>;
|
|
612
|
+
declare const ExtractFromProseResponseSchema: z.ZodObject<{
|
|
613
|
+
response: z.ZodObject<{
|
|
614
|
+
message: z.ZodString;
|
|
615
|
+
}, z.core.$strip>;
|
|
616
|
+
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
617
|
+
extractMeta: z.ZodNullable<z.ZodObject<{
|
|
618
|
+
confidence: z.ZodEnum<{
|
|
619
|
+
low: "low";
|
|
620
|
+
medium: "medium";
|
|
621
|
+
high: "high";
|
|
622
|
+
}>;
|
|
623
|
+
needsUserInput: z.ZodBoolean;
|
|
624
|
+
warnings: z.ZodArray<z.ZodString>;
|
|
625
|
+
cellConfidence: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
626
|
+
rowIndex: z.ZodNumber;
|
|
627
|
+
columnKey: z.ZodString;
|
|
628
|
+
confidence: z.ZodEnum<{
|
|
629
|
+
low: "low";
|
|
630
|
+
medium: "medium";
|
|
631
|
+
high: "high";
|
|
632
|
+
}>;
|
|
633
|
+
quote: z.ZodOptional<z.ZodString>;
|
|
634
|
+
}, z.core.$strip>>>;
|
|
635
|
+
}, z.core.$strip>>;
|
|
636
|
+
lastAccuracyEvaluation: z.ZodOptional<z.ZodObject<{
|
|
637
|
+
score: z.ZodNumber;
|
|
638
|
+
issues: z.ZodArray<z.ZodString>;
|
|
639
|
+
sufficient: z.ZodBoolean;
|
|
640
|
+
summary: z.ZodString;
|
|
641
|
+
}, z.core.$strip>>;
|
|
642
|
+
}, z.core.$strip>;
|
|
643
|
+
type ExtractFromProseResponse = z.infer<typeof ExtractFromProseResponseSchema>;
|
|
416
644
|
interface StorytellingOptions {
|
|
417
645
|
excludeTitle?: boolean;
|
|
418
646
|
excludeSubtitle?: boolean;
|
|
@@ -434,8 +662,9 @@ type GenerateGraphResponse = z.infer<typeof GenerateGraphResponseSchema>;
|
|
|
434
662
|
* Client SDK for the Graphy AI Agents API.
|
|
435
663
|
*
|
|
436
664
|
* Provides methods for AI-powered chart generation, narrative text creation,
|
|
437
|
-
*
|
|
438
|
-
*
|
|
665
|
+
* prompt suggestions, exploration, annotations, mutation, and prose-to-dataset
|
|
666
|
+
* extraction. Each method has a request-response variant and a streaming variant
|
|
667
|
+
* returning an `AsyncIterableIterator` of SSE events.
|
|
439
668
|
*
|
|
440
669
|
* @example
|
|
441
670
|
* ```typescript
|
|
@@ -564,10 +793,19 @@ declare class GraphyAiSdk {
|
|
|
564
793
|
message: string;
|
|
565
794
|
steps: string[];
|
|
566
795
|
};
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
796
|
+
stories: {
|
|
797
|
+
topic: string;
|
|
798
|
+
score: number;
|
|
799
|
+
count: number;
|
|
800
|
+
findings: {
|
|
801
|
+
finding: string;
|
|
802
|
+
confidence: number;
|
|
803
|
+
relevance: number;
|
|
804
|
+
topic: string;
|
|
805
|
+
chartHint: string;
|
|
806
|
+
chartFamily: "comparison" | "relationship" | "distribution" | "composition";
|
|
807
|
+
evidenceSummary: string;
|
|
808
|
+
}[];
|
|
571
809
|
}[];
|
|
572
810
|
}>;
|
|
573
811
|
/**
|
|
@@ -583,10 +821,19 @@ declare class GraphyAiSdk {
|
|
|
583
821
|
message: string;
|
|
584
822
|
steps: string[];
|
|
585
823
|
};
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
824
|
+
stories: {
|
|
825
|
+
topic: string;
|
|
826
|
+
score: number;
|
|
827
|
+
count: number;
|
|
828
|
+
findings: {
|
|
829
|
+
finding: string;
|
|
830
|
+
confidence: number;
|
|
831
|
+
relevance: number;
|
|
832
|
+
topic: string;
|
|
833
|
+
chartHint: string;
|
|
834
|
+
chartFamily: "comparison" | "relationship" | "distribution" | "composition";
|
|
835
|
+
evidenceSummary: string;
|
|
836
|
+
}[];
|
|
590
837
|
}[];
|
|
591
838
|
}>>>;
|
|
592
839
|
/**
|
|
@@ -620,9 +867,105 @@ declare class GraphyAiSdk {
|
|
|
620
867
|
};
|
|
621
868
|
config: _graphysdk_core_node.GraphConfig;
|
|
622
869
|
}>>>;
|
|
870
|
+
/**
|
|
871
|
+
* Runs the mutate agent to apply dataset transformations (filter, select, derive,
|
|
872
|
+
* group-by, rename, etc.) to the chart's dataset based on the user prompt.
|
|
873
|
+
*
|
|
874
|
+
* @param data - Parameters including the chart config and the user prompt.
|
|
875
|
+
* @param onProgress - Optional callback invoked with progress updates.
|
|
876
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
877
|
+
* @returns The agent response message, the ordered list of applied step names,
|
|
878
|
+
* and the updated chart config containing the mutated dataset.
|
|
879
|
+
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
880
|
+
*/
|
|
881
|
+
generateMutation(data: GenerateMutationParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
|
|
882
|
+
response: {
|
|
883
|
+
message: string;
|
|
884
|
+
steps: string[];
|
|
885
|
+
};
|
|
886
|
+
config: _graphysdk_core_node.GraphConfig;
|
|
887
|
+
}>;
|
|
888
|
+
/**
|
|
889
|
+
* Streams mutate agent events via SSE.
|
|
890
|
+
*
|
|
891
|
+
* @param data - Parameters including the chart config and the user prompt.
|
|
892
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
893
|
+
* @returns An async iterator yielding {@link SSEEvent} objects.
|
|
894
|
+
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
895
|
+
*/
|
|
896
|
+
generateMutationStream(data: GenerateMutationParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
|
|
897
|
+
response: {
|
|
898
|
+
message: string;
|
|
899
|
+
steps: string[];
|
|
900
|
+
};
|
|
901
|
+
config: _graphysdk_core_node.GraphConfig;
|
|
902
|
+
}>>>;
|
|
903
|
+
/**
|
|
904
|
+
* Runs the extract agent to build a chart-ready dataset from unstructured prose.
|
|
905
|
+
*
|
|
906
|
+
* @param data - Parameters including `sourceText` and optional request metadata.
|
|
907
|
+
* @param onProgress - Optional callback invoked with progress updates.
|
|
908
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
909
|
+
* @returns The updated chart config, extraction trust metadata, and optional accuracy audit.
|
|
910
|
+
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
911
|
+
*/
|
|
912
|
+
extractFromProse(data: ExtractFromProseParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
|
|
913
|
+
response: {
|
|
914
|
+
message: string;
|
|
915
|
+
};
|
|
916
|
+
config: _graphysdk_core_node.GraphConfig;
|
|
917
|
+
extractMeta: {
|
|
918
|
+
confidence: "low" | "medium" | "high";
|
|
919
|
+
needsUserInput: boolean;
|
|
920
|
+
warnings: string[];
|
|
921
|
+
cellConfidence?: {
|
|
922
|
+
rowIndex: number;
|
|
923
|
+
columnKey: string;
|
|
924
|
+
confidence: "low" | "medium" | "high";
|
|
925
|
+
quote?: string | undefined;
|
|
926
|
+
}[] | undefined;
|
|
927
|
+
} | null;
|
|
928
|
+
lastAccuracyEvaluation?: {
|
|
929
|
+
score: number;
|
|
930
|
+
issues: string[];
|
|
931
|
+
sufficient: boolean;
|
|
932
|
+
summary: string;
|
|
933
|
+
} | undefined;
|
|
934
|
+
}>;
|
|
935
|
+
/**
|
|
936
|
+
* Streams extract-agent events via SSE.
|
|
937
|
+
*
|
|
938
|
+
* @param data - Parameters including `sourceText` and optional request metadata.
|
|
939
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
940
|
+
* @returns An async iterator yielding {@link SSEEvent} objects.
|
|
941
|
+
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
942
|
+
*/
|
|
943
|
+
extractFromProseStream(data: ExtractFromProseParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
|
|
944
|
+
response: {
|
|
945
|
+
message: string;
|
|
946
|
+
};
|
|
947
|
+
config: _graphysdk_core_node.GraphConfig;
|
|
948
|
+
extractMeta: {
|
|
949
|
+
confidence: "low" | "medium" | "high";
|
|
950
|
+
needsUserInput: boolean;
|
|
951
|
+
warnings: string[];
|
|
952
|
+
cellConfidence?: {
|
|
953
|
+
rowIndex: number;
|
|
954
|
+
columnKey: string;
|
|
955
|
+
confidence: "low" | "medium" | "high";
|
|
956
|
+
quote?: string | undefined;
|
|
957
|
+
}[] | undefined;
|
|
958
|
+
} | null;
|
|
959
|
+
lastAccuracyEvaluation?: {
|
|
960
|
+
score: number;
|
|
961
|
+
issues: string[];
|
|
962
|
+
sufficient: boolean;
|
|
963
|
+
summary: string;
|
|
964
|
+
} | undefined;
|
|
965
|
+
}>>>;
|
|
623
966
|
private stripStorytelling;
|
|
624
967
|
private wrapStreamWithStorytellingStripping;
|
|
625
968
|
}
|
|
626
969
|
|
|
627
|
-
export { AiChartTypeEnum, ExploreFindingSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, isCompleteEvent, isErrorEvent, isGraphyApiError, isProgressEvent };
|
|
628
|
-
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 };
|
|
970
|
+
export { AiChartTypeEnum, ChartFamilySchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
|
|
971
|
+
export type { AiChartType, ChartFamily, ClientConfig, CompleteEvent, ErrorEvent, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, Logger, Metadata, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, 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 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,u,h;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){u=y.value,f=!1;const t=u;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!==(h=t.retryable)&&void 0!==h&&h})}}}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 u=n.enum(["EN_GB","EN_US"]),h=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:u.optional(),storytellingEffort:p.optional().default("low"),budget:y.optional()}),m=1e4,b=n.object({config:h,userPrompt:n.string().max(1e4).optional().default(""),metadata:f.optional()}),v=b.extend({maxSuggestionCount:n.number().int().min(1).max(4).optional()}),w=n.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),$=n.object({dataPrepPrompt:n.string(),chartType:w,summary:n.string()}),S=n.object({response:n.object({message:n.string()}),config:h}),j=n.object({suggestions:n.array($)}),x=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.")}),C=n.object({response:n.object({message:n.string(),steps:n.array(n.string())}),findings:n.array(x)}),O=n.object({response:n.object({message:n.string(),steps:n.array(n.string())}),config:h}),k=n.object({config:h,response:n.object({message:n.string(),steps:n.array(n.string())})}),E="/api/v0";class R{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=k.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 S.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 j.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 C.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 O.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{w as AiChartTypeEnum,x as ExploreFindingSchema,O as GenerateAnnotationsResponseSchema,C as GenerateExplorationResponseSchema,k as GenerateGraphResponseSchema,S as GenerateNarrativeResponseSchema,v as GenerateSuggestionsParamsSchema,j as GenerateSuggestionsResponseSchema,b as GraphGenerationRequestSchema,R as GraphyAiSdk,s as GraphyApiError,y as InvocationBudgetSchema,m as MAX_USER_PROMPT_LENGTH,f as MetadataSchema,p as StorytellingEffortSchema,$ as SuggestionSchema,c as isCompleteEvent,g as isErrorEvent,a as isGraphyApiError,l as isProgressEvent};
|
|
1
|
+
import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as i,__rest as n}from"tslib";import{z as o}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,c=t=>"progress"===t.type,l=t=>"complete"===t.type,g=t=>"error"===t.type,d=t=>"preview"===t.type,u=t=>"reasoning"===t.type;class h{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 c(t)}static isCompleteEvent(t){return l(t)}static isErrorEvent(t){return g(t)}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,n,o){return t(this,void 0,void 0,function*(){var t,a,d,u,h;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${r}`);try{const b=yield this.makeRequest(r,i,o),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var m,f=!0,y=e(this.parseSSE(b));!(t=(m=yield y.next()).done);f=!0){u=m.value,f=!1;const t=u;if(c(t)&&n&&n(t),l(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!==(h=t.retryable)&&void 0!==h&&h})}}}catch(t){a={error:t}}finally{try{f||t||!(d=y.return)||(yield d.call(y))}finally{if(a)throw a.error}}const i=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${i}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 n="",o="",a="";try{for(;;){const{done:t,value:s}=yield i(e.read());if(t)break;n+=r.decode(s,{stream:!0});const c=n.split(/\r?\n/);n=c.pop()||"";for(const t of c)if(t.startsWith("event: "))o=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"===o){const r=t;e=Object.assign({type:"progress"},r)}else if("complete"===o)e={type:"complete",data:t};else if("error"===o){const r=t;e=Object.assign({type:"error"},r)}else if("preview"===o){const r=t;e=Object.assign(Object.assign({},r),{type:"preview"})}else{if("reasoning"!==o){o="",a="";continue}{const r=t;e=Object.assign(Object.assign({},r),{type:"reasoning"})}}if(yield yield i(e),"complete"===o||"error"===o)return yield i(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}o="",a=""}}}finally{e.releaseLock()}})}makeRequest(e,r,i){return t(this,arguments,void 0,function*(t,e,r,i=1,n="POST"){if(!t.startsWith("/"))throw new s("Invalid endpoint: must start with /");const o=new URL(t,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new s("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${o}`);const a=new AbortController,c=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();r&&r.addEventListener("abort",l);try{const c=yield fetch(o,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(!c.ok){const o=c.status>=500||429===c.status;let a,l=`HTTP ${c.status}`;try{const t=yield c.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?l=e.message:"string"==typeof e.error&&(l=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new s(l,{status:c.status,code:a,retryable:o});if(o&&i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${o}ms (attempt ${i+1})`),yield this.sleep(o),this.makeRequest(t,e,r,i+1,n)}throw this.logger.error(`${this.tag} Request failed: ${t} (${c.status}) - ${l}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),c}catch(o){if(o instanceof s)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),o;if(i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${o}ms`),yield this.sleep(o),this.makeRequest(t,e,r,i+1,n)}throw this.logger.error(`${this.tag} Network error: ${t}`,o),new s("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",l)}})}}const p=o.enum(["EN_GB","EN_US"]),m=o.custom(t=>null!=t&&"object"==typeof t),f=o.enum(["none","low","medium","high"]),y=o.object({maxWallClockMs:o.number().positive().optional(),maxTotalTokens:o.number().int().positive().optional(),maxCostUsd:o.number().positive().optional()}),b=o.object({callId:o.string().max(256),locale:p.optional(),storytellingEffort:f.optional().default("low"),budget:y.optional()}),v=1e4,w=o.object({config:m,userPrompt:o.string().max(1e4).optional().default(""),metadata:b.optional()}),$=w.extend({maxSuggestionCount:o.number().int().min(1).max(4).optional()}),j=o.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),S=o.object({dataPrepPrompt:o.string(),chartType:j,summary:o.string()}),x=o.object({response:o.object({message:o.string()}),config:m}),O=o.object({suggestions:o.array(S)}),k=o.enum(["comparison","relationship","distribution","composition"]),C=o.object({finding:o.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:o.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:o.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:o.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:o.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:k.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:o.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),E=o.object({topic:o.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:o.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:o.number().int().min(1).describe("Number of findings in this story."),findings:o.array(C).describe("Child findings, sorted by quadrant score desc.")}),R=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),stories:o.array(E)}),T=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),config:m}),P=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),config:m}),q=o.enum(["high","medium","low"]),A=o.object({confidence:q,needsUserInput:o.boolean(),warnings:o.array(o.string()),cellConfidence:o.array(o.object({rowIndex:o.number().int().nonnegative(),columnKey:o.string(),confidence:q,quote:o.string().optional()})).optional()}),N=o.object({score:o.number().min(0).max(1),issues:o.array(o.string()),sufficient:o.boolean(),summary:o.string()}),U=5e5,D=o.object({sourceText:o.string().min(1).max(U),metadata:b.optional()}),K=o.object({response:o.object({message:o.string()}),config:m,extractMeta:A.nullable(),lastAccuracyEvaluation:N.optional()}),I=o.object({config:m,response:o.object({message:o.string(),steps:o.array(o.string())})}),F="/api/v0";class G{constructor(t){this.client=new h(t)}generateGraph(e,r,i){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,o=n(e,["storytellingOptions"]),s=yield this.client.fetch(`${F}/generate`,o,r,i),a=I.parse(s);return this.stripStorytelling(a,t)})}generateGraphStream(e,r){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,i=n(e,["storytellingOptions"]),o=yield this.client.stream(`${F}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(o,t)})}generateNarrative(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${F}/narrate`,e,r,i);return x.parse(t)})}generateNarrativeStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${F}/narrate`,e,r)})}generateSuggestions(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${F}/suggestions`,e,r,i);return O.parse(t)})}generateSuggestionsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${F}/suggestions`,e,r)})}generateExploration(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${F}/explore`,e,r,i);return R.parse(t)})}generateExplorationStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${F}/explore`,e,r)})}generateAnnotations(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${F}/annotate`,e,r,i);return T.parse(t)})}generateAnnotationsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${F}/annotate`,e,r)})}generateMutation(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${F}/mutate`,e,r,i);return P.parse(t)})}generateMutationStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${F}/mutate`,e,r)})}extractFromProse(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${F}/extract`,e,r,i);return K.parse(t)})}extractFromProseStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${F}/extract`,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,n){return r(this,arguments,function*(){var r,o,s,a;try{for(var c,g=!0,d=e(t);!(r=(c=yield i(d.next())).done);g=!0){a=c.value,g=!1;const t=a;if(l(t)){const e=this.stripStorytelling(t.data,n);yield yield i(Object.assign(Object.assign({},t),{data:e}))}else yield yield i(t)}}catch(t){o={error:t}}finally{try{g||r||!(s=d.return)||(yield i(s.call(d)))}finally{if(o)throw o.error}}})}}export{j as AiChartTypeEnum,k as ChartFamilySchema,C as ExploreFindingSchema,E as ExploreStorySchema,N as ExtractAccuracyEvaluationSchema,q as ExtractConfidenceSchema,D as ExtractFromProseParamsSchema,K as ExtractFromProseResponseSchema,A as ExtractMetaSchema,T as GenerateAnnotationsResponseSchema,R as GenerateExplorationResponseSchema,I as GenerateGraphResponseSchema,P as GenerateMutationResponseSchema,x as GenerateNarrativeResponseSchema,$ as GenerateSuggestionsParamsSchema,O as GenerateSuggestionsResponseSchema,w as GraphGenerationRequestSchema,G as GraphyAiSdk,s as GraphyApiError,y as InvocationBudgetSchema,U as MAX_SOURCE_TEXT_LENGTH,v as MAX_USER_PROMPT_LENGTH,b as MetadataSchema,f as StorytellingEffortSchema,S as SuggestionSchema,l as isCompleteEvent,g as isErrorEvent,a as isGraphyApiError,d as isPreviewEvent,c as isProgressEvent,u as isReasoningEvent};
|
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.1776786180132",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"files": [
|
|
@@ -18,12 +18,12 @@
|
|
|
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.1776786180132"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|
|
25
25
|
"@rollup/plugin-node-resolve": "^16.0.1",
|
|
26
|
-
"@rollup/plugin-terser": "^0.
|
|
26
|
+
"@rollup/plugin-terser": "^1.0.0",
|
|
27
27
|
"@rollup/plugin-typescript": "^12.1.4",
|
|
28
28
|
"lodash-es": "^4.18.1",
|
|
29
29
|
"rollup": "^4.59.0",
|