@graphysdk/agents-sdk 1.4.0 → 1.5.0-beta.1779451530994
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 +54 -19
- 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 a=e=>"progress"===e.type,s=e=>"complete"===e.type,i=e=>"error"===e.type;class n{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 a(e)}static isCompleteEvent(e){return s(e)}static isErrorEvent(e){return i(e)}stream(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,a);return this.parseSSE(e)})}fetch(t,n,o,c){return e.__awaiter(this,void 0,void 0,function*(){var m,l,d,u,p;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,n,c),x=b.headers.get("content-type");if(null==x?void 0:x.includes("text/event-stream")){try{for(var h,f=!0,y=e.__asyncValues(this.parseSSE(b));!(m=(h=yield y.next()).done);f=!0){u=h.value,f=!1;const e=u;if(a(e)&&o&&o(e),s(e))return e.data;if(i(e)){const a=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(p=e.retryable)&&void 0!==p&&p})}}}catch(e){l={error:e}}finally{try{f||m||!(d=y.return)||(yield d.call(y))}finally{if(l)throw l.error}}const n=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${n}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const a=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-g;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 a=t.body.getReader(),s=new TextDecoder;let i="",n="",o="";try{for(;;){const{done:t,value:r}=yield e.__await(a.read());if(t)break;i+=s.decode(r,{stream:!0});const c=i.split(/\r?\n/);i=c.pop()||"";for(const t of c)if(t.startsWith("event: "))n=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"===n){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===n)r={type:"complete",data:t};else if("error"===n){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===n){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==n){n="",o="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===n||"error"===n)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}n="",o=""}}}finally{a.releaseLock()}})}makeRequest(t,a,s){return e.__awaiter(this,arguments,void 0,function*(e,t,a,s=1,i="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const n=new URL(e,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${s}/${this.retryConfig.attempts}: ${n}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),m=()=>o.abort();a&&a.addEventListener("abort",m);try{const c=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:o.signal},"POST"===i&&{body:JSON.stringify(t)}));if(!c.ok){const n=c.status>=500||429===c.status;let o,m=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?m=t.message:"string"==typeof t.error&&(m=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=new r(m,{status:c.status,code:o,retryable:n});if(n&&s<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,s-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${s+1})`),yield this.sleep(r),this.makeRequest(e,t,a,s+1,i)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${m}`),l}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),n;if(s<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,s-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,a,s+1,i)}throw this.logger.error(`${this.tag} Network error: ${e}`,n),new r("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",m)}})}}const o=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),m=t.z.enum(["low","medium","high"]),l=t.z.enum(["none","low","medium","high"]),d=t.z.enum(["agentic","fast"]),u=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:o.optional(),effort:m.optional(),storytellingEffort:l.optional().default("low"),budget:u.optional(),executionMode:d.optional()}),g=t.z.object({config:c,userPrompt:t.z.string().max(1e4).optional().default(""),metadata:p.optional()}),h=g.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),f=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),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"]),z=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(z).describe("Child findings, sorted by quadrant score desc.")}),S=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(_)}),w=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"]),A=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()}),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()}),j=5e5,$=2097152,R=7340032,k=6291456,O=8388608,D=k,M=O,P=12582912;function I(e){return 4*Math.ceil(e/3)}const G=I($),B=I(R),X=I(k),N=I(O),F=I(D),U=I(M),q=I(P);function K(e){return e.replace(/\s+/g,"")}function L(e){const t=K(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const H=/^image\/(png|jpeg|jpg|webp|gif)$/i,Y=t.z.object({mimeType:t.z.string().min(1).refine(e=>H.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(G).refine(L,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),W=t.z.enum(["image","document","spreadsheet"]),V=Y.extend({kind:t.z.literal("image")}),J=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(X).refine(L,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Z=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(F).refine(L,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),Q=t.z.discriminatedUnion("kind",[V,J,Z]),ee=t.z.object({sourceText:t.z.string().max(j).default(""),images:t.z.array(Y).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(Q).max(12).optional(),metadata:p.optional()}).superRefine((e,t)=>{var r,a;const s=e.sourceText.trim(),i=null!==(r=e.images)&&void 0!==r?r:[],n=null!==(a=e.attachments)&&void 0!==a?a:[];if(i.length>0&&n.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===s.length&&0===i.length&&0===n.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(i.length>0){i.reduce((e,t)=>e+K(t.dataBase64).length,0)>B&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,m=0,l=0,d=0,u=0,p=0;for(const e of n){const t=K(e.dataBase64).length;switch(p+=t,e.kind){case"image":o+=1,l+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":m+=1,u+=t}}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"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const g=o<=8&&c<=2&&m<=2;n.length>0&&g&&(l>B&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>N&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>U&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>q&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const te=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:A.nullable(),lastAccuracyEvaluation:C.optional()}),re=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),ae=x,se=t.z.enum(["deal-breaker","pro","con","family","specificity","continuity"]),ie=t.z.object({kind:se,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),ne=t.z.enum(["ok","disqualified"]),oe=t.z.object({rank:t.z.number().int().positive(),type:f,score:t.z.number(),verdict:ne,factors:t.z.array(ie)}),ce=g.extend({chartFamily:v.optional()}),me=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures"]),le=t.z.object({kind:me,message:t.z.string()}),de=t.z.enum(["sum","avg","count","min","max"]),ue=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:de,chartType:f,score:t.z.number(),message:t.z.string()}),pe=t.z.object({ranking:t.z.array(oe),observations:t.z.array(le).optional().default([]),suggestions:t.z.array(ue).optional().default([])}),ge="/api/v0";exports.AggregationFunctionSchema=de,exports.AggregationSuggestionSchema=ue,exports.AiChartTypeEnum=f,exports.ChartFamilySchema=v,exports.ChartFitEntrySchema=oe,exports.ChartFitFactorKindSchema=se,exports.ChartFitFactorSchema=ie,exports.ChartFitVerdictSchema=ne,exports.DataObservationKindSchema=me,exports.DataObservationSchema=le,exports.EvaluateParamsSchema=ce,exports.EvaluateResponseSchema=pe,exports.ExecutionModeSchema=d,exports.ExploreFindingSchema=z,exports.ExploreStorySchema=_,exports.ExtractAccuracyEvaluationSchema=C,exports.ExtractAttachmentInputSchema=Q,exports.ExtractAttachmentKindSchema=W,exports.ExtractConfidenceSchema=T,exports.ExtractFromProseParamsSchema=ee,exports.ExtractFromProseResponseSchema=te,exports.ExtractMetaSchema=A,exports.GenerateAnnotationsResponseSchema=w,exports.GenerateExplorationResponseSchema=S,exports.GenerateGraphResponseSchema=re,exports.GenerateGraphSuggestionsResponseSchema=ae,exports.GenerateMutationResponseSchema=E,exports.GenerateNarrativeResponseSchema=b,exports.GenerateSuggestionsParamsSchema=h,exports.GenerateSuggestionsResponseSchema=x,exports.GraphGenerationRequestSchema=g,exports.GraphyAiSdk=class{constructor(e){this.client=new n(e)}generateGraph(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:s}=t,i=e.__rest(t,["storytellingOptions"]),n=yield this.client.fetch(`${ge}/generate`,i,r,a),o=re.parse(n);return this.stripStorytelling(o,s)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,s=e.__rest(t,["storytellingOptions"]),i=yield this.client.stream(`${ge}/generate`,s,r);return this.wrapStreamWithStorytellingStripping(i,a)})}generateNarrative(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ge}/narrate`,t,r,a);return b.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ge}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ge}/suggestions`,t,r,a);return x.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ge}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ge}/explore`,t,r,a);return S.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ge}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ge}/annotate`,t,r,a);return w.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ge}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ge}/mutate`,t,r,a);return E.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ge}/mutate`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ge}/evaluate`,t,void 0,r);return pe.parse(e)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ge}/extract`,t,r,a);return te.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ge}/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 a,i,n,o;try{for(var c,m=!0,l=e.__asyncValues(t);!(a=(c=yield e.__await(l.next())).done);m=!0){o=c.value,m=!1;const t=o;if(s(t)){const a=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){i={error:e}}finally{try{m||a||!(n=l.return)||(yield e.__await(n.call(l)))}finally{if(i)throw i.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=u,exports.InvocationEffortSchema=m,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=P,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=O,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=k,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=R,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=$,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=M,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=D,exports.MAX_SOURCE_TEXT_LENGTH=j,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=p,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=y,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:K(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:K(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:K(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=s,exports.isErrorEvent=i,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,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 a=e=>"progress"===e.type,s=e=>"complete"===e.type,i=e=>"error"===e.type;class n{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 a(e)}static isCompleteEvent(e){return s(e)}static isErrorEvent(e){return i(e)}stream(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,a);return this.parseSSE(e)})}fetch(t,n,o,c){return e.__awaiter(this,void 0,void 0,function*(){var m,l,d,p,u;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,n,c),x=b.headers.get("content-type");if(null==x?void 0:x.includes("text/event-stream")){try{for(var h,f=!0,y=e.__asyncValues(this.parseSSE(b));!(m=(h=yield y.next()).done);f=!0){p=h.value,f=!1;const e=p;if(a(e)&&o&&o(e),s(e))return e.data;if(i(e)){const a=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){l={error:e}}finally{try{f||m||!(d=y.return)||(yield d.call(y))}finally{if(l)throw l.error}}const n=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${n}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const a=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-g;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 a=t.body.getReader(),s=new TextDecoder;let i="",n="",o="";try{for(;;){const{done:t,value:r}=yield e.__await(a.read());if(t)break;i+=s.decode(r,{stream:!0});const c=i.split(/\r?\n/);i=c.pop()||"";for(const t of c)if(t.startsWith("event: "))n=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"===n){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===n)r={type:"complete",data:t};else if("error"===n){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===n){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==n){n="",o="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===n||"error"===n)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}n="",o=""}}}finally{a.releaseLock()}})}makeRequest(t,a,s){return e.__awaiter(this,arguments,void 0,function*(e,t,a,s=1,i="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const n=new URL(e,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${s}/${this.retryConfig.attempts}: ${n}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),m=()=>o.abort();a&&a.addEventListener("abort",m);try{const c=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:o.signal},"POST"===i&&{body:JSON.stringify(t)}));if(!c.ok){const n=c.status>=500||429===c.status;let o,m=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?m=t.message:"string"==typeof t.error&&(m=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=new r(m,{status:c.status,code:o,retryable:n});if(n&&s<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,s-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${s+1})`),yield this.sleep(r),this.makeRequest(e,t,a,s+1,i)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${m}`),l}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),n;if(s<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,s-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,a,s+1,i)}throw this.logger.error(`${this.tag} Network error: ${e}`,n),new r("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",m)}})}}const o=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),m=t.z.enum(["low","medium","high"]),l=t.z.enum(["none","low","medium","high"]),d=t.z.enum(["agentic","fast"]),p=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).optional(),locale:o.optional(),effort:m.optional(),storytellingEffort:l.optional().default("low"),budget:p.optional(),executionMode:d.optional()}),g=1e4,h=t.z.object({config:c,userPrompt:t.z.string().max(g).optional().default(""),metadata:u.optional()}),f=h.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),y=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),b=t.z.object({dataPrepPrompt:t.z.string(),chartType:y,summary:t.z.string()}),x=h.extend({userPrompt:t.z.string().max(g)}),v=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),z=t.z.object({suggestions:t.z.array(b)}),_=t.z.enum(["comparison","relationship","distribution","composition"]),S=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:_.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(S).describe("Child findings, sorted by quadrant score desc.")}),E=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(w)}),T=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),A=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),C=t.z.enum(["high","medium","low"]),j=t.z.object({confidence:C,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:C,quote:t.z.string().optional()})).optional()}),$=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()}),R=5e5,k=2097152,O=7340032,D=6291456,M=8388608,P=D,I=M,G=12582912;function B(e){return 4*Math.ceil(e/3)}const X=B(k),N=B(O),F=B(D),U=B(M),q=B(P),K=B(I),L=B(G);function H(e){return e.replace(/\s+/g,"")}function Y(e){const t=H(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const W=/^image\/(png|jpeg|jpg|webp|gif)$/i,V=t.z.object({mimeType:t.z.string().min(1).refine(e=>W.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(X).refine(Y,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),J=t.z.enum(["image","document","spreadsheet"]),Z=V.extend({kind:t.z.literal("image")}),Q=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(F).refine(Y,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ee=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(q).refine(Y,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),te=t.z.discriminatedUnion("kind",[Z,Q,ee]),re=t.z.object({sourceText:t.z.string().max(R).default(""),images:t.z.array(V).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(te).max(12).optional(),metadata:u.optional()}).superRefine((e,t)=>{var r,a;const s=e.sourceText.trim(),i=null!==(r=e.images)&&void 0!==r?r:[],n=null!==(a=e.attachments)&&void 0!==a?a:[];if(i.length>0&&n.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===s.length&&0===i.length&&0===n.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(i.length>0){i.reduce((e,t)=>e+H(t.dataBase64).length,0)>N&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,m=0,l=0,d=0,p=0,u=0;for(const e of n){const t=H(e.dataBase64).length;switch(u+=t,e.kind){case"image":o+=1,l+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":m+=1,p+=t}}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"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const g=o<=8&&c<=2&&m<=2;n.length>0&&g&&(l>N&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>U&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>K&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>L&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const ae=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:j.nullable(),lastAccuracyEvaluation:$.optional()}),se=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),ie=z,ne=t.z.enum(["deal-breaker","pro","con","family","specificity","continuity"]),oe=t.z.object({kind:ne,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),ce=t.z.enum(["ok","disqualified"]),me=t.z.object({rank:t.z.number().int().positive(),type:y,score:t.z.number(),verdict:ce,factors:t.z.array(oe)}),le=t.z.object({config:c,chartFamily:_.optional(),metadata:u.optional()}),de=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures"]),pe=t.z.object({kind:de,message:t.z.string()}),ue=t.z.enum(["sum","avg","count","min","max"]),ge=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:ue,chartType:y,score:t.z.number(),message:t.z.string()}),he=t.z.object({ranking:t.z.array(me),observations:t.z.array(pe).optional().default([]),suggestions:t.z.array(ge).optional().default([])}),fe="/api/v0";exports.AggregationFunctionSchema=ue,exports.AggregationSuggestionSchema=ge,exports.AiChartTypeEnum=y,exports.ChartFamilySchema=_,exports.ChartFitEntrySchema=me,exports.ChartFitFactorKindSchema=ne,exports.ChartFitFactorSchema=oe,exports.ChartFitVerdictSchema=ce,exports.DataObservationKindSchema=de,exports.DataObservationSchema=pe,exports.EvaluateParamsSchema=le,exports.EvaluateResponseSchema=he,exports.ExecutionModeSchema=d,exports.ExploreFindingSchema=S,exports.ExploreStorySchema=w,exports.ExtractAccuracyEvaluationSchema=$,exports.ExtractAttachmentInputSchema=te,exports.ExtractAttachmentKindSchema=J,exports.ExtractConfidenceSchema=C,exports.ExtractFromProseParamsSchema=re,exports.ExtractFromProseResponseSchema=ae,exports.ExtractMetaSchema=j,exports.GenerateAnnotationsResponseSchema=T,exports.GenerateExplorationResponseSchema=E,exports.GenerateGraphResponseSchema=se,exports.GenerateGraphSuggestionsResponseSchema=ie,exports.GenerateMutationResponseSchema=A,exports.GenerateNarrativeParamsSchema=x,exports.GenerateNarrativeResponseSchema=v,exports.GenerateSuggestionsParamsSchema=f,exports.GenerateSuggestionsResponseSchema=z,exports.GraphGenerationRequestSchema=h,exports.GraphyAiSdk=class{constructor(e){this.client=new n(e)}generateGraph(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:s}=t,i=e.__rest(t,["storytellingOptions"]),n=yield this.client.fetch(`${fe}/generate`,i,r,a),o=se.parse(n);return this.stripStorytelling(o,s)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,s=e.__rest(t,["storytellingOptions"]),i=yield this.client.stream(`${fe}/generate`,s,r);return this.wrapStreamWithStorytellingStripping(i,a)})}generateNarrative(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/narrate`,t,r,a);return v.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/suggestions`,t,r,a);return z.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/explore`,t,r,a);return E.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/annotate`,t,r,a);return T.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/mutate`,t,r,a);return A.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/mutate`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/evaluate`,t,void 0,r);return he.parse(e)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/extract`,t,r,a);return ae.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/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 a,i,n,o;try{for(var c,m=!0,l=e.__asyncValues(t);!(a=(c=yield e.__await(l.next())).done);m=!0){o=c.value,m=!1;const t=o;if(s(t)){const a=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){i={error:e}}finally{try{m||a||!(n=l.return)||(yield e.__await(n.call(l)))}finally{if(i)throw i.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=p,exports.InvocationEffortSchema=m,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=G,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=M,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=D,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=O,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=k,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=I,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=P,exports.MAX_SOURCE_TEXT_LENGTH=R,exports.MAX_USER_PROMPT_LENGTH=g,exports.MetadataSchema=u,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=b,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:H(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:H(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:H(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=s,exports.isErrorEvent=i,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,exports.isReasoningEvent=e=>"reasoning"===e.type;
|
package/dist/index.d.ts
CHANGED
|
@@ -308,7 +308,7 @@ type InvocationBudget = z.infer<typeof InvocationBudgetSchema>;
|
|
|
308
308
|
* `MetadataSchema` in `apps/agents-api/src/modules/api/api.types.ts`.
|
|
309
309
|
*/
|
|
310
310
|
declare const MetadataSchema: z.ZodObject<{
|
|
311
|
-
callId: z.ZodString
|
|
311
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
312
312
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
313
313
|
EN_GB: "EN_GB";
|
|
314
314
|
EN_US: "EN_US";
|
|
@@ -346,7 +346,7 @@ declare const GraphGenerationRequestSchema: z.ZodObject<{
|
|
|
346
346
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
347
347
|
userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
348
348
|
metadata: z.ZodOptional<z.ZodObject<{
|
|
349
|
-
callId: z.ZodString
|
|
349
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
350
350
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
351
351
|
EN_GB: "EN_GB";
|
|
352
352
|
EN_US: "EN_US";
|
|
@@ -379,7 +379,7 @@ declare const GenerateSuggestionsParamsSchema: z.ZodObject<{
|
|
|
379
379
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
380
380
|
userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
381
381
|
metadata: z.ZodOptional<z.ZodObject<{
|
|
382
|
-
callId: z.ZodString
|
|
382
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
383
383
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
384
384
|
EN_GB: "EN_GB";
|
|
385
385
|
EN_US: "EN_US";
|
|
@@ -458,7 +458,42 @@ declare const SuggestionSchema: z.ZodObject<{
|
|
|
458
458
|
summary: z.ZodString;
|
|
459
459
|
}, z.core.$strip>;
|
|
460
460
|
type Suggestion = z.infer<typeof SuggestionSchema>;
|
|
461
|
-
|
|
461
|
+
/**
|
|
462
|
+
* Request body for `POST /v0/narrate`. Unlike the other agents, `userPrompt` is
|
|
463
|
+
* required — the narrative agent needs an instruction to write against.
|
|
464
|
+
*/
|
|
465
|
+
declare const GenerateNarrativeParamsSchema: z.ZodObject<{
|
|
466
|
+
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
467
|
+
metadata: z.ZodOptional<z.ZodObject<{
|
|
468
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
469
|
+
locale: z.ZodOptional<z.ZodEnum<{
|
|
470
|
+
EN_GB: "EN_GB";
|
|
471
|
+
EN_US: "EN_US";
|
|
472
|
+
}>>;
|
|
473
|
+
effort: z.ZodOptional<z.ZodEnum<{
|
|
474
|
+
low: "low";
|
|
475
|
+
medium: "medium";
|
|
476
|
+
high: "high";
|
|
477
|
+
}>>;
|
|
478
|
+
storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
|
|
479
|
+
low: "low";
|
|
480
|
+
medium: "medium";
|
|
481
|
+
high: "high";
|
|
482
|
+
none: "none";
|
|
483
|
+
}>>>;
|
|
484
|
+
budget: z.ZodOptional<z.ZodObject<{
|
|
485
|
+
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
486
|
+
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
487
|
+
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
488
|
+
}, z.core.$strip>>;
|
|
489
|
+
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
490
|
+
agentic: "agentic";
|
|
491
|
+
fast: "fast";
|
|
492
|
+
}>>;
|
|
493
|
+
}, z.core.$strip>>;
|
|
494
|
+
userPrompt: z.ZodString;
|
|
495
|
+
}, z.core.$strip>;
|
|
496
|
+
type GenerateNarrativeParams = z.input<typeof GenerateNarrativeParamsSchema>;
|
|
462
497
|
declare const GenerateNarrativeResponseSchema: z.ZodObject<{
|
|
463
498
|
response: z.ZodObject<{
|
|
464
499
|
message: z.ZodString;
|
|
@@ -701,7 +736,7 @@ declare const ExtractFromProseParamsSchema: z.ZodObject<{
|
|
|
701
736
|
filename: z.ZodOptional<z.ZodString>;
|
|
702
737
|
}, z.core.$strip>], "kind">>>;
|
|
703
738
|
metadata: z.ZodOptional<z.ZodObject<{
|
|
704
|
-
callId: z.ZodString
|
|
739
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
705
740
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
706
741
|
EN_GB: "EN_GB";
|
|
707
742
|
EN_US: "EN_US";
|
|
@@ -915,15 +950,21 @@ declare const ChartFitEntrySchema: z.ZodObject<{
|
|
|
915
950
|
}, z.core.$strip>;
|
|
916
951
|
type ChartFitEntry = z.infer<typeof ChartFitEntrySchema>;
|
|
917
952
|
/**
|
|
918
|
-
* Request body for `POST /v0/evaluate`.
|
|
919
|
-
*
|
|
920
|
-
*
|
|
953
|
+
* Request body for `POST /v0/evaluate`. Evaluation is deterministic — it reads only
|
|
954
|
+
* `config.data` and the optional `chartFamily`, so this is its own type rather than a
|
|
955
|
+
* reuse of `GraphGenerationRequestSchema`: there is no `userPrompt`. Server-side,
|
|
956
|
+
* `config.type`, brand kit, and annotations are also ignored.
|
|
921
957
|
*/
|
|
922
958
|
declare const EvaluateParamsSchema: z.ZodObject<{
|
|
923
959
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
924
|
-
|
|
960
|
+
chartFamily: z.ZodOptional<z.ZodEnum<{
|
|
961
|
+
comparison: "comparison";
|
|
962
|
+
relationship: "relationship";
|
|
963
|
+
distribution: "distribution";
|
|
964
|
+
composition: "composition";
|
|
965
|
+
}>>;
|
|
925
966
|
metadata: z.ZodOptional<z.ZodObject<{
|
|
926
|
-
callId: z.ZodString
|
|
967
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
927
968
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
928
969
|
EN_GB: "EN_GB";
|
|
929
970
|
EN_US: "EN_US";
|
|
@@ -949,12 +990,6 @@ declare const EvaluateParamsSchema: z.ZodObject<{
|
|
|
949
990
|
fast: "fast";
|
|
950
991
|
}>>;
|
|
951
992
|
}, z.core.$strip>>;
|
|
952
|
-
chartFamily: z.ZodOptional<z.ZodEnum<{
|
|
953
|
-
comparison: "comparison";
|
|
954
|
-
relationship: "relationship";
|
|
955
|
-
distribution: "distribution";
|
|
956
|
-
composition: "composition";
|
|
957
|
-
}>>;
|
|
958
993
|
}, z.core.$strip>;
|
|
959
994
|
type EvaluateParams = z.input<typeof EvaluateParamsSchema>;
|
|
960
995
|
/**
|
|
@@ -1403,8 +1438,8 @@ declare class GraphyAiSdk {
|
|
|
1403
1438
|
* returns the full ranking with per-type factor breakdowns. Deterministic, no LLM call.
|
|
1404
1439
|
*
|
|
1405
1440
|
* @remarks
|
|
1406
|
-
* - The server only reads `config.data` and the optional `chartFamily`. Other fields
|
|
1407
|
-
* `
|
|
1441
|
+
* - The server only reads `config.data` and the optional `chartFamily`. Other fields on
|
|
1442
|
+
* `config` (`config.type`, brand kit, annotations) are accepted-and-ignored.
|
|
1408
1443
|
* - `config.type` is silently ignored: this endpoint reports intrinsic chart fit and does not
|
|
1409
1444
|
* apply the mutate-agent's continuity bonus. To honor the current chart type, use {@link generateMutation}.
|
|
1410
1445
|
* - Disqualified types are returned at the tail of the ranking with `verdict: 'disqualified'`,
|
|
@@ -1521,5 +1556,5 @@ declare class GraphyAiSdk {
|
|
|
1521
1556
|
private wrapStreamWithStorytellingStripping;
|
|
1522
1557
|
}
|
|
1523
1558
|
|
|
1524
|
-
export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, 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_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
|
|
1559
|
+
export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeParamsSchema, 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_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
|
|
1525
1560
|
export type { AggregationFunction, AggregationSuggestion, AiChartType, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, ClientConfig, CompleteEvent, DataObservation, DataObservationKind, ErrorEvent, EvaluateParams, EvaluateResponse, 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 i,__await as n,__rest as r}from"tslib";import{z as s}from"zod";class a 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 o=e=>e instanceof a,c=e=>"progress"===e.type,l=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type;class g{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 m(e)}stream(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,i,n);return this.parseSSE(e)})}fetch(i,n,r,s){return e(this,void 0,void 0,function*(){var e,o,d,u,g;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const y=yield this.makeRequest(i,n,s),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var p,f=!0,b=t(this.parseSSE(y));!(e=(p=yield b.next()).done);f=!0){u=p.value,f=!1;const e=u;if(c(e)&&r&&r(e),l(e))return e.data;if(m(e)){const t=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(g=e.retryable)&&void 0!==g&&g})}}}catch(e){o={error:e}}finally{try{f||e||!(d=b.return)||(yield d.call(b))}finally{if(o)throw o.error}}const n=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${n}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof a)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 a("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let r="",s="",o="";try{for(;;){const{done:e,value:a}=yield n(t.read());if(e)break;r+=i.decode(a,{stream:!0});const c=r.split(/\r?\n/);r=c.pop()||"";for(const e of c)if(e.startsWith("event: "))s=e.slice(7).trim();else if(e.startsWith("data: "))o+=(o?"\n":"")+e.slice(6);else if(""===e.trim()&&o){try{const e=JSON.parse(o);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="",o="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield n(t),"complete"===s||"error"===s)return yield n(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}s="",o=""}}}finally{t.releaseLock()}})}makeRequest(t,i,n){return e(this,arguments,void 0,function*(e,t,i,n=1,r="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const s=new URL(e,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${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:r,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"===r&&{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 a(l,{status:c.status,code:o,retryable:s});if(s&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${s}ms (attempt ${n+1})`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}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 a)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 s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${s}ms`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new a("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"]),b=s.enum(["none","low","medium","high"]),y=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:b.optional().default("low"),budget:v.optional(),executionMode:y.optional()}),x=1e4,j=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()}),k=s.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),S=s.object({dataPrepPrompt:s.string(),chartType:k,summary:s.string()}),C=s.object({response:s.object({message:s.string()}),config:p}),T=s.object({suggestions:s.array(S)}),O=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:O.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)}),B=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),P=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),A=s.enum(["high","medium","low"]),U=s.object({confidence:A,needsUserInput:s.boolean(),warnings:s.array(s.string()),cellConfidence:s.array(s.object({rowIndex:s.number().int().nonnegative(),columnKey:s.string(),confidence:A,quote:s.string().optional()})).optional()}),N=s.object({score:s.number().min(0).max(1),issues:s.array(s.string()),sufficient:s.boolean(),summary:s.string()}),q=5e5,D=8,F=2097152,K=7340032,M=2,L=6291456,G=8388608,W=2,z=L,H=G,J=12582912,_=12;function Y(e){return 4*Math.ceil(e/3)}const Z=Y(F),Q=Y(K),V=Y(L),X=Y(G),ee=Y(z),te=Y(H),ie=Y(J);function ne(e){return e.replace(/\s+/g,"")}function re(e){const t=ne(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const se=/^image\/(png|jpeg|jpg|webp|gif)$/i,ae=s.object({mimeType:s.string().min(1).refine(e=>se.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:s.string().min(1).max(Z).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),oe=s.enum(["image","document","spreadsheet"]),ce=ae.extend({kind:s.literal("image")}),le=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(V).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),me=s.object({kind:s.literal("spreadsheet"),mimeType:s.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:s.string().min(1).max(ee).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:s.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),de=s.discriminatedUnion("kind",[ce,le,me]),ue=s.object({sourceText:s.string().max(q).default(""),images:s.array(ae).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:s.array(de).max(12).optional(),metadata:w.optional()}).superRefine((e,t)=>{var i,n;const r=e.sourceText.trim(),s=null!==(i=e.images)&&void 0!==i?i:[],a=null!==(n=e.attachments)&&void 0!==n?n:[];if(s.length>0&&a.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===r.length&&0===s.length&&0===a.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+ne(t.dataBase64).length,0)>Q&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,l=0,m=0,d=0,u=0,g=0;for(const e of a){const t=ne(e.dataBase64).length;switch(g+=t,e.kind){case"image":o+=1,m+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":l+=1,u+=t}}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"]}),l>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const h=o<=8&&c<=2&&l<=2;a.length>0&&h&&(m>Q&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>X&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>te&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>ie&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function ge(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ne(e.dataBase64)}}function he(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ne(e.dataBase64)}}function pe(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ne(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const fe=s.object({response:s.object({message:s.string()}),config:p,extractMeta:U.nullable(),lastAccuracyEvaluation:N.optional()}),be=s.object({config:p,response:s.object({message:s.string(),steps:s.array(s.string())})}),ye=T,ve=s.enum(["deal-breaker","pro","con","family","specificity","continuity"]),we=s.object({kind:ve,label:s.string(),weight:s.number(),reason:s.string()}),xe=s.enum(["ok","disqualified"]),je=s.object({rank:s.number().int().positive(),type:k,score:s.number(),verdict:xe,factors:s.array(we)}),$e=j.extend({chartFamily:O.optional()}),ke=s.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures"]),Se=s.object({kind:ke,message:s.string()}),Ce=s.enum(["sum","avg","count","min","max"]),Te=s.object({dimensionName:s.string(),dimensionLabel:s.string(),measureName:s.string().nullable(),measureLabel:s.string().nullable(),fn:Ce,chartType:k,score:s.number(),message:s.string()}),Oe=s.object({ranking:s.array(je),observations:s.array(Se).optional().default([]),suggestions:s.array(Te).optional().default([])}),Ee="/api/v0";class Ie{constructor(e){this.client=new g(e)}generateGraph(t,i,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,s=r(t,["storytellingOptions"]),a=yield this.client.fetch(`${Ee}/generate`,s,i,n),o=be.parse(a);return this.stripStorytelling(o,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,n=r(t,["storytellingOptions"]),s=yield this.client.stream(`${Ee}/generate`,n,i);return this.wrapStreamWithStorytellingStripping(s,e)})}generateNarrative(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ee}/narrate`,t,i,n);return C.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ee}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ee}/suggestions`,t,i,n);return T.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ee}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ee}/explore`,t,i,n);return R.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ee}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ee}/annotate`,t,i,n);return B.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ee}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ee}/mutate`,t,i,n);return P.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ee}/mutate`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ee}/evaluate`,t,void 0,i);return Oe.parse(e)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ee}/extract`,t,i,n);return fe.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ee}/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,r){return i(this,arguments,function*(){var i,s,a,o;try{for(var c,m=!0,d=t(e);!(i=(c=yield n(d.next())).done);m=!0){o=c.value,m=!1;const e=o;if(l(e)){const t=this.stripStorytelling(e.data,r);yield yield n(Object.assign(Object.assign({},e),{data:t}))}else yield yield n(e)}}catch(e){s={error:e}}finally{try{m||i||!(a=d.return)||(yield n(a.call(d)))}finally{if(s)throw s.error}}})}}export{Ce as AggregationFunctionSchema,Te as AggregationSuggestionSchema,k as AiChartTypeEnum,O as ChartFamilySchema,je as ChartFitEntrySchema,ve as ChartFitFactorKindSchema,we as ChartFitFactorSchema,xe as ChartFitVerdictSchema,ke as DataObservationKindSchema,Se as DataObservationSchema,$e as EvaluateParamsSchema,Oe as EvaluateResponseSchema,y as ExecutionModeSchema,E as ExploreFindingSchema,I as ExploreStorySchema,N as ExtractAccuracyEvaluationSchema,de as ExtractAttachmentInputSchema,oe as ExtractAttachmentKindSchema,A as ExtractConfidenceSchema,ue as ExtractFromProseParamsSchema,fe as ExtractFromProseResponseSchema,U as ExtractMetaSchema,B as GenerateAnnotationsResponseSchema,R as GenerateExplorationResponseSchema,be as GenerateGraphResponseSchema,ye as GenerateGraphSuggestionsResponseSchema,P as GenerateMutationResponseSchema,C as GenerateNarrativeResponseSchema,$ as GenerateSuggestionsParamsSchema,T as GenerateSuggestionsResponseSchema,j as GraphGenerationRequestSchema,Ie as GraphyAiSdk,a as GraphyApiError,v as InvocationBudgetSchema,f as InvocationEffortSchema,_ as MAX_EXTRACT_ATTACHMENTS,J as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,M as MAX_EXTRACT_DOCUMENTS,G as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,L as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,D as MAX_EXTRACT_IMAGES,K as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,F as MAX_EXTRACT_IMAGE_DECODED_BYTES,W as MAX_EXTRACT_SPREADSHEETS,H as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,z as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,q as MAX_SOURCE_TEXT_LENGTH,x as MAX_USER_PROMPT_LENGTH,w as MetadataSchema,b as StorytellingEffortSchema,S as SuggestionSchema,ge as buildImageAttachment,he as buildPdfAttachment,pe as buildSpreadsheetAttachment,l as isCompleteEvent,m as isErrorEvent,o as isGraphyApiError,d as isPreviewEvent,c as isProgressEvent,u as isReasoningEvent};
|
|
1
|
+
import{__awaiter as e,__asyncValues as t,__asyncGenerator as i,__await as n,__rest as r}from"tslib";import{z as s}from"zod";class a 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 o=e=>e instanceof a,c=e=>"progress"===e.type,l=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type;class g{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 m(e)}stream(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,i,n);return this.parseSSE(e)})}fetch(i,n,r,s){return e(this,void 0,void 0,function*(){var e,o,d,u,g;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const y=yield this.makeRequest(i,n,s),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var p,f=!0,b=t(this.parseSSE(y));!(e=(p=yield b.next()).done);f=!0){u=p.value,f=!1;const e=u;if(c(e)&&r&&r(e),l(e))return e.data;if(m(e)){const t=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(g=e.retryable)&&void 0!==g&&g})}}}catch(e){o={error:e}}finally{try{f||e||!(d=b.return)||(yield d.call(b))}finally{if(o)throw o.error}}const n=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${n}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof a)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 a("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let r="",s="",o="";try{for(;;){const{done:e,value:a}=yield n(t.read());if(e)break;r+=i.decode(a,{stream:!0});const c=r.split(/\r?\n/);r=c.pop()||"";for(const e of c)if(e.startsWith("event: "))s=e.slice(7).trim();else if(e.startsWith("data: "))o+=(o?"\n":"")+e.slice(6);else if(""===e.trim()&&o){try{const e=JSON.parse(o);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="",o="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield n(t),"complete"===s||"error"===s)return yield n(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}s="",o=""}}}finally{t.releaseLock()}})}makeRequest(t,i,n){return e(this,arguments,void 0,function*(e,t,i,n=1,r="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const s=new URL(e,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${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:r,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"===r&&{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 a(l,{status:c.status,code:o,retryable:s});if(s&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${s}ms (attempt ${n+1})`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}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 a)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 s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${s}ms`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new a("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"]),b=s.enum(["none","low","medium","high"]),y=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).optional(),locale:h.optional(),effort:f.optional(),storytellingEffort:b.optional().default("low"),budget:v.optional(),executionMode:y.optional()}),x=1e4,j=s.object({config:p,userPrompt:s.string().max(x).optional().default(""),metadata:w.optional()}),$=j.extend({maxSuggestionCount:s.number().int().min(1).max(4).optional()}),k=s.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),S=s.object({dataPrepPrompt:s.string(),chartType:k,summary:s.string()}),C=j.extend({userPrompt:s.string().max(x)}),T=s.object({response:s.object({message:s.string()}),config:p}),O=s.object({suggestions:s.array(S)}),E=s.enum(["comparison","relationship","distribution","composition"]),I=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:E.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.")}),P=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(I).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(P)}),B=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}),U=s.enum(["high","medium","low"]),N=s.object({confidence:U,needsUserInput:s.boolean(),warnings:s.array(s.string()),cellConfidence:s.array(s.object({rowIndex:s.number().int().nonnegative(),columnKey:s.string(),confidence:U,quote:s.string().optional()})).optional()}),q=s.object({score:s.number().min(0).max(1),issues:s.array(s.string()),sufficient:s.boolean(),summary:s.string()}),D=5e5,F=8,K=2097152,M=7340032,L=2,G=6291456,W=8388608,z=2,H=G,J=W,_=12582912,Y=12;function Z(e){return 4*Math.ceil(e/3)}const Q=Z(K),V=Z(M),X=Z(G),ee=Z(W),te=Z(H),ie=Z(J),ne=Z(_);function re(e){return e.replace(/\s+/g,"")}function se(e){const t=re(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const ae=/^image\/(png|jpeg|jpg|webp|gif)$/i,oe=s.object({mimeType:s.string().min(1).refine(e=>ae.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:s.string().min(1).max(Q).refine(se,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ce=s.enum(["image","document","spreadsheet"]),le=oe.extend({kind:s.literal("image")}),me=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(X).refine(se,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),de=s.object({kind:s.literal("spreadsheet"),mimeType:s.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:s.string().min(1).max(te).refine(se,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:s.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),ue=s.discriminatedUnion("kind",[le,me,de]),ge=s.object({sourceText:s.string().max(D).default(""),images:s.array(oe).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:s.array(ue).max(12).optional(),metadata:w.optional()}).superRefine((e,t)=>{var i,n;const r=e.sourceText.trim(),s=null!==(i=e.images)&&void 0!==i?i:[],a=null!==(n=e.attachments)&&void 0!==n?n:[];if(s.length>0&&a.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===r.length&&0===s.length&&0===a.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+re(t.dataBase64).length,0)>V&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,l=0,m=0,d=0,u=0,g=0;for(const e of a){const t=re(e.dataBase64).length;switch(g+=t,e.kind){case"image":o+=1,m+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":l+=1,u+=t}}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"]}),l>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const h=o<=8&&c<=2&&l<=2;a.length>0&&h&&(m>V&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ee&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>ie&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>ne&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function he(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:re(e.dataBase64)}}function pe(e){return{kind:"document",mimeType:"application/pdf",dataBase64:re(e.dataBase64)}}function fe(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:re(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const be=s.object({response:s.object({message:s.string()}),config:p,extractMeta:N.nullable(),lastAccuracyEvaluation:q.optional()}),ye=s.object({config:p,response:s.object({message:s.string(),steps:s.array(s.string())})}),ve=O,we=s.enum(["deal-breaker","pro","con","family","specificity","continuity"]),xe=s.object({kind:we,label:s.string(),weight:s.number(),reason:s.string()}),je=s.enum(["ok","disqualified"]),$e=s.object({rank:s.number().int().positive(),type:k,score:s.number(),verdict:je,factors:s.array(xe)}),ke=s.object({config:p,chartFamily:E.optional(),metadata:w.optional()}),Se=s.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures"]),Ce=s.object({kind:Se,message:s.string()}),Te=s.enum(["sum","avg","count","min","max"]),Oe=s.object({dimensionName:s.string(),dimensionLabel:s.string(),measureName:s.string().nullable(),measureLabel:s.string().nullable(),fn:Te,chartType:k,score:s.number(),message:s.string()}),Ee=s.object({ranking:s.array($e),observations:s.array(Ce).optional().default([]),suggestions:s.array(Oe).optional().default([])}),Ie="/api/v0";class Pe{constructor(e){this.client=new g(e)}generateGraph(t,i,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,s=r(t,["storytellingOptions"]),a=yield this.client.fetch(`${Ie}/generate`,s,i,n),o=ye.parse(a);return this.stripStorytelling(o,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,n=r(t,["storytellingOptions"]),s=yield this.client.stream(`${Ie}/generate`,n,i);return this.wrapStreamWithStorytellingStripping(s,e)})}generateNarrative(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/narrate`,t,i,n);return T.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/suggestions`,t,i,n);return O.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/explore`,t,i,n);return R.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/annotate`,t,i,n);return B.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/mutate`,t,i,n);return A.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/mutate`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/evaluate`,t,void 0,i);return Ee.parse(e)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/extract`,t,i,n);return be.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/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,r){return i(this,arguments,function*(){var i,s,a,o;try{for(var c,m=!0,d=t(e);!(i=(c=yield n(d.next())).done);m=!0){o=c.value,m=!1;const e=o;if(l(e)){const t=this.stripStorytelling(e.data,r);yield yield n(Object.assign(Object.assign({},e),{data:t}))}else yield yield n(e)}}catch(e){s={error:e}}finally{try{m||i||!(a=d.return)||(yield n(a.call(d)))}finally{if(s)throw s.error}}})}}export{Te as AggregationFunctionSchema,Oe as AggregationSuggestionSchema,k as AiChartTypeEnum,E as ChartFamilySchema,$e as ChartFitEntrySchema,we as ChartFitFactorKindSchema,xe as ChartFitFactorSchema,je as ChartFitVerdictSchema,Se as DataObservationKindSchema,Ce as DataObservationSchema,ke as EvaluateParamsSchema,Ee as EvaluateResponseSchema,y as ExecutionModeSchema,I as ExploreFindingSchema,P as ExploreStorySchema,q as ExtractAccuracyEvaluationSchema,ue as ExtractAttachmentInputSchema,ce as ExtractAttachmentKindSchema,U as ExtractConfidenceSchema,ge as ExtractFromProseParamsSchema,be as ExtractFromProseResponseSchema,N as ExtractMetaSchema,B as GenerateAnnotationsResponseSchema,R as GenerateExplorationResponseSchema,ye as GenerateGraphResponseSchema,ve as GenerateGraphSuggestionsResponseSchema,A as GenerateMutationResponseSchema,C as GenerateNarrativeParamsSchema,T as GenerateNarrativeResponseSchema,$ as GenerateSuggestionsParamsSchema,O as GenerateSuggestionsResponseSchema,j as GraphGenerationRequestSchema,Pe as GraphyAiSdk,a as GraphyApiError,v as InvocationBudgetSchema,f as InvocationEffortSchema,Y as MAX_EXTRACT_ATTACHMENTS,_ as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,L as MAX_EXTRACT_DOCUMENTS,W as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,G as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,F as MAX_EXTRACT_IMAGES,M as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,K as MAX_EXTRACT_IMAGE_DECODED_BYTES,z as MAX_EXTRACT_SPREADSHEETS,J as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,H as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,D as MAX_SOURCE_TEXT_LENGTH,x as MAX_USER_PROMPT_LENGTH,w as MetadataSchema,b as StorytellingEffortSchema,S as SuggestionSchema,he as buildImageAttachment,pe as buildPdfAttachment,fe as buildSpreadsheetAttachment,l as isCompleteEvent,m as isErrorEvent,o 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.
|
|
4
|
+
"version": "1.5.0-beta.1779451530994",
|
|
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.
|
|
21
|
+
"@graphysdk/core": "1.5.0-beta.1779451530994"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|