@graphysdk/agents-sdk 1.3.0-beta.1776957859415 → 1.3.0-beta.1778059383500
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 +71 -11
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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,u,d,p;const h=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,f=!0,y=e.__asyncValues(this.parseSSE(b));!(l=(m=yield y.next()).done);f=!0){d=m.value,f=!1;const e=d;if(i(e)&&a&&a(e),n(e))return e.data;if(o(e)){const i=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${t} ${i}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(p=e.retryable)&&void 0!==p&&p})}}}catch(e){g={error:e}}finally{try{f||l||!(u=y.return)||(yield u.call(y))}finally{if(g)throw g.error}}const s=Date.now()-h;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()-h;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${i}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-h;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(["low","medium","high"]),g=t.z.enum(["none","low","medium","high"]),u=t.z.enum(["agentic","fast"]),d=t.z.object({maxWallClockMs:t.z.number().positive().optional(),maxTotalTokens:t.z.number().int().positive().optional(),maxCostUsd:t.z.number().positive().optional()}),p=t.z.object({callId:t.z.string().max(256),locale:a.optional(),effort:l.optional(),storytellingEffort:g.optional().default("low"),budget:d.optional(),executionMode:u.optional()}),h=t.z.object({config:c,userPrompt:t.z.string().max(1e4).optional().default(""),metadata:p.optional()}),m=h.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),f=t.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),y=t.z.object({dataPrepPrompt:t.z.string(),chartType:f,summary:t.z.string()}),b=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),v=t.z.object({suggestions:t.z.array(y)}),w=t.z.enum(["comparison","relationship","distribution","composition"]),x=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:w.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.")}),z=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(x).describe("Child findings, sorted by quadrant score desc.")}),_=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(z)}),S=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),E=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),$=t.z.enum(["high","medium","low"]),j=t.z.object({confidence:$,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:$,quote:t.z.string().optional()})).optional()}),C=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()}),T=5e5,R=2097152,O=7340032,A=4*Math.ceil(699050.6666666666),G=4*Math.ceil(2446677.3333333335);function k(e){return e.replace(/\s+/g,"")}const M=t.z.object({mimeType:t.z.string().min(1).refine(e=>/^image\/(png|jpeg|jpg|webp|gif)$/i.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(A).refine(function(e){const t=k(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)},{message:"dataBase64 must be standard base64 (RFC 4648)"})}),P=t.z.object({sourceText:t.z.string().max(T).default(""),images:t.z.array(M).max(8).optional(),metadata:p.optional()}).superRefine((e,t)=>{var r;const i=e.sourceText.trim(),n=null!==(r=e.images)&&void 0!==r?r:[];if(0===i.length&&0===n.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one image",path:["sourceText"]});if(0===n.length)return;n.reduce((e,t)=>e+k(t.dataBase64).length,0)>G&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}),D=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:j.nullable(),lastAccuracyEvaluation:C.optional()}),I=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),q=v,N="/api/v0";exports.AiChartTypeEnum=f,exports.ChartFamilySchema=w,exports.ExecutionModeSchema=u,exports.ExploreFindingSchema=x,exports.ExploreStorySchema=z,exports.ExtractAccuracyEvaluationSchema=C,exports.ExtractConfidenceSchema=$,exports.ExtractFromProseParamsSchema=P,exports.ExtractFromProseResponseSchema=D,exports.ExtractMetaSchema=j,exports.GenerateAnnotationsResponseSchema=S,exports.GenerateExplorationResponseSchema=_,exports.GenerateGraphResponseSchema=I,exports.GenerateGraphSuggestionsResponseSchema=q,exports.GenerateMutationResponseSchema=E,exports.GenerateNarrativeResponseSchema=b,exports.GenerateSuggestionsParamsSchema=m,exports.GenerateSuggestionsResponseSchema=v,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(`${N}/generate`,o,r,i),a=I.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(`${N}/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(`${N}/narrate`,t,r,i);return b.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${N}/narrate`,t,r)})}generateSuggestions(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${N}/suggestions`,t,r,i);return v.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${N}/suggestions`,t,r)})}generateExploration(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${N}/explore`,t,r,i);return _.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${N}/explore`,t,r)})}generateAnnotations(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${N}/annotate`,t,r,i);return S.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${N}/annotate`,t,r)})}generateMutation(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${N}/mutate`,t,r,i);return E.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${N}/mutate`,t,r)})}extractFromProse(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${N}/extract`,t,r,i);return D.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${N}/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=d,exports.InvocationEffortSchema=l,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=O,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=R,exports.MAX_SOURCE_TEXT_LENGTH=T,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=p,exports.StorytellingEffortSchema=g,exports.SuggestionSchema=y,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;
|
|
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,a=e=>"complete"===e.type,n=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 a(e)}static isErrorEvent(e){return n(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,o,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,d,g,u;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,s,c),x=b.headers.get("content-type");if(null==x?void 0:x.includes("text/event-stream")){try{for(var p,f=!0,y=e.__asyncValues(this.parseSSE(b));!(l=(p=yield y.next()).done);f=!0){g=p.value,f=!1;const e=g;if(i(e)&&o&&o(e),a(e))return e.data;if(n(e)){const i=Date.now()-h;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){m={error:e}}finally{try{f||l||!(d=y.return)||(yield d.call(y))}finally{if(m)throw m.error}}const s=Date.now()-h;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()-h;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${i}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-h;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(),a=new TextDecoder;let n="",s="",o="";try{for(;;){const{done:t,value:r}=yield e.__await(i.read());if(t)break;n+=a.decode(r,{stream:!0});const c=n.split(/\r?\n/);n=c.pop()||"";for(const t of c)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))o+=(o?"\n":"")+t.slice(6);else if(""===t.trim()&&o){try{const t=JSON.parse(o);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="",o="";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",o)}s="",o=""}}}finally{i.releaseLock()}})}makeRequest(t,i,a){return e.__awaiter(this,arguments,void 0,function*(e,t,i,a=1,n="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 ${a}/${this.retryConfig.attempts}: ${s}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),l=()=>o.abort();i&&i.addEventListener("abort",l);try{const c=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:o.signal},"POST"===n&&{body:JSON.stringify(t)}));if(!c.ok){const s=c.status>=500||429===c.status;let o,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&&(o=t.code)}}catch(e){}const m=new r(l,{status:c.status,code:o,retryable:s});if(s&&a<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${a+1})`),yield this.sleep(r),this.makeRequest(e,t,i,a+1,n)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),m}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(a<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,i,a+1,n)}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 o=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),l=t.z.enum(["low","medium","high"]),m=t.z.enum(["none","low","medium","high"]),d=t.z.enum(["agentic","fast"]),g=t.z.object({maxWallClockMs:t.z.number().positive().optional(),maxTotalTokens:t.z.number().int().positive().optional(),maxCostUsd:t.z.number().positive().optional()}),u=t.z.object({callId:t.z.string().max(256),locale:o.optional(),effort:l.optional(),storytellingEffort:m.optional().default("low"),budget:g.optional(),executionMode:d.optional()}),h=t.z.object({config:c,userPrompt:t.z.string().max(1e4).optional().default(""),metadata:u.optional()}),p=h.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),f=t.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),y=t.z.object({dataPrepPrompt:t.z.string(),chartType:f,summary:t.z.string()}),b=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),x=t.z.object({suggestions:t.z.array(y)}),v=t.z.enum(["comparison","relationship","distribution","composition"]),w=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:v.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.")}),_=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(w).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(_)}),S=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),E=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),T=t.z.enum(["high","medium","low"]),$=t.z.object({confidence:T,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:T,quote:t.z.string().optional()})).optional()}),j=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()}),C=5e5,A=2097152,O=7340032,R=6291456,M=8388608,k=12582912,D=4*Math.ceil(699050.6666666666),G=4*Math.ceil(2446677.3333333335),I=4*Math.ceil(2097152),P=4*Math.ceil(2796202.6666666665),B=4*Math.ceil(4194304);function N(e){return e.replace(/\s+/g,"")}function U(e){const t=N(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const X=/^image\/(png|jpeg|jpg|webp|gif)$/i,q=t.z.object({mimeType:t.z.string().min(1).refine(e=>X.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(D).refine(U,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),F=t.z.enum(["image","document"]),K=q.extend({kind:t.z.literal("image")}),L=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(I).refine(U,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),H=t.z.discriminatedUnion("kind",[K,L]),W=t.z.object({sourceText:t.z.string().max(C).default(""),images:t.z.array(q).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(H).max(10).optional(),metadata:u.optional()}).superRefine((e,t)=>{var r,i;const a=e.sourceText.trim(),n=null!==(r=e.images)&&void 0!==r?r:[],s=null!==(i=e.attachments)&&void 0!==i?i:[];if(n.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===a.length&&0===n.length&&0===s.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(n.length>0){n.reduce((e,t)=>e+N(t.dataBase64).length,0)>G&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}const o=s.filter(e=>"image"===e.kind).length,c=s.length-o;if(o>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),s.length>0&&o<=8&&c<=2){let e=0,r=0,i=0;for(const t of s){const a=N(t.dataBase64).length;i+=a,"image"===t.kind?e+=a:r+=a}e>G&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),r>P&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),i>B&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]})}});const Y=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:$.nullable(),lastAccuracyEvaluation:j.optional()}),J=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),V=x,Z="/api/v0";exports.AiChartTypeEnum=f,exports.ChartFamilySchema=v,exports.ExecutionModeSchema=d,exports.ExploreFindingSchema=w,exports.ExploreStorySchema=_,exports.ExtractAccuracyEvaluationSchema=j,exports.ExtractAttachmentInputSchema=H,exports.ExtractAttachmentKindSchema=F,exports.ExtractConfidenceSchema=T,exports.ExtractFromProseParamsSchema=W,exports.ExtractFromProseResponseSchema=Y,exports.ExtractMetaSchema=$,exports.GenerateAnnotationsResponseSchema=S,exports.GenerateExplorationResponseSchema=z,exports.GenerateGraphResponseSchema=J,exports.GenerateGraphSuggestionsResponseSchema=V,exports.GenerateMutationResponseSchema=E,exports.GenerateNarrativeResponseSchema=b,exports.GenerateSuggestionsParamsSchema=p,exports.GenerateSuggestionsResponseSchema=x,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:a}=t,n=e.__rest(t,["storytellingOptions"]),s=yield this.client.fetch(`${Z}/generate`,n,r,i),o=J.parse(s);return this.stripStorytelling(o,a)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,a=e.__rest(t,["storytellingOptions"]),n=yield this.client.stream(`${Z}/generate`,a,r);return this.wrapStreamWithStorytellingStripping(n,i)})}generateNarrative(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Z}/narrate`,t,r,i);return b.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Z}/narrate`,t,r)})}generateSuggestions(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Z}/suggestions`,t,r,i);return x.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Z}/suggestions`,t,r)})}generateExploration(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Z}/explore`,t,r,i);return z.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Z}/explore`,t,r)})}generateAnnotations(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Z}/annotate`,t,r,i);return S.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Z}/annotate`,t,r)})}generateMutation(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Z}/mutate`,t,r,i);return E.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Z}/mutate`,t,r)})}extractFromProse(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Z}/extract`,t,r,i);return Y.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Z}/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,n,s,o;try{for(var c,l=!0,m=e.__asyncValues(t);!(i=(c=yield e.__await(m.next())).done);l=!0){o=c.value,l=!1;const t=o;if(a(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){n={error:e}}finally{try{l||i||!(s=m.return)||(yield e.__await(s.call(m)))}finally{if(n)throw n.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.InvocationEffortSchema=l,exports.MAX_EXTRACT_ATTACHMENTS=10,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=k,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=M,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=R,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=O,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=A,exports.MAX_SOURCE_TEXT_LENGTH=C,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=u,exports.StorytellingEffortSchema=m,exports.SuggestionSchema=y,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:N(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:N(e.dataBase64)}},exports.isCompleteEvent=a,exports.isErrorEvent=n,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
|
@@ -627,20 +627,58 @@ type ExtractAccuracyEvaluation = z.infer<typeof ExtractAccuracyEvaluationSchema>
|
|
|
627
627
|
declare const MAX_SOURCE_TEXT_LENGTH = 500000;
|
|
628
628
|
/** Mirrors apps/agents-api extract image limits (server re-validates decoded size). */
|
|
629
629
|
declare const MAX_EXTRACT_IMAGES = 8;
|
|
630
|
-
/** Same caps as apps/agents-api (
|
|
630
|
+
/** Same caps as apps/agents-api (16MB `/api/v0/extract` JSON body budget; other `/api/*` routes stay at 10MB). */
|
|
631
631
|
declare const MAX_EXTRACT_IMAGE_DECODED_BYTES: number;
|
|
632
632
|
declare const MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES: number;
|
|
633
|
+
/** Mirrors apps/agents-api extract document (PDF) limits. */
|
|
634
|
+
declare const MAX_EXTRACT_DOCUMENTS = 2;
|
|
635
|
+
declare const MAX_EXTRACT_DOCUMENT_DECODED_BYTES: number;
|
|
636
|
+
declare const MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES: number;
|
|
637
|
+
/** Combined cap across images and documents in one request. Mirrors agents-api. */
|
|
638
|
+
declare const MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES: number;
|
|
639
|
+
/** Total attachments cap (images + documents). Mirrors agents-api. */
|
|
640
|
+
declare const MAX_EXTRACT_ATTACHMENTS: number;
|
|
633
641
|
declare const extractImagePartSchema: z.ZodObject<{
|
|
634
642
|
mimeType: z.ZodString;
|
|
635
643
|
dataBase64: z.ZodString;
|
|
636
644
|
}, z.core.$strip>;
|
|
637
|
-
/**
|
|
645
|
+
/** Discriminator for entries in `attachments[]`. */
|
|
646
|
+
declare const ExtractAttachmentKindSchema: z.ZodEnum<{
|
|
647
|
+
image: "image";
|
|
648
|
+
document: "document";
|
|
649
|
+
}>;
|
|
650
|
+
type ExtractAttachmentKind = z.infer<typeof ExtractAttachmentKindSchema>;
|
|
651
|
+
declare const ExtractAttachmentInputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
652
|
+
mimeType: z.ZodString;
|
|
653
|
+
dataBase64: z.ZodString;
|
|
654
|
+
kind: z.ZodLiteral<"image">;
|
|
655
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
656
|
+
kind: z.ZodLiteral<"document">;
|
|
657
|
+
mimeType: z.ZodString;
|
|
658
|
+
dataBase64: z.ZodString;
|
|
659
|
+
}, z.core.$strip>], "kind">;
|
|
660
|
+
type ExtractAttachmentInput = z.infer<typeof ExtractAttachmentInputSchema>;
|
|
661
|
+
/**
|
|
662
|
+
* Request body for `POST /v0/extract`. Mirrors `ExtractFromProseRequestSchema` in agents-api.
|
|
663
|
+
*
|
|
664
|
+
* @remarks Wire support for `attachments` requires a matching agents-api release that accepts the
|
|
665
|
+
* same field (same rollout stack). Older servers only read `images[]` and ignore unknown keys.
|
|
666
|
+
*/
|
|
638
667
|
declare const ExtractFromProseParamsSchema: z.ZodObject<{
|
|
639
668
|
sourceText: z.ZodDefault<z.ZodString>;
|
|
640
669
|
images: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
641
670
|
mimeType: z.ZodString;
|
|
642
671
|
dataBase64: z.ZodString;
|
|
643
672
|
}, z.core.$strip>>>;
|
|
673
|
+
attachments: z.ZodOptional<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
674
|
+
mimeType: z.ZodString;
|
|
675
|
+
dataBase64: z.ZodString;
|
|
676
|
+
kind: z.ZodLiteral<"image">;
|
|
677
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
678
|
+
kind: z.ZodLiteral<"document">;
|
|
679
|
+
mimeType: z.ZodString;
|
|
680
|
+
dataBase64: z.ZodString;
|
|
681
|
+
}, z.core.$strip>], "kind">>>;
|
|
644
682
|
metadata: z.ZodOptional<z.ZodObject<{
|
|
645
683
|
callId: z.ZodString;
|
|
646
684
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
@@ -671,6 +709,24 @@ declare const ExtractFromProseParamsSchema: z.ZodObject<{
|
|
|
671
709
|
}, z.core.$strip>;
|
|
672
710
|
type ExtractImageInput = z.infer<typeof extractImagePartSchema>;
|
|
673
711
|
type ExtractFromProseParams = z.input<typeof ExtractFromProseParamsSchema>;
|
|
712
|
+
/**
|
|
713
|
+
* Builds an `attachments[]` entry for an image. Strips whitespace from the base64 string and
|
|
714
|
+
* normalizes the MIME so the wire payload matches what the server expects. Prefer this helper over
|
|
715
|
+
* constructing the object literal yourself.
|
|
716
|
+
*/
|
|
717
|
+
declare function buildImageAttachment(input: ExtractImageInput): Extract<ExtractAttachmentInput, {
|
|
718
|
+
kind: 'image';
|
|
719
|
+
}>;
|
|
720
|
+
/**
|
|
721
|
+
* Builds an `attachments[]` entry for a PDF document. Forces `mimeType: 'application/pdf'` to keep
|
|
722
|
+
* callers from accidentally tagging a PDF as anything else; the server runs the same MIME and
|
|
723
|
+
* magic-byte checks on top.
|
|
724
|
+
*/
|
|
725
|
+
declare function buildPdfAttachment(input: {
|
|
726
|
+
dataBase64: string;
|
|
727
|
+
}): Extract<ExtractAttachmentInput, {
|
|
728
|
+
kind: 'document';
|
|
729
|
+
}>;
|
|
674
730
|
declare const ExtractFromProseResponseSchema: z.ZodObject<{
|
|
675
731
|
response: z.ZodObject<{
|
|
676
732
|
message: z.ZodString;
|
|
@@ -994,11 +1050,13 @@ declare class GraphyAiSdk {
|
|
|
994
1050
|
config: _graphysdk_core_node.GraphConfig;
|
|
995
1051
|
}>>>;
|
|
996
1052
|
/**
|
|
997
|
-
* Runs the extract agent to build a chart-ready dataset from unstructured prose.
|
|
1053
|
+
* Runs the extract agent to build a chart-ready dataset from unstructured prose, images, and/or PDFs.
|
|
998
1054
|
*
|
|
999
|
-
* @param data - Parameters including `sourceText`, optional `
|
|
1000
|
-
*
|
|
1001
|
-
*
|
|
1055
|
+
* @param data - Parameters including `sourceText`, optional `attachments[]` (preferred: each entry is
|
|
1056
|
+
* `{ kind: "image" | "document", mimeType, dataBase64 }` where `dataBase64` is standard RFC 4648
|
|
1057
|
+
* base64 — not a `data:...;base64,...` URL), optional legacy `images[]` (deprecated; use
|
|
1058
|
+
* `attachments[]` instead), and optional request metadata. At least one of non-empty `sourceText`,
|
|
1059
|
+
* `attachments[]`, or `images[]` is required. `images[]` and `attachments[]` are mutually exclusive.
|
|
1002
1060
|
* @param onProgress - Optional callback invoked with progress updates.
|
|
1003
1061
|
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
1004
1062
|
* @returns The updated chart config, extraction trust metadata, and optional accuracy audit.
|
|
@@ -1030,9 +1088,11 @@ declare class GraphyAiSdk {
|
|
|
1030
1088
|
/**
|
|
1031
1089
|
* Streams extract-agent events via SSE.
|
|
1032
1090
|
*
|
|
1033
|
-
* @param data - Parameters including `sourceText`, optional `
|
|
1034
|
-
*
|
|
1035
|
-
* At least one of
|
|
1091
|
+
* @param data - Parameters including `sourceText`, optional `attachments[]` (preferred), optional
|
|
1092
|
+
* legacy `images[]` (deprecated; use `attachments[]` instead), and optional request metadata.
|
|
1093
|
+
* See {@link extractFromProse} for the full attachment shape. At least one of non-empty
|
|
1094
|
+
* `sourceText`, `attachments[]`, or `images[]` is required; `images[]` and `attachments[]`
|
|
1095
|
+
* are mutually exclusive.
|
|
1036
1096
|
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
1037
1097
|
* @returns An async iterator yielding {@link SSEEvent} objects.
|
|
1038
1098
|
* @throws {GraphyApiError} When the API returns an error or the network request fails.
|
|
@@ -1064,5 +1124,5 @@ declare class GraphyAiSdk {
|
|
|
1064
1124
|
private wrapStreamWithStorytellingStripping;
|
|
1065
1125
|
}
|
|
1066
1126
|
|
|
1067
|
-
export { AiChartTypeEnum, ChartFamilySchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
|
|
1068
|
-
export type { AiChartType, ChartFamily, ClientConfig, CompleteEvent, ErrorEvent, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, Logger, Metadata, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
|
|
1127
|
+
export { AiChartTypeEnum, ChartFamilySchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, MAX_EXTRACT_ATTACHMENTS, MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES, MAX_EXTRACT_DOCUMENTS, MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES, MAX_EXTRACT_DOCUMENT_DECODED_BYTES, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
|
|
1128
|
+
export type { AiChartType, ChartFamily, ClientConfig, CompleteEvent, ErrorEvent, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, Logger, Metadata, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e,__asyncValues as t,__asyncGenerator as r,__await as i,__rest as n}from"tslib";import{z as o}from"zod";class s 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 a=e=>e instanceof s,c=e=>"progress"===e.type,l=e=>"complete"===e.type,g=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type;class h{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 c(e)}static isCompleteEvent(e){return l(e)}static isErrorEvent(e){return g(e)}stream(t,r,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,i);return this.parseSSE(e)})}fetch(r,i,n,o){return e(this,void 0,void 0,function*(){var e,a,d,u,h;const m=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 p,f=!0,y=t(this.parseSSE(b));!(e=(p=yield y.next()).done);f=!0){u=p.value,f=!1;const e=u;if(c(e)&&n&&n(e),l(e))return e.data;if(g(e)){const t=Date.now()-m;throw this.logger.error(`${this.tag} Server error: ${r} ${t}ms`,e.error),new s(e.error,{code:e.code,retryable:null!==(h=e.retryable)&&void 0!==h&&h})}}}catch(e){a={error:e}}finally{try{f||e||!(d=y.return)||(yield d.call(y))}finally{if(a)throw a.error}}const i=Date.now()-m;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${i}ms`),new s("Stream ended without completion")}return yield b.json()}catch(e){const t=Date.now()-m;if(this.logger.error(`${this.tag} Fetch failed: ${r} ${t}ms`,e),e instanceof s)throw e;throw e}finally{const e=Date.now()-m;this.logger.debug(`${this.tag} Fetch completed: ${r} ${e}ms`)}})}ping(){return e(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(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return r(this,arguments,function*(){if(!e.body)throw new s("Response body is null");const t=e.body.getReader(),r=new TextDecoder;let n="",o="",a="";try{for(;;){const{done:e,value:s}=yield i(t.read());if(e)break;n+=r.decode(s,{stream:!0});const c=n.split(/\r?\n/);n=c.pop()||"";for(const e of c)if(e.startsWith("event: "))o=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 t;if("progress"===o){const r=e;t=Object.assign({type:"progress"},r)}else if("complete"===o)t={type:"complete",data:e};else if("error"===o){const r=e;t=Object.assign({type:"error"},r)}else if("preview"===o){const r=e;t=Object.assign(Object.assign({},r),{type:"preview"})}else{if("reasoning"!==o){o="",a="";continue}{const r=e;t=Object.assign(Object.assign({},r),{type:"reasoning"})}}if(yield yield i(t),"complete"===o||"error"===o)return yield i(void 0)}catch(e){this.logger.warn("Invalid SSE data format",a)}o="",a=""}}}finally{t.releaseLock()}})}makeRequest(t,r,i){return e(this,arguments,void 0,function*(e,t,r,i=1,n="POST"){if(!e.startsWith("/"))throw new s("Invalid endpoint: must start with /");const o=new URL(e,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(t)}));if(!c.ok){const o=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 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 ${e} in ${o}ms (attempt ${i+1})`),yield this.sleep(o),this.makeRequest(e,t,r,i+1,n)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),g}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(o){if(o instanceof s)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),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 ${e} in ${o}ms`),yield this.sleep(o),this.makeRequest(e,t,r,i+1,n)}throw this.logger.error(`${this.tag} Network error: ${e}`,o),new s("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",l)}})}}const m=o.enum(["EN_GB","EN_US"]),p=o.custom(e=>null!=e&&"object"==typeof e),f=o.enum(["low","medium","high"]),y=o.enum(["none","low","medium","high"]),b=o.enum(["agentic","fast"]),v=o.object({maxWallClockMs:o.number().positive().optional(),maxTotalTokens:o.number().int().positive().optional(),maxCostUsd:o.number().positive().optional()}),w=o.object({callId:o.string().max(256),locale:m.optional(),effort:f.optional(),storytellingEffort:y.optional().default("low"),budget:v.optional(),executionMode:b.optional()}),$=1e4,j=o.object({config:p,userPrompt:o.string().max(1e4).optional().default(""),metadata:w.optional()}),x=j.extend({maxSuggestionCount:o.number().int().min(1).max(4).optional()}),S=o.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),O=o.object({dataPrepPrompt:o.string(),chartType:S,summary:o.string()}),C=o.object({response:o.object({message:o.string()}),config:p}),k=o.object({suggestions:o.array(O)}),E=o.enum(["comparison","relationship","distribution","composition"]),T=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:E.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.")}),R=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(T).describe("Child findings, sorted by quadrant score desc.")}),P=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),stories:o.array(R)}),A=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),config:p}),q=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),config:p}),N=o.enum(["high","medium","low"]),U=o.object({confidence:N,needsUserInput:o.boolean(),warnings:o.array(o.string()),cellConfidence:o.array(o.object({rowIndex:o.number().int().nonnegative(),columnKey:o.string(),confidence:N,quote:o.string().optional()})).optional()}),D=o.object({score:o.number().min(0).max(1),issues:o.array(o.string()),sufficient:o.boolean(),summary:o.string()}),I=5e5,K=8,M=2097152,B=7340032,F=4*Math.ceil(699050.6666666666),G=4*Math.ceil(2446677.3333333335);function L(e){return e.replace(/\s+/g,"")}const W=o.object({mimeType:o.string().min(1).refine(e=>/^image\/(png|jpeg|jpg|webp|gif)$/i.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:o.string().min(1).max(F).refine(function(e){const t=L(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)},{message:"dataBase64 must be standard base64 (RFC 4648)"})}),z=o.object({sourceText:o.string().max(I).default(""),images:o.array(W).max(8).optional(),metadata:w.optional()}).superRefine((e,t)=>{var r;const i=e.sourceText.trim(),n=null!==(r=e.images)&&void 0!==r?r:[];if(0===i.length&&0===n.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one image",path:["sourceText"]});if(0===n.length)return;n.reduce((e,t)=>e+L(t.dataBase64).length,0)>G&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}),H=o.object({response:o.object({message:o.string()}),config:p,extractMeta:U.nullable(),lastAccuracyEvaluation:D.optional()}),J=o.object({config:p,response:o.object({message:o.string(),steps:o.array(o.string())})}),_=k,Y="/api/v0";class Z{constructor(e){this.client=new h(e)}generateGraph(t,r,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,o=n(t,["storytellingOptions"]),s=yield this.client.fetch(`${Y}/generate`,o,r,i),a=J.parse(s);return this.stripStorytelling(a,e)})}generateGraphStream(t,r){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,i=n(t,["storytellingOptions"]),o=yield this.client.stream(`${Y}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(o,e)})}generateNarrative(t,r,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Y}/narrate`,t,r,i);return C.parse(e)})}generateNarrativeStream(t,r){return e(this,void 0,void 0,function*(){return this.client.stream(`${Y}/narrate`,t,r)})}generateSuggestions(t,r,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Y}/suggestions`,t,r,i);return k.parse(e)})}generateSuggestionsStream(t,r){return e(this,void 0,void 0,function*(){return this.client.stream(`${Y}/suggestions`,t,r)})}generateExploration(t,r,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Y}/explore`,t,r,i);return P.parse(e)})}generateExplorationStream(t,r){return e(this,void 0,void 0,function*(){return this.client.stream(`${Y}/explore`,t,r)})}generateAnnotations(t,r,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Y}/annotate`,t,r,i);return A.parse(e)})}generateAnnotationsStream(t,r){return e(this,void 0,void 0,function*(){return this.client.stream(`${Y}/annotate`,t,r)})}generateMutation(t,r,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Y}/mutate`,t,r,i);return q.parse(e)})}generateMutationStream(t,r){return e(this,void 0,void 0,function*(){return this.client.stream(`${Y}/mutate`,t,r)})}extractFromProse(t,r,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Y}/extract`,t,r,i);return H.parse(e)})}extractFromProseStream(t,r){return e(this,void 0,void 0,function*(){return this.client.stream(`${Y}/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(e,n){return r(this,arguments,function*(){var r,o,s,a;try{for(var c,g=!0,d=t(e);!(r=(c=yield i(d.next())).done);g=!0){a=c.value,g=!1;const e=a;if(l(e)){const t=this.stripStorytelling(e.data,n);yield yield i(Object.assign(Object.assign({},e),{data:t}))}else yield yield i(e)}}catch(e){o={error:e}}finally{try{g||r||!(s=d.return)||(yield i(s.call(d)))}finally{if(o)throw o.error}}})}}export{S as AiChartTypeEnum,E as ChartFamilySchema,b as ExecutionModeSchema,T as ExploreFindingSchema,R as ExploreStorySchema,D as ExtractAccuracyEvaluationSchema,N as ExtractConfidenceSchema,z as ExtractFromProseParamsSchema,H as ExtractFromProseResponseSchema,U as ExtractMetaSchema,A as GenerateAnnotationsResponseSchema,P as GenerateExplorationResponseSchema,J as GenerateGraphResponseSchema,_ as GenerateGraphSuggestionsResponseSchema,q as GenerateMutationResponseSchema,C as GenerateNarrativeResponseSchema,x as GenerateSuggestionsParamsSchema,k as GenerateSuggestionsResponseSchema,j as GraphGenerationRequestSchema,Z as GraphyAiSdk,s as GraphyApiError,v as InvocationBudgetSchema,f as InvocationEffortSchema,K as MAX_EXTRACT_IMAGES,B as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,M as MAX_EXTRACT_IMAGE_DECODED_BYTES,I as MAX_SOURCE_TEXT_LENGTH,$ as MAX_USER_PROMPT_LENGTH,w as MetadataSchema,y as StorytellingEffortSchema,O as SuggestionSchema,l as isCompleteEvent,g as isErrorEvent,a as isGraphyApiError,d as isPreviewEvent,c as isProgressEvent,u as isReasoningEvent};
|
|
1
|
+
import{__awaiter as e,__asyncValues as t,__asyncGenerator as i,__await as r,__rest as n}from"tslib";import{z as s}from"zod";class o extends Error{constructor(e,t){var i;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!==(i=null==t?void 0:t.retryable)&&void 0!==i&&i}}const a=e=>e instanceof o,c=e=>"progress"===e.type,l=e=>"complete"===e.type,d=e=>"error"===e.type,m=e=>"preview"===e.type,g=e=>"reasoning"===e.type;class u{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 c(e)}static isCompleteEvent(e){return l(e)}static isErrorEvent(e){return d(e)}stream(t,i,r){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,i,r);return this.parseSSE(e)})}fetch(i,r,n,s){return e(this,void 0,void 0,function*(){var e,a,m,g,u;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const b=yield this.makeRequest(i,r,s),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var p,f=!0,y=t(this.parseSSE(b));!(e=(p=yield y.next()).done);f=!0){g=p.value,f=!1;const e=g;if(c(e)&&n&&n(e),l(e))return e.data;if(d(e)){const t=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new o(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){a={error:e}}finally{try{f||e||!(m=y.return)||(yield m.call(y))}finally{if(a)throw a.error}}const r=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${r}ms`),new o("Stream ended without completion")}return yield b.json()}catch(e){const t=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof o)throw e;throw e}finally{const e=Date.now()-h;this.logger.debug(`${this.tag} Fetch completed: ${i} ${e}ms`)}})}ping(){return e(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(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return i(this,arguments,function*(){if(!e.body)throw new o("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let n="",s="",a="";try{for(;;){const{done:e,value:o}=yield r(t.read());if(e)break;n+=i.decode(o,{stream:!0});const c=n.split(/\r?\n/);n=c.pop()||"";for(const e of c)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 t;if("progress"===s){const i=e;t=Object.assign({type:"progress"},i)}else if("complete"===s)t={type:"complete",data:e};else if("error"===s){const i=e;t=Object.assign({type:"error"},i)}else if("preview"===s){const i=e;t=Object.assign(Object.assign({},i),{type:"preview"})}else{if("reasoning"!==s){s="",a="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield r(t),"complete"===s||"error"===s)return yield r(void 0)}catch(e){this.logger.warn("Invalid SSE data format",a)}s="",a=""}}}finally{t.releaseLock()}})}makeRequest(t,i,r){return e(this,arguments,void 0,function*(e,t,i,r=1,n="POST"){if(!e.startsWith("/"))throw new o("Invalid endpoint: must start with /");const s=new URL(e,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new o("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${r}/${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: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(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 d=new o(l,{status:c.status,code:a,retryable:s});if(s&&r<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${s}ms (attempt ${r+1})`),yield this.sleep(s),this.makeRequest(e,t,i,r+1,n)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),d}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(s){if(s instanceof o)throw s;if(s instanceof Error&&"AbortError"===s.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),s;if(r<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${s}ms`),yield this.sleep(s),this.makeRequest(e,t,i,r+1,n)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new o("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const h=s.enum(["EN_GB","EN_US"]),p=s.custom(e=>null!=e&&"object"==typeof e),f=s.enum(["low","medium","high"]),y=s.enum(["none","low","medium","high"]),b=s.enum(["agentic","fast"]),v=s.object({maxWallClockMs:s.number().positive().optional(),maxTotalTokens:s.number().int().positive().optional(),maxCostUsd:s.number().positive().optional()}),w=s.object({callId:s.string().max(256),locale:h.optional(),effort:f.optional(),storytellingEffort:y.optional().default("low"),budget:v.optional(),executionMode:b.optional()}),x=1e4,$=s.object({config:p,userPrompt:s.string().max(1e4).optional().default(""),metadata:w.optional()}),j=$.extend({maxSuggestionCount:s.number().int().min(1).max(4).optional()}),S=s.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),k=s.object({dataPrepPrompt:s.string(),chartType:S,summary:s.string()}),C=s.object({response:s.object({message:s.string()}),config:p}),O=s.object({suggestions:s.array(k)}),T=s.enum(["comparison","relationship","distribution","composition"]),E=s.object({finding:s.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:s.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:s.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:s.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:s.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:T.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:s.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),I=s.object({topic:s.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:s.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:s.number().int().min(1).describe("Number of findings in this story."),findings:s.array(E).describe("Child findings, sorted by quadrant score desc.")}),R=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),stories:s.array(I)}),P=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),A=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),B=s.enum(["high","medium","low"]),U=s.object({confidence:B,needsUserInput:s.boolean(),warnings:s.array(s.string()),cellConfidence:s.array(s.object({rowIndex:s.number().int().nonnegative(),columnKey:s.string(),confidence:B,quote:s.string().optional()})).optional()}),M=s.object({score:s.number().min(0).max(1),issues:s.array(s.string()),sufficient:s.boolean(),summary:s.string()}),q=5e5,N=8,D=2097152,K=7340032,F=2,G=6291456,W=8388608,L=12582912,z=10,H=4*Math.ceil(699050.6666666666),J=4*Math.ceil(2446677.3333333335),_=4*Math.ceil(2097152),Y=4*Math.ceil(2796202.6666666665),Z=4*Math.ceil(4194304);function Q(e){return e.replace(/\s+/g,"")}function V(e){const t=Q(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const X=/^image\/(png|jpeg|jpg|webp|gif)$/i,ee=s.object({mimeType:s.string().min(1).refine(e=>X.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:s.string().min(1).max(H).refine(V,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),te=s.enum(["image","document"]),ie=ee.extend({kind:s.literal("image")}),re=s.object({kind:s.literal("document"),mimeType:s.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:s.string().min(1).max(_).refine(V,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ne=s.discriminatedUnion("kind",[ie,re]),se=s.object({sourceText:s.string().max(q).default(""),images:s.array(ee).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:s.array(ne).max(10).optional(),metadata:w.optional()}).superRefine((e,t)=>{var i,r;const n=e.sourceText.trim(),s=null!==(i=e.images)&&void 0!==i?i:[],o=null!==(r=e.attachments)&&void 0!==r?r:[];if(s.length>0&&o.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===n.length&&0===s.length&&0===o.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(s.length>0){s.reduce((e,t)=>e+Q(t.dataBase64).length,0)>J&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}const a=o.filter(e=>"image"===e.kind).length,c=o.length-a;if(a>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),o.length>0&&a<=8&&c<=2){let e=0,i=0,r=0;for(const t of o){const n=Q(t.dataBase64).length;r+=n,"image"===t.kind?e+=n:i+=n}e>J&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),i>Y&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),r>Z&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]})}});function oe(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:Q(e.dataBase64)}}function ae(e){return{kind:"document",mimeType:"application/pdf",dataBase64:Q(e.dataBase64)}}const ce=s.object({response:s.object({message:s.string()}),config:p,extractMeta:U.nullable(),lastAccuracyEvaluation:M.optional()}),le=s.object({config:p,response:s.object({message:s.string(),steps:s.array(s.string())})}),de=O,me="/api/v0";class ge{constructor(e){this.client=new u(e)}generateGraph(t,i,r){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,s=n(t,["storytellingOptions"]),o=yield this.client.fetch(`${me}/generate`,s,i,r),a=le.parse(o);return this.stripStorytelling(a,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,r=n(t,["storytellingOptions"]),s=yield this.client.stream(`${me}/generate`,r,i);return this.wrapStreamWithStorytellingStripping(s,e)})}generateNarrative(t,i,r){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${me}/narrate`,t,i,r);return C.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${me}/narrate`,t,i)})}generateSuggestions(t,i,r){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${me}/suggestions`,t,i,r);return O.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${me}/suggestions`,t,i)})}generateExploration(t,i,r){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${me}/explore`,t,i,r);return R.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${me}/explore`,t,i)})}generateAnnotations(t,i,r){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${me}/annotate`,t,i,r);return P.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${me}/annotate`,t,i)})}generateMutation(t,i,r){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${me}/mutate`,t,i,r);return A.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${me}/mutate`,t,i)})}extractFromProse(t,i,r){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${me}/extract`,t,i,r);return ce.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${me}/extract`,t,i)})}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(e,n){return i(this,arguments,function*(){var i,s,o,a;try{for(var c,d=!0,m=t(e);!(i=(c=yield r(m.next())).done);d=!0){a=c.value,d=!1;const e=a;if(l(e)){const t=this.stripStorytelling(e.data,n);yield yield r(Object.assign(Object.assign({},e),{data:t}))}else yield yield r(e)}}catch(e){s={error:e}}finally{try{d||i||!(o=m.return)||(yield r(o.call(m)))}finally{if(s)throw s.error}}})}}export{S as AiChartTypeEnum,T as ChartFamilySchema,b as ExecutionModeSchema,E as ExploreFindingSchema,I as ExploreStorySchema,M as ExtractAccuracyEvaluationSchema,ne as ExtractAttachmentInputSchema,te as ExtractAttachmentKindSchema,B as ExtractConfidenceSchema,se as ExtractFromProseParamsSchema,ce as ExtractFromProseResponseSchema,U as ExtractMetaSchema,P as GenerateAnnotationsResponseSchema,R as GenerateExplorationResponseSchema,le as GenerateGraphResponseSchema,de as GenerateGraphSuggestionsResponseSchema,A as GenerateMutationResponseSchema,C as GenerateNarrativeResponseSchema,j as GenerateSuggestionsParamsSchema,O as GenerateSuggestionsResponseSchema,$ as GraphGenerationRequestSchema,ge as GraphyAiSdk,o as GraphyApiError,v as InvocationBudgetSchema,f as InvocationEffortSchema,z as MAX_EXTRACT_ATTACHMENTS,L as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,F as MAX_EXTRACT_DOCUMENTS,W as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,G as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,N as MAX_EXTRACT_IMAGES,K as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,D as MAX_EXTRACT_IMAGE_DECODED_BYTES,q as MAX_SOURCE_TEXT_LENGTH,x as MAX_USER_PROMPT_LENGTH,w as MetadataSchema,y as StorytellingEffortSchema,k as SuggestionSchema,oe as buildImageAttachment,ae as buildPdfAttachment,l as isCompleteEvent,d as isErrorEvent,a as isGraphyApiError,m as isPreviewEvent,c as isProgressEvent,g 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.1778059383500",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"files": [
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
20
|
"zod": "^4.3.6",
|
|
21
|
-
"@graphysdk/core": "1.3.0-beta.
|
|
21
|
+
"@graphysdk/core": "1.3.0-beta.1778059383500"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|