langchain-ai / langchainjs

πŸ¦œπŸ”— Build context-aware reasoning applications πŸ¦œπŸ”—
https://js.langchain.com/docs/
MIT License
12.82k stars 2.22k forks source link

Error occurred: Error: (f-string) Missing value for input Question ( Promnt Template) #5838

Closed psathish10 closed 2 months ago

psathish10 commented 5 months ago

Checked other resources

Example Code

import "reflect-metadata"; import { MemoryVectorStore } from "langchain/vectorstores/memory"; import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors"; import { FewShotPromptTemplate, PromptTemplate } from "@langchain/core/prompts"; import { createSqlQueryChain } from "langchain/chains/sql_db"; import { db } from "./db.js"; import { GoogleGenerativeAIEmbeddings } from "@langchain/google-genai"; import { TaskType } from "@google/generative-ai"; import { ChatGoogleGenerativeAI } from "@langchain/google-genai"; import { HarmBlockThreshold, HarmCategory } from "@google/generative-ai";

import few_shots from "./fewShorts.js";

async function main() { try { // Initialize example selector const embeddings = new GoogleGenerativeAIEmbeddings({ apiKey: "api", model: "embedding-001", taskType: TaskType.RETRIEVAL_QUERY, });

const exampleSelector =
  await SemanticSimilarityExampleSelector.fromExamples(
    few_shots,
    embeddings,
    MemoryVectorStore,
    { k: 5, inputKeys: ["input"] }
  );

// Ensure `exampleSelector` correctly selects examples
const selectedExamples = await exampleSelector.selectExamples({
  input: "how many employees are there?",
});
console.log("Selected examples:", selectedExamples);

// Define example prompt template
// const examplePrompt = PromptTemplate.fromTemplate(
//   `User input: {input}\nSQL Query: {query}`
// );
const examplePrompt = new PromptTemplate({
  inputVariables: ["Question", "SQLQuery", "SQLResult", "Answer"],
  template:
    "\nQuestion: {Question}\nSQLQuery:{SQLQuery}\nSQLResult:{SQLResult}\nAnswer:{Answer}",
});
// Define FewShotPromptTemplate
const prompt = new FewShotPromptTemplate({
  exampleSelector,
  examplePrompt,
  prefix: `You are a MySQL expert. Given an input question, create a syntactically correct MySQL query to run.

Unless otherwise specified, do not return more than {top_k} rows.

Here is the relevant table info: {table_info}

Below are a number of examples of questions and their corresponding SQL queries.`, // suffix: "Question: \nSQLQuery:\nSQLResult:\nAnswer:", inputVariables: ["input", "top_k", "table_info"], });

// Initialize the LLM (Large Language Model)
const llm = new ChatGoogleGenerativeAI({
  apiKey: "api",
  model: "gemini-pro",
  maxOutputTokens: 2048,
  safetySettings: [
    {
      category: HarmCategory.HARM_CATEGORY_HARASSMENT,
      threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    },
  ],
});

// Create the SQL query chain
const chain = await createSqlQueryChain({
  db,
  llm,
  prompt,
  dialect: "mysql",
});

// Invoke the chain with the question and required input variables
const result = await chain.invoke({
  question: "how many employees are there?",
  top_k: 10, // Example value for top_k
  // table_info: , / Example table info
});
console.log("SQL Query result:", result);

} catch (error) { console.error("Error occurred:", error); } }

main();

Error Message and Stack Trace (if applicable)

Error occurred: Error: (f-string) Missing value for input Question at file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/prompts/template.js:78:15
at Array.reduce () at Object.interpolateFString [as f-string] (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/prompts/template.js:73:80) at renderTemplate (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/prompts/template.js:91:115) at PromptTemplate.format (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/prompts/prompt.js:71:16) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Promise.all (index 0) at async FewShotPromptTemplate.format (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/prompts/few_shot.js:149:32) at async FewShotPromptTemplate.formatPromptValue (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/prompts/string.js:18:33) at async FewShotPromptTemplate._callWithConfig (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/runnables/base.js:210:22)

Description

Iam Trying to run the file but its not working its throw error

System Info

Node : V20.0.0 "@langchain/community": "^0.2.10", "@langchain/core": "^0.2.6", "@langchain/google-genai": "^0.0.17", "@langchain/openai": "^0.1.3", "@prisma/client": "^5.15.0", "chromadb": "^1.8.1", "config": "^3.3.11", "cors": "^2.8.5", "express": "^4.19.2", "langchain": "^0.2.5", "mysql": "^2.18.1", "mysql2": "^3.10.1", "sequelize": "^6.37.3", "typeorm": "^0.3.20", "winston": "^3.13.0", "zod": "^3.23.8"

dosubot[bot] commented 5 months ago

The error you're encountering is due to the PromptTemplate not receiving a value for the "Question" input. To resolve this, you need to ensure that the template includes a placeholder for "Question" and that you provide a value for it when creating the prompt.

Here's how you can modify your code to include the necessary input:

  1. Ensure the PromptTemplate includes the "Question" placeholder:

    const examplePrompt = new PromptTemplate({
     inputVariables: ["Question", "SQLQuery", "SQLResult", "Answer"],
     template: "\nQuestion: {Question}\nSQLQuery:{SQLQuery}\nSQLResult:{SQLResult}\nAnswer:{Answer}",
    });
  2. Provide the "Question" input when invoking the chain:

    const result = await chain.invoke({
     question: "how many employees are there?",
     top_k: 10, // Example value for top_k
     table_info: "your_table_info_here", // Provide the necessary table info
     Question: "how many employees are there?", // Ensure this matches the input variable in the template
    });

Here's the updated main function with the necessary changes:

async function main() {
  try {
    // Initialize example selector
    const embeddings = new GoogleGenerativeAIEmbeddings({
      apiKey: "api",
      model: "embedding-001",
      taskType: TaskType.RETRIEVAL_QUERY,
    });

    const exampleSelector =
      await SemanticSimilarityExampleSelector.fromExamples(
        few_shots,
        embeddings,
        MemoryVectorStore,
        { k: 5, inputKeys: ["input"] }
      );

    // Ensure `exampleSelector` correctly selects examples
    const selectedExamples = await exampleSelector.selectExamples({
      input: "how many employees are there?",
    });
    console.log("Selected examples:", selectedExamples);

    // Define example prompt template
    const examplePrompt = new PromptTemplate({
      inputVariables: ["Question", "SQLQuery", "SQLResult", "Answer"],
      template:
        "\nQuestion: {Question}\nSQLQuery:{SQLQuery}\nSQLResult:{SQLResult}\nAnswer:{Answer}",
    });

    // Define FewShotPromptTemplate
    const prompt = new FewShotPromptTemplate({
      exampleSelector,
      examplePrompt,
      prefix: `You are a MySQL expert. Given an input question, create a syntactically correct MySQL query to run.
Unless otherwise specified, do not return more than {top_k} rows.

Here is the relevant table info: {table_info}

Below are a number of examples of questions and their corresponding SQL queries.`,
      inputVariables: ["input", "top_k", "table_info"],
    });

    // Initialize the LLM (Large Language Model)
    const llm = new ChatGoogleGenerativeAI({
      apiKey: "api",
      model: "gemini-pro",
      maxOutputTokens: 2048,
      safetySettings: [
        {
          category: HarmCategory.HARM_CATEGORY_HARASSMENT,
          threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
        },
      ],
    });

    // Create the SQL query chain
    const chain = await createSqlQueryChain({
      db,
      llm,
      prompt,
      dialect: "mysql",
    });

    // Invoke the chain with the question and required input variables
    const result = await chain.invoke({
      question: "how many employees are there?",
      top_k: 10, // Example value for top_k
      table_info: "your_table_info_here", // Provide the necessary table info
      Question: "how many employees are there?", // Ensure this matches the input variable in the template
    });
    console.log("SQL Query result:", result);
  } catch (error) {
    console.error("Error occurred:", error);
  }
}

main();

This should resolve the error related to the PromptTemplate not receiving a value for the "Question" input [1].

To continue talking to Dosu, mention @dosu.