langchain-ai / langchainjs

🦜🔗 Build context-aware reasoning applications 🦜🔗
https://js.langchain.com/docs/
MIT License
11.75k stars 1.96k forks source link

text to sql Error occurred: Error: (f-string) Missing value for input query #5778

Open psathish10 opened 2 weeks ago

psathish10 commented 2 weeks ago

Checked other resources

Example Code

Database config import mysql from "mysql2/promise"; import { SqlDatabase } from "langchain/sql_db";

// Update with your actual database configuration const dbConfig = { host: "localhost", user: "root", password: "", database: "test", };

let db;

const setupDatabase = async () => { try { const connection = await mysql.createConnection(dbConfig); console.log("Database connected successfully.");

// Create a SqlDatabase instance using the mysql connection
db = new SqlDatabase({
  appDataSource: connection,
  options: {
    client: "mysql",
  },
});

} catch (error) { console.error("Unable to connect to the database:", error); throw error; // re-throw the error to notify the caller } };

setupDatabase(); // Call the setup function to connect to the database

// Export the db instance for use in other modules export { db };

Main Function: 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: "apikey", 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}`
);

// 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: "User input: {input}\nSQL query: ", inputVariables: ["input", "top_k", "table_info"], });

// Format the prompt
// const formattedPrompt = await prompt.format({
//   input: "How many employees are there?",
//   top_k: "3",
//   table_info: "foo",
// });

// console.log("Formatted prompt:", formattedPrompt);

// Initialize the LLM (Large Language Model)
const llm = new ChatGoogleGenerativeAI({
  apiKey: "apikey",
  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
const result = await chain.invoke({
  question: "how many employees are there?",
});
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 query

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 (<anonymous>)
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

{ "name": "ask_with_ai", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@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", "mysql": "^2.18.1", "mysql2": "^3.10.1", "sequelize": "^6.37.3", "typeorm": "^0.3.20", "winston": "^3.13.0", "zod": "^3.23.8" } }

System Info

lateste version of langchian

dosubot[bot] commented 2 weeks ago

The error "Missing value for input query" indicates that the input object passed to the FewShotPromptTemplate is missing the required query property. To resolve this, ensure that the input object includes all the necessary properties defined in the inputVariables of the FewShotPromptTemplate.

Here's how you can structure your input object correctly:

  1. Ensure input Object Contains Required Properties:

    • The input object should include input, top_k, and table_info properties as defined in your FewShotPromptTemplate.
  2. Update the invoke Call:

    • When invoking the chain, make sure to pass the correct properties.

Here's an updated version of your main function:

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: "apikey",
      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}`
    );

    // 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: "User input: {input}\nSQL query: ",
      inputVariables: ["input", "top_k", "table_info"],
    });

    // Initialize the LLM (Large Language Model)
    const llm = new ChatGoogleGenerativeAI({
      apiKey: "apikey",
      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
    const result = await chain.invoke({
      input: "how many employees are there?",
      top_k: 3,
      table_info: "foo",
    });
    console.log("SQL Query result:", result);
  } catch (error) {
    console.error("Error occurred:", error);
  }
}

main();

Ensure that the input object passed to the invoke method includes input, top_k, and table_info properties. This should resolve the "Missing value for input query" error [1][2][3].

To continue talking to Dosu, mention @dosu.

psathish10 commented 2 weeks ago

Error occurred: Error: Input must include a question property.

at RunnableLambda.input [as func] (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/langchain/dist/chains/sql_db/sql_db_chain.js:248:19)
at file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/runnables/base.js:1484:45
at MockAsyncLocalStorage.run (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/singletons/index.js:7:16)
at file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/runnables/base.js:1482:67
at new Promise (<anonymous>)
at RunnableLambda._invoke (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/runnables/base.js:1477:16)
at RunnableLambda._callWithConfig (file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/runnables/base.js:210:33)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async file:///C:/Users/SATHISH/OneDrive%20-%20Toolfe/Desktop/Askwith_ai_Backend/Ask_With_AI/node_modules/@langchain/core/dist/runnables/base.js:1329:31
at async Promise.all (index 0)