You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm developing a next based app and after updating llamaindex to v0.5.21 I started to see the following error:
⨯ TypeError: Cannot redefine property: format
at Function.defineProperty ()
at eval (webpack-internal:///(rsc)/../../node_modules/@llamaindex/core/dist/prompts/index.js:28:8)
at (rsc)/../../node_modules/@llamaindex/core/dist/prompts/index.js (apps/web/.next/server/vendor-chunks/@llamaindex.js:80:1)
at webpack_require (apps/web/.next/server/webpack-runtime.js:33:43)
at eval (webpack-internal:///(rsc)/../../node_modules/llamaindex/dist/index.edge.js:222:82)
at (rsc)/../../node_modules/llamaindex/dist/index.edge.js (apps/web/.next/server/vendor-chunks/llamaindex.js:560:1)
Initially I assumed that the error was caused by #1154 (hence my comments in there)
In my attempt to isolate the problem I've checked out to latest commit that was working (lllamaindex v0.5.16) and then started bumping llamaindex step-by-step in my pnpm-workspace.yaml that looks like:
The error comes from this file apps/web/.next/server/vendor-chunks/@llamaindex.js
import{objectEntries}from'../utils/index.js';import{z}from'zod';functiongetDefaultExportFromCjs(x){returnx&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default') ? x['default'] : x;}Object.defineProperty(String.prototype,"format",{value: function(...args_){// Create variablesletself=this;let__patterns__=self.match(/({.*?})/g);const{REF,FILL_CHAR,MASK_NUMBER,ALIGN_OP,CROP_SIZE,DOT,FRACTION,TYPE_VAR}={REF: 1,FILL_CHAR: 2,MASK_NUMBER: 3,ALIGN_OP: 4,CROP_SIZE: 5,DOT: 6,FRACTION: 7,TYPE_VAR: 8};constDEFAULT_PLACE=6;constALL_REGEXP=/{(\w+)?:([^>\^<\d#]|0)?([#%,])?([>^<\.])?(\d+)?(\.)?(\d+)?([eEfFgGdxXobn#%])?}/g;constregExpBasic=/{\[?(\w+)\]?}/;// it's not best solutionconstisObject=typeofargs_[0]==="object";// types/use logic__patterns__?.map((pattern,patt_index)=>{constkargs=ALL_REGEXP.exec(pattern)||ALL_REGEXP.exec(pattern);constwargs=regExpBasic.exec(pattern);// Insert values (one 2 one / array / object)constINDEX_VAR=(wargs ? wargs[REF] : kargs ? kargs[REF] : patt_index)||patt_index;letNATUAL_VALUE=isObject ? args_[0][INDEX_VAR] : args_[INDEX_VAR];letACTUAL_VALUE=isObject ? args_[0][INDEX_VAR] : args_[INDEX_VAR];// Verify sintax/semanticif(ACTUAL_VALUE===null||ACTUAL_VALUE===undefined)thrownewError(`Replacement index ${INDEX_VAR} out of range for positional args tuple`);if(kargs){// If TYPE_VAR is not defined and the first argument is a number, pad a string should from left, so set TYPE_VAR to "d"if(kargs[TYPE_VAR]===undefined&&typeofACTUAL_VALUE==="number"){kargs[TYPE_VAR]="d";}constLETTER=(!kargs[FILL_CHAR] ? false : !kargs[ALIGN_OP]&&[
..."FfbefoxXn"].includes(kargs[FILL_CHAR].toLowerCase()) ? kargs[FILL_CHAR] : kargs[TYPE_VAR])||kargs[TYPE_VAR];// padronazeif(LETTER){constfloatSize=pattern.includes(".") ? Number(kargs[FRACTION]||kargs[CROP_SIZE]) : DEFAULT_PLACE;switch(LETTER){case"E":
ACTUAL_VALUE=ACTUAL_VALUE.toExponential(DEFAULT_PLACE).toUpperCase();break;case"e":
ACTUAL_VALUE=ACTUAL_VALUE.toExponential(DEFAULT_PLACE);break;case"X":
ACTUAL_VALUE=ACTUAL_VALUE.toString(16).toUpperCase();break;case"x":
ACTUAL_VALUE=ACTUAL_VALUE.toString(16);// Hexadecimalbreak;case"b":
ACTUAL_VALUE=ACTUAL_VALUE.toString(2);// Binarybreak;case"f":
case"F":
ACTUAL_VALUE=ACTUAL_VALUE.toFixed(floatSize);break;case"o":
ACTUAL_VALUE=ACTUAL_VALUE.toString(8);// Octalbreak;}// maskswitch(kargs[MASK_NUMBER]){case"#":
constMASK={x: "0x",X: "0X",o: "0o",b: "0b"}[LETTER];ACTUAL_VALUE=MASK+ACTUAL_VALUE;break;}}// signalif([
..." +-,%"].includes(kargs[FILL_CHAR])&&typeofNATUAL_VALUE==="number"){ACTUAL_VALUE=ACTUAL_VALUE.toString().replace("-","");if(NATUAL_VALUE>=0)switch(kargs[FILL_CHAR]){case"+":
ACTUAL_VALUE="+"+ACTUAL_VALUE;break;case" ":
ACTUAL_VALUE=" "+ACTUAL_VALUE;break;case",":
ACTUAL_VALUE=NATUAL_VALUE.toString().split(/(?=(?:...)*$)/).join(kargs[FILL_CHAR]);break;case"%":
ACTUAL_VALUE=(NATUAL_VALUE*100).toFixed(kargs[FRACTION]||DEFAULT_PLACE)+"%";break;}elseACTUAL_VALUE="-"+ACTUAL_VALUE;}// space / order / trimif(kargs[CROP_SIZE]){ACTUAL_VALUE=ACTUAL_VALUE.toString();constFILL_ELEMENT=kargs[FILL_CHAR]||" ";constSIZE_STRING=ACTUAL_VALUE.length;constSIZE_ARG=kargs[CROP_SIZE];constFILL_LENGTH=SIZE_STRING>SIZE_ARG ? SIZE_STRING : SIZE_ARG;constFILL=FILL_ELEMENT.repeat(FILL_LENGTH);switch(kargs[ALIGN_OP]||kargs[FILL_CHAR]){case"<":
ACTUAL_VALUE=ACTUAL_VALUE.padEnd(FILL_LENGTH,FILL_ELEMENT);break;case".":
if(!(LETTER&&/[fF]/.test(LETTER)))ACTUAL_VALUE=ACTUAL_VALUE.slice(0,SIZE_ARG);break;case">":
ACTUAL_VALUE=ACTUAL_VALUE.padStart(FILL_LENGTH,FILL_ELEMENT);break;case"^":
constlength_start=Math.floor((FILL_LENGTH-SIZE_STRING)/2);conststring_start=length_start>0 ? FILL_ELEMENT.repeat(length_start)+ACTUAL_VALUE : ACTUAL_VALUE;ACTUAL_VALUE=FILL.replace(RegExp(`.{${string_start.length}}`),string_start);break;default:
ACTUAL_VALUE=LETTER ? ACTUAL_VALUE.padStart(FILL_LENGTH,FILL_ELEMENT) : ACTUAL_VALUE.padEnd(FILL_LENGTH,FILL_ELEMENT);break;}}}// SET Definitive valueself=self.replace(pattern,ACTUAL_VALUE);});returnself;}});varpythonFormatJs=(inputString, ...param)=>inputString.format(...param);varformat=/*@__PURE__*/getDefaultExportFromCjs(pythonFormatJs);constpromptType={SUMMARY: "summary",TREE_INSERT: "insert",TREE_SELECT: "tree_select",TREE_SELECT_MULTIPLE: "tree_select_multiple",QUESTION_ANSWER: "text_qa",REFINE: "refine",KEYWORD_EXTRACT: "keyword_extract",QUERY_KEYWORD_EXTRACT: "query_keyword_extract",SCHEMA_EXTRACT: "schema_extract",TEXT_TO_SQL: "text_to_sql",TEXT_TO_GRAPH_QUERY: "text_to_graph_query",TABLE_CONTEXT: "table_context",KNOWLEDGE_TRIPLET_EXTRACT: "knowledge_triplet_extract",SIMPLE_INPUT: "simple_input",PANDAS: "pandas",JSON_PATH: "json_path",SINGLE_SELECT: "single_select",MULTI_SELECT: "multi_select",VECTOR_STORE_QUERY: "vector_store_query",SUB_QUESTION: "sub_question",SQL_RESPONSE_SYNTHESIS: "sql_response_synthesis",SQL_RESPONSE_SYNTHESIS_V2: "sql_response_synthesis_v2",CONVERSATION: "conversation",DECOMPOSE: "decompose",CHOICE_SELECT: "choice_select",CUSTOM: "custom",RANKGPT_RERANK: "rankgpt_rerank"};constpromptTypeSchema=z.enum([promptType.SUMMARY,promptType.TREE_INSERT,promptType.TREE_SELECT,promptType.TREE_SELECT_MULTIPLE,promptType.QUESTION_ANSWER,promptType.REFINE,promptType.KEYWORD_EXTRACT,promptType.QUERY_KEYWORD_EXTRACT,promptType.SCHEMA_EXTRACT,promptType.TEXT_TO_SQL,promptType.TEXT_TO_GRAPH_QUERY,promptType.TABLE_CONTEXT,promptType.KNOWLEDGE_TRIPLET_EXTRACT,promptType.SIMPLE_INPUT,promptType.PANDAS,promptType.JSON_PATH,promptType.SINGLE_SELECT,promptType.MULTI_SELECT,promptType.VECTOR_STORE_QUERY,promptType.SUB_QUESTION,promptType.SQL_RESPONSE_SYNTHESIS,promptType.SQL_RESPONSE_SYNTHESIS_V2,promptType.CONVERSATION,promptType.DECOMPOSE,promptType.CHOICE_SELECT,promptType.CUSTOM,promptType.RANKGPT_RERANK]);constPromptType=promptTypeSchema.enum;classBasePromptTemplate{constructor(options){this.metadata={};this.templateVars=newSet();this.options={};this.templateVarMappings={};this.functionMappings={};const{ metadata, templateVars, outputParser, templateVarMappings, functionMappings }=options;if(metadata){this.metadata=metadata;}if(templateVars){this.templateVars=newSet(templateVars);}if(options.options){this.options=options.options;}this.outputParser=outputParser;if(templateVarMappings){this.templateVarMappings=templateVarMappings;}if(functionMappings){this.functionMappings=functionMappings;}}mapTemplateVars(options){consttemplateVarMappings=this.templateVarMappings;returnObject.fromEntries(objectEntries(options).map(([k,v])=>[templateVarMappings[k]||k,v]));}mapFunctionVars(options){constfunctionMappings=this.functionMappings;constnewOptions={};for(const[k,v]ofobjectEntries(functionMappings)){newOptions[k]=v(options);}for(const[k,v]ofobjectEntries(options)){if(!(kinnewOptions)){newOptions[k]=v;}}returnnewOptions;}mapAllVars(options){constnewOptions=this.mapFunctionVars(options);returnthis.mapTemplateVars(newOptions);}}classPromptTemplateextendsBasePromptTemplate{
#template;constructor(options){const{ template, promptType, ...rest}=options;super(rest);this.#template =template;this.promptType=promptType??PromptType.custom;}partialFormat(options){constprompt=newPromptTemplate({template: this.template,templateVars: [
...this.templateVars],options: this.options,outputParser: this.outputParser,templateVarMappings: this.templateVarMappings,functionMappings: this.functionMappings,metadata: this.metadata,promptType: this.promptType});prompt.options={
...prompt.options,
...options};returnprompt;}format(options){constallOptions={
...this.options,
...options};constmappedAllOptions=this.mapAllVars(allOptions);constprompt=format(this.template,mappedAllOptions);if(this.outputParser){returnthis.outputParser.format(prompt);}returnprompt;}formatMessages(options){constprompt=this.format(options);return[{role: "user",content: prompt}];}gettemplate(){returnthis.#template;}}classPromptMixin{validatePrompts(promptsDict,moduleDict){for(constkeyofObject.keys(promptsDict)){if(key.includes(":")){thrownewError(`Prompt key ${key} cannot contain ':'.`);}}for(constkeyofObject.keys(moduleDict)){if(key.includes(":")){thrownewError(`Module key ${key} cannot contain ':'.`);}}}getPrompts(){constpromptsDict=this._getPrompts();constmoduleDict=this._getPromptModules();this.validatePrompts(promptsDict,moduleDict);constallPrompts={
...promptsDict};for(const[module_name,prompt_module]ofobjectEntries(moduleDict)){for(const[key,prompt]ofobjectEntries(prompt_module.getPrompts())){allPrompts[`${module_name}:${key}`]=prompt;}}returnallPrompts;}updatePrompts(prompts){constpromptModules=this._getPromptModules();this._updatePrompts(prompts);constsubPrompt={};for(constkeyinprompts){if(key.includes(":")){const[module_name,sub_key]=key.split(":");if(!subPrompt[module_name]){subPrompt[module_name]={};}subPrompt[module_name][sub_key]=prompts[key];}}for(const[module_name,subPromptDict]ofObject.entries(subPrompt)){if(!promptModules[module_name]){thrownewError(`Module ${module_name} not found.`);}constmoduleToUpdate=promptModules[module_name];moduleToUpdate.updatePrompts(subPromptDict);}}}constdefaultTextQAPrompt=newPromptTemplate({templateVars: ["context","query"],template: `Context information is below.---------------------{context}---------------------Given the context information and not prior knowledge, answer the query.Query: {query}Answer:`});constanthropicTextQaPrompt=newPromptTemplate({templateVars: ["context","query"],template: `Context information:<context>{context}</context>Given the context information and not prior knowledge, answer the query.Query: {query}`});constdefaultSummaryPrompt=newPromptTemplate({templateVars: ["context"],template: `Write a summary of the following. Try to use only the information provided. Try to include as many key details as possible.{context}SUMMARY:"""`});constanthropicSummaryPrompt=newPromptTemplate({templateVars: ["context"],template: `Summarize the following text. Try to use only the information provided. Try to include as many key details as possible.<original-text>{context}</original-text>SUMMARY:`});constdefaultRefinePrompt=newPromptTemplate({templateVars: ["query","existingAnswer","context"],template: `The original query is as follows: {query}We have provided an existing answer: {existingAnswer}We have the opportunity to refine the existing answer (only if needed) with some more context below.------------{context}------------Given the new context, refine the original answer to better answer the query. If the context isn't useful, return the original answer.Refined Answer:`});constdefaultTreeSummarizePrompt=newPromptTemplate({templateVars: ["context","query"],template: `Context information from multiple sources is below.---------------------{context}---------------------Given the information from multiple sources and not prior knowledge, answer the query.Query: {query}Answer:`});constdefaultChoiceSelectPrompt=newPromptTemplate({templateVars: ["context","query"],template: `A list of documents is shown below. Each document has a number next to it along with a summary of the document. A question is also provided.Respond with the numbers of the documentsyou should consult to answer the question, in order of relevance, as wellas the relevance score. The relevance score is a number from 1-10 based onhow relevant you think the document is to the question.Do not include any documents that are not relevant to the question.Example format:Document 1:<summary of document 1>Document 2:<summary of document 2>...Document 10:\n<summary of document 10>Question: <question>Answer:Doc: 9, Relevance: 7Doc: 3, Relevance: 4Doc: 7, Relevance: 3Let's try this now:{context}Question: {query}Answer:`});functionbuildToolsText(tools){consttoolsObj=tools.reduce((acc,tool)=>{acc[tool.name]=tool.description;returnacc;},{});returnJSON.stringify(toolsObj,null,4);}constexampleTools=[{name: "uber_10k",description: "Provides information about Uber financials for year 2021"},{name: "lyft_10k",description: "Provides information about Lyft financials for year 2021"}];constexampleQueryStr=`Compare and contrast the revenue growth and EBITDA of Uber and Lyft for year 2021`;constexampleOutput=[{subQuestion: "What is the revenue growth of Uber",toolName: "uber_10k"},{subQuestion: "What is the EBITDA of Uber",toolName: "uber_10k"},{subQuestion: "What is the revenue growth of Lyft",toolName: "lyft_10k"},{subQuestion: "What is the EBITDA of Lyft",toolName: "lyft_10k"}];constdefaultSubQuestionPrompt=newPromptTemplate({templateVars: ["toolsStr","queryStr"],template: `Given a user question, and a list of tools, output a list of relevant sub-questions that when composed can help answer the full user question:# Example 1<Tools>\`\`\`json${buildToolsText(exampleTools)}\`\`\`<User Question>${exampleQueryStr}<Output>\`\`\`json${JSON.stringify(exampleOutput,null,4)}\`\`\`# Example 2<Tools>\`\`\`json{toolsStr}\`\`\`<User Question>{queryStr}<Output>`});constdefaultCondenseQuestionPrompt=newPromptTemplate({templateVars: ["chatHistory","question"],template: `Given a conversation (between Human and Assistant) and a follow up message from Human, rewrite the message to be a standalone question that captures all relevant context from the conversation.<Chat History>{chatHistory}<Follow Up Message>{question}<Standalone question>`});constdefaultContextSystemPrompt=newPromptTemplate({templateVars: ["context"],template: `Context information is below.---------------------{context}---------------------`});constdefaultKeywordExtractPrompt=newPromptTemplate({templateVars: ["maxKeywords","context"],template: `Some text is provided below. Given the text, extract up to {maxKeywords} keywords from the text. Avoid stopwords.---------------------{context}---------------------Provide keywords in the following comma-separated format: 'KEYWORDS: <keywords>'`}).partialFormat({maxKeywords: "10"});constdefaultQueryKeywordExtractPrompt=newPromptTemplate({templateVars: ["maxKeywords","question"],template: `( "A question is provided below. Given the question, extract up to {maxKeywords} " "keywords from the text. Focus on extracting the keywords that we can use " "to best lookup answers to the question. Avoid stopwords." "---------------------" "{question}" "---------------------" "Provide keywords in the following comma-separated format: 'KEYWORDS: <keywords>'")`}).partialFormat({maxKeywords: "10"});export{BasePromptTemplate,PromptMixin,PromptTemplate,anthropicSummaryPrompt,anthropicTextQaPrompt,defaultChoiceSelectPrompt,defaultCondenseQuestionPrompt,defaultContextSystemPrompt,defaultKeywordExtractPrompt,defaultQueryKeywordExtractPrompt,defaultRefinePrompt,defaultSubQuestionPrompt,defaultSummaryPrompt,defaultTextQAPrompt,defaultTreeSummarizePrompt};
More context about how this error happens:
I'm using llamaindex at app/api/chat/route.ts , in other words, I'm using Route Handlers
When I start my app and open /home next.js compiles the app and I can call llamaindex at app/api/chat/route.ts without any error. Then, when I navigate to another page (e.g, /products) next.js does another compilation. After this when I call the handler at app/api/chat/route.ts I get the error above.
I'm assuming that during the first compilation the Object.defineProperty(String.prototype, "format", {/* logic */}) gets executed without any issue. However, during the second compilation if throws the Cannot redefine property: format error
@marcusschiesser@himself65 any idea of what's going on here? My knowledge about this lib is pretty limited.
The text was updated successfully, but these errors were encountered:
I'm developing a next based app and after updating llamaindex to v0.5.21 I started to see the following error:
Initially I assumed that the error was caused by #1154 (hence my comments in there)
In my attempt to isolate the problem I've checked out to latest commit that was working (lllamaindex v0.5.16) and then started bumping llamaindex step-by-step in my
pnpm-workspace.yaml
that looks like:Results:
v0.5.16 - OK
v0.5.17 - OK
v0.5.18 - OK
v0.5.19 - OK
v0.5.20 - OK
v0.5.21 - Error starts here
v0.5.22 - - Error continues here
Rolling back to v0.5.20 the error disappears. This leads me be to believe that the culprit is some commit between 0.5.20 and 0.5.21
Here are the changes in
pnpm-lock.yaml
The error comes from this file
apps/web/.next/server/vendor-chunks/@llamaindex.js
More context about how this error happens:
I'm using
llamaindex
atapp/api/chat/route.ts
, in other words, I'm using Route HandlersWhen I start my app and open
/home
next.js compiles the app and I can call llamaindex atapp/api/chat/route.ts
without any error. Then, when I navigate to another page (e.g,/products
) next.js does another compilation. After this when I call the handler atapp/api/chat/route.ts
I get the error above.I'm assuming that during the first compilation the
Object.defineProperty(String.prototype, "format", {/* logic */})
gets executed without any issue. However, during the second compilation if throws theCannot redefine property: format
error@marcusschiesser @himself65 any idea of what's going on here? My knowledge about this lib is pretty limited.
The text was updated successfully, but these errors were encountered: