url
stringlengths
30
161
markdown
stringlengths
27
670k
last_modified
stringclasses
1 value
https://js.langchain.com/v0.2/docs/how_to/graph_mapping
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to map values to a database On this page How to map values to a database =============================== In this guide we’ll go over strategies to improve graph database query generation by mapping values from user inputs to database. When using the built-in graph chains, the LLM is aware of the graph schema, but has no information about the values of properties stored in the database. Therefore, we can introduce a new step in graph database QA system to accurately map values. Setup[​](#setup "Direct link to Setup") --------------------------------------- #### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i langchain @langchain/community @langchain/openai neo4j-driver zod yarn add langchain @langchain/community @langchain/openai neo4j-driver zod pnpm add langchain @langchain/community @langchain/openai neo4j-driver zod #### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") We’ll use OpenAI in this example: OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true Next, we need to define Neo4j credentials. Follow [these installation steps](https://neo4j.com/docs/operations-manual/current/installation/) to set up a Neo4j database. NEO4J_URI="bolt://localhost:7687"NEO4J_USERNAME="neo4j"NEO4J_PASSWORD="password" The below example will create a connection with a Neo4j database and will populate it with example data about movies and their actors. import "neo4j-driver";import { Neo4jGraph } from "@langchain/community/graphs/neo4j_graph";const url = Deno.env.get("NEO4J_URI");const username = Deno.env.get("NEO4J_USER");const password = Deno.env.get("NEO4J_PASSWORD");const graph = await Neo4jGraph.initialize({ url, username, password });// Import movie informationconst moviesQuery = `LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'AS rowMERGE (m:Movie {id:row.movieId})SET m.released = date(row.released), m.title = row.title, m.imdbRating = toFloat(row.imdbRating)FOREACH (director in split(row.director, '|') | MERGE (p:Person {name:trim(director)}) MERGE (p)-[:DIRECTED]->(m))FOREACH (actor in split(row.actors, '|') | MERGE (p:Person {name:trim(actor)}) MERGE (p)-[:ACTED_IN]->(m))FOREACH (genre in split(row.genres, '|') | MERGE (g:Genre {name:trim(genre)}) MERGE (m)-[:IN_GENRE]->(g))`;await graph.query(moviesQuery); Schema refreshed successfully. [] Detecting entities in the user input[​](#detecting-entities-in-the-user-input "Direct link to Detecting entities in the user input") ------------------------------------------------------------------------------------------------------------------------------------ We have to extract the types of entities/values we want to map to a graph database. In this example, we are dealing with a movie graph, so we can map movies and people to the database. import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatOpenAI } from "@langchain/openai";import { z } from "zod";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const entities = z .object({ names: z .array(z.string()) .describe("All the person or movies appearing in the text"), }) .describe("Identifying information about entities.");const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are extracting person and movies from the text."], [ "human", "Use the given format to extract information from the following\ninput: {question}", ],]);const entityChain = prompt.pipe(llm.withStructuredOutput(entities)); We can test the entity extraction chain. const entities = await entityChain.invoke({ question: "Who played in Casino movie?",});entities; { names: [ "Casino" ] } We will utilize a simple `CONTAINS` clause to match entities to database. In practice, you might want to use a fuzzy search or a fulltext index to allow for minor misspellings. const matchQuery = `MATCH (p:Person|Movie)WHERE p.name CONTAINS $value OR p.title CONTAINS $valueRETURN coalesce(p.name, p.title) AS result, labels(p)[0] AS typeLIMIT 1`;const matchToDatabase = async (values) => { let result = ""; for (const entity of values.names) { const response = await graph.query(matchQuery, { value: entity, }); if (response.length > 0) { result += `${entity} maps to ${response[0]["result"]} ${response[0]["type"]} in database\n`; } } return result;};await matchToDatabase(entities); "Casino maps to Casino Movie in database\n" Custom Cypher generating chain[​](#custom-cypher-generating-chain "Direct link to Custom Cypher generating chain") ------------------------------------------------------------------------------------------------------------------ We need to define a custom Cypher prompt that takes the entity mapping information along with the schema and the user question to construct a Cypher statement. We will be using the LangChain expression language to accomplish that. import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";// Generate Cypher statement based on natural language inputconst cypherTemplate = `Based on the Neo4j graph schema below, write a Cypher query that would answer the user's question:{schema}Entities in the question map to the following database values:{entities_list}Question: {question}Cypher query:`;const cypherPrompt = ChatPromptTemplate.fromMessages([ [ "system", "Given an input question, convert it to a Cypher query. No pre-amble.", ], ["human", cypherTemplate],]);const llmWithStop = llm.bind({ stop: ["\nCypherResult:"] });const cypherResponse = RunnableSequence.from([ RunnablePassthrough.assign({ names: entityChain }), RunnablePassthrough.assign({ entities_list: async (x) => matchToDatabase(x.names), schema: async (_) => graph.getSchema(), }), cypherPrompt, llmWithStop, new StringOutputParser(),]); const cypher = await cypherResponse.invoke({ question: "Who played in Casino movie?",});cypher; 'MATCH (:Movie {title: "Casino"})<-[:ACTED_IN]-(actor)\nRETURN actor.name' * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to construct knowledge graphs ](/v0.2/docs/how_to/graph_constructing)[ Next How to improve results with prompting ](/v0.2/docs/how_to/graph_prompting) * [Setup](#setup) * [Detecting entities in the user input](#detecting-entities-in-the-user-input) * [Custom Cypher generating chain](#custom-cypher-generating-chain)
null
https://js.langchain.com/v0.2/docs/introduction/#__docusaurus_skipToContent_fallback
* [](/v0.2/) * Introduction On this page Introduction ============ **LangChain** is a framework for developing applications powered by large language models (LLMs). LangChain simplifies every stage of the LLM application lifecycle: * **Development**: Build your applications using LangChain's open-source [building blocks](/v0.2/docs/how_to/#langchain-expression-language-lcel) and [components](/v0.2/docs/how_to/). Hit the ground running using [third-party integrations](/v0.2/docs/integrations/platforms/). * **Productionization**: Use [LangSmith](https://docs.smith.langchain.com) to inspect, monitor and evaluate your chains, so that you can continuously optimize and deploy with confidence. * **Deployment**: Turn any chain into an API with [LangServe](https://www.langchain.com/langserve). ![Diagram outlining the hierarchical organization of the LangChain framework, displaying the interconnected parts across multiple layers.](/v0.2/svg/langchain_stack.svg "LangChain Framework Overview")![Diagram outlining the hierarchical organization of the LangChain framework, displaying the interconnected parts across multiple layers.](/v0.2/svg/langchain_stack_dark.svg "LangChain Framework Overview") Concretely, the framework consists of the following open-source libraries: * **`@langchain/core`**: Base abstractions and LangChain Expression Language. * **`@langchain/community`**: Third party integrations. * Partner packages (e.g. **`@langchain/openai`**, **`@langchain/anthropic`**, etc.): Some integrations have been further split into their own lightweight packages that only depend on **`@langchain/core`**. * **`langchain`**: Chains, agents, and retrieval strategies that make up an application's cognitive architecture. * **[langgraph](https://www.langchain.com/langserveh)**: Build robust and stateful multi-actor applications with LLMs by modeling steps as edges and nodes in a graph. * **[LangSmith](https://docs.smith.langchain.com)**: A developer platform that lets you debug, test, evaluate, and monitor LLM applications. note These docs focus on the JavaScript LangChain library. [Head here](https://python.langchain.com) for docs on the Python LangChain library. [Tutorials](/v0.2/docs/tutorials)[​](#tutorials "Direct link to tutorials") --------------------------------------------------------------------------- If you're looking to build something specific or are more of a hands-on learner, check out our [tutorials](/v0.2/docs/tutorials). This is the best place to get started. These are the best ones to get started with: * [Build a Simple LLM Application](/v0.2/docs/tutorials/llm_chain) * [Build a Chatbot](/v0.2/docs/tutorials/chatbot) * [Build an Agent](/v0.2/docs/tutorials/agents) Explore the full list of tutorials [here](/v0.2/docs/tutorials). [How-To Guides](/v0.2/docs/how_to/)[​](#how-to-guides "Direct link to how-to-guides") ------------------------------------------------------------------------------------- [Here](/v0.2/docs/how_to/) you'll find short answers to “How do I….?” types of questions. These how-to guides don't cover topics in depth - you'll find that material in the [Tutorials](/v0.2/docs/tutorials) and the [API Reference](https://v02.api.js.langchain.com). However, these guides will help you quickly accomplish common tasks. [Conceptual Guide](/v0.2/docs/concepts)[​](#conceptual-guide "Direct link to conceptual-guide") ----------------------------------------------------------------------------------------------- Introductions to all the key parts of LangChain you'll need to know! [Here](/v0.2/docs/concepts) you'll find high level explanations of all LangChain concepts. [API reference](https://api.js.langchain.com)[​](#api-reference "Direct link to api-reference") ----------------------------------------------------------------------------------------------- Head to the reference section for full documentation of all classes and methods in the LangChain Python packages. Ecosystem[​](#ecosystem "Direct link to Ecosystem") --------------------------------------------------- ### [🦜🛠️ LangSmith](https://docs.smith.langchain.com)[​](#️-langsmith "Direct link to ️-langsmith") Trace and evaluate your language model applications and intelligent agents to help you move from prototype to production. ### [🦜🕸️ LangGraph](https://langchain-ai.github.io/langgraphjs/)[​](#️-langgraph "Direct link to ️-langgraph") Build stateful, multi-actor applications with LLMs, built on top of (and intended to be used with) LangChain primitives. Additional resources[​](#additional-resources "Direct link to Additional resources") ------------------------------------------------------------------------------------ ### [Security](/v0.2/docs/security)[​](#security "Direct link to security") Read up on our [Security](/v0.2/docs/security) best practices to make sure you're developing safely with LangChain. ### [Integrations](/v0.2/docs/integrations/platforms/)[​](#integrations "Direct link to integrations") LangChain is part of a rich ecosystem of tools that integrate with our framework and build on top of it. Check out our growing list of [integrations](/v0.2/docs/integrations/platforms/). ### [Contributing](/v0.2/docs/contributing)[​](#contributing "Direct link to contributing") Check out the developer's guide for guidelines on contributing and help getting your dev environment set up. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Next Tutorials ](/v0.2/docs/tutorials/) * [Tutorials](#tutorials) * [How-To Guides](#how-to-guides) * [Conceptual Guide](#conceptual-guide) * [API reference](#api-reference) * [Ecosystem](#ecosystem) * [🦜🛠️ LangSmith](#️-langsmith) * [🦜🕸️ LangGraph](#️-langgraph) * [Additional resources](#additional-resources) * [Security](#security) * [Integrations](#integrations) * [Contributing](#contributing)
null
https://js.langchain.com/v0.2/docs/how_to/graph_prompting
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to improve results with prompting On this page How to improve results with prompting ===================================== In this guide we’ll go over prompting strategies to improve graph database query generation. We’ll largely focus on methods for getting relevant database-specific information in your prompt. Setup[​](#setup "Direct link to Setup") --------------------------------------- #### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i langchain @langchain/community @langchain/openai neo4j-driver yarn add langchain @langchain/community @langchain/openai neo4j-driver pnpm add langchain @langchain/community @langchain/openai neo4j-driver #### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") We’ll use OpenAI in this example: OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true Next, we need to define Neo4j credentials. Follow [these installation steps](https://neo4j.com/docs/operations-manual/current/installation/) to set up a Neo4j database. NEO4J_URI="bolt://localhost:7687"NEO4J_USERNAME="neo4j"NEO4J_PASSWORD="password" The below example will create a connection with a Neo4j database and will populate it with example data about movies and their actors. const url = Deno.env.get("NEO4J_URI");const username = Deno.env.get("NEO4J_USER");const password = Deno.env.get("NEO4J_PASSWORD"); import "neo4j-driver";import { Neo4jGraph } from "@langchain/community/graphs/neo4j_graph";const graph = await Neo4jGraph.initialize({ url, username, password });// Import movie informationconst moviesQuery = `LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'AS rowMERGE (m:Movie {id:row.movieId})SET m.released = date(row.released), m.title = row.title, m.imdbRating = toFloat(row.imdbRating)FOREACH (director in split(row.director, '|') | MERGE (p:Person {name:trim(director)}) MERGE (p)-[:DIRECTED]->(m))FOREACH (actor in split(row.actors, '|') | MERGE (p:Person {name:trim(actor)}) MERGE (p)-[:ACTED_IN]->(m))FOREACH (genre in split(row.genres, '|') | MERGE (g:Genre {name:trim(genre)}) MERGE (m)-[:IN_GENRE]->(g))`;await graph.query(moviesQuery); Schema refreshed successfully. [] Filtering graph schema ====================== At times, you may need to focus on a specific subset of the graph schema while generating Cypher statements. Let’s say we are dealing with the following graph schema: await graph.refreshSchema();console.log(graph.getSchema()); Node properties are the following:Movie {imdbRating: FLOAT, id: STRING, released: DATE, title: STRING}, Person {name: STRING}, Genre {name: STRING}, Chunk {embedding: LIST, id: STRING, text: STRING}Relationship properties are the following:The relationships are the following:(:Movie)-[:IN_GENRE]->(:Genre), (:Person)-[:DIRECTED]->(:Movie), (:Person)-[:ACTED_IN]->(:Movie) Few-shot examples[​](#few-shot-examples "Direct link to Few-shot examples") --------------------------------------------------------------------------- Including examples of natural language questions being converted to valid Cypher queries against our database in the prompt will often improve model performance, especially for complex queries. Let’s say we have the following examples: const examples = [ { question: "How many artists are there?", query: "MATCH (a:Person)-[:ACTED_IN]->(:Movie) RETURN count(DISTINCT a)", }, { question: "Which actors played in the movie Casino?", query: "MATCH (m:Movie {{title: 'Casino'}})<-[:ACTED_IN]-(a) RETURN a.name", }, { question: "How many movies has Tom Hanks acted in?", query: "MATCH (a:Person {{name: 'Tom Hanks'}})-[:ACTED_IN]->(m:Movie) RETURN count(m)", }, { question: "List all the genres of the movie Schindler's List", query: "MATCH (m:Movie {{title: 'Schindler\\'s List'}})-[:IN_GENRE]->(g:Genre) RETURN g.name", }, { question: "Which actors have worked in movies from both the comedy and action genres?", query: "MATCH (a:Person)-[:ACTED_IN]->(:Movie)-[:IN_GENRE]->(g1:Genre), (a)-[:ACTED_IN]->(:Movie)-[:IN_GENRE]->(g2:Genre) WHERE g1.name = 'Comedy' AND g2.name = 'Action' RETURN DISTINCT a.name", }, { question: "Which directors have made movies with at least three different actors named 'John'?", query: "MATCH (d:Person)-[:DIRECTED]->(m:Movie)<-[:ACTED_IN]-(a:Person) WHERE a.name STARTS WITH 'John' WITH d, COUNT(DISTINCT a) AS JohnsCount WHERE JohnsCount >= 3 RETURN d.name", }, { question: "Identify movies where directors also played a role in the film.", query: "MATCH (p:Person)-[:DIRECTED]->(m:Movie), (p)-[:ACTED_IN]->(m) RETURN m.title, p.name", }, { question: "Find the actor with the highest number of movies in the database.", query: "MATCH (a:Actor)-[:ACTED_IN]->(m:Movie) RETURN a.name, COUNT(m) AS movieCount ORDER BY movieCount DESC LIMIT 1", },]; We can create a few-shot prompt with them like so: import { FewShotPromptTemplate, PromptTemplate } from "@langchain/core/prompts";const examplePrompt = PromptTemplate.fromTemplate( "User input: {question}\nCypher query: {query}");const prompt = new FewShotPromptTemplate({ examples: examples.slice(0, 5), examplePrompt, prefix: "You are a Neo4j expert. Given an input question, create a syntactically correct Cypher query to run.\n\nHere is the schema information\n{schema}.\n\nBelow are a number of examples of questions and their corresponding Cypher queries.", suffix: "User input: {question}\nCypher query: ", inputVariables: ["question", "schema"],}); console.log( await prompt.format({ question: "How many artists are there?", schema: "foo", })); You are a Neo4j expert. Given an input question, create a syntactically correct Cypher query to run.Here is the schema informationfoo.Below are a number of examples of questions and their corresponding Cypher queries.User input: How many artists are there?Cypher query: MATCH (a:Person)-[:ACTED_IN]->(:Movie) RETURN count(DISTINCT a)User input: Which actors played in the movie Casino?Cypher query: MATCH (m:Movie {title: 'Casino'})<-[:ACTED_IN]-(a) RETURN a.nameUser input: How many movies has Tom Hanks acted in?Cypher query: MATCH (a:Person {name: 'Tom Hanks'})-[:ACTED_IN]->(m:Movie) RETURN count(m)User input: List all the genres of the movie Schindler's ListCypher query: MATCH (m:Movie {title: 'Schindler\'s List'})-[:IN_GENRE]->(g:Genre) RETURN g.nameUser input: Which actors have worked in movies from both the comedy and action genres?Cypher query: MATCH (a:Person)-[:ACTED_IN]->(:Movie)-[:IN_GENRE]->(g1:Genre), (a)-[:ACTED_IN]->(:Movie)-[:IN_GENRE]->(g2:Genre) WHERE g1.name = 'Comedy' AND g2.name = 'Action' RETURN DISTINCT a.nameUser input: How many artists are there?Cypher query: Dynamic few-shot examples[​](#dynamic-few-shot-examples "Direct link to Dynamic few-shot examples") --------------------------------------------------------------------------------------------------- If we have enough examples, we may want to only include the most relevant ones in the prompt, either because they don’t fit in the model’s context window or because the long tail of examples distracts the model. And specifically, given any input we want to include the examples most relevant to that input. We can do just this using an ExampleSelector. In this case we’ll use a [SemanticSimilarityExampleSelector](https://v02.api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html), which will store the examples in the vector database of our choosing. At runtime it will perform a similarity search between the input and our examples, and return the most semantically similar ones: import { OpenAIEmbeddings } from "@langchain/openai";import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors";import { Neo4jVectorStore } from "@langchain/community/vectorstores/neo4j_vector";const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( examples, new OpenAIEmbeddings(), Neo4jVectorStore, { k: 5, inputKeys: ["question"], preDeleteCollection: true, url, username, password, }); await exampleSelector.selectExamples({ question: "how many artists are there?",}); [ { query: "MATCH (a:Person)-[:ACTED_IN]->(:Movie) RETURN count(DISTINCT a)", question: "How many artists are there?" }, { query: "MATCH (a:Person {{name: 'Tom Hanks'}})-[:ACTED_IN]->(m:Movie) RETURN count(m)", question: "How many movies has Tom Hanks acted in?" }, { query: "MATCH (a:Person)-[:ACTED_IN]->(:Movie)-[:IN_GENRE]->(g1:Genre), (a)-[:ACTED_IN]->(:Movie)-[:IN_GENRE"... 84 more characters, question: "Which actors have worked in movies from both the comedy and action genres?" }, { query: "MATCH (d:Person)-[:DIRECTED]->(m:Movie)<-[:ACTED_IN]-(a:Person) WHERE a.name STARTS WITH 'John' WITH"... 71 more characters, question: "Which directors have made movies with at least three different actors named 'John'?" }, { query: "MATCH (a:Actor)-[:ACTED_IN]->(m:Movie) RETURN a.name, COUNT(m) AS movieCount ORDER BY movieCount DES"... 9 more characters, question: "Find the actor with the highest number of movies in the database." }] To use it, we can pass the ExampleSelector directly in to our FewShotPromptTemplate: const prompt = new FewShotPromptTemplate({ exampleSelector, examplePrompt, prefix: "You are a Neo4j expert. Given an input question, create a syntactically correct Cypher query to run.\n\nHere is the schema information\n{schema}.\n\nBelow are a number of examples of questions and their corresponding Cypher queries.", suffix: "User input: {question}\nCypher query: ", inputVariables: ["question", "schema"],}); console.log( await prompt.format({ question: "how many artists are there?", schema: "foo", })); You are a Neo4j expert. Given an input question, create a syntactically correct Cypher query to run.Here is the schema informationfoo.Below are a number of examples of questions and their corresponding Cypher queries.User input: How many artists are there?Cypher query: MATCH (a:Person)-[:ACTED_IN]->(:Movie) RETURN count(DISTINCT a)User input: How many movies has Tom Hanks acted in?Cypher query: MATCH (a:Person {name: 'Tom Hanks'})-[:ACTED_IN]->(m:Movie) RETURN count(m)User input: Which actors have worked in movies from both the comedy and action genres?Cypher query: MATCH (a:Person)-[:ACTED_IN]->(:Movie)-[:IN_GENRE]->(g1:Genre), (a)-[:ACTED_IN]->(:Movie)-[:IN_GENRE]->(g2:Genre) WHERE g1.name = 'Comedy' AND g2.name = 'Action' RETURN DISTINCT a.nameUser input: Which directors have made movies with at least three different actors named 'John'?Cypher query: MATCH (d:Person)-[:DIRECTED]->(m:Movie)<-[:ACTED_IN]-(a:Person) WHERE a.name STARTS WITH 'John' WITH d, COUNT(DISTINCT a) AS JohnsCount WHERE JohnsCount >= 3 RETURN d.nameUser input: Find the actor with the highest number of movies in the database.Cypher query: MATCH (a:Actor)-[:ACTED_IN]->(m:Movie) RETURN a.name, COUNT(m) AS movieCount ORDER BY movieCount DESC LIMIT 1User input: how many artists are there?Cypher query: import { ChatOpenAI } from "@langchain/openai";import { GraphCypherQAChain } from "langchain/chains/graph_qa/cypher";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0,});const chain = GraphCypherQAChain.fromLLM({ graph, llm, cypherPrompt: prompt,}); await chain.invoke({ query: "How many actors are in the graph?",}); { result: "There are 967 actors in the graph." } * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to map values to a database ](/v0.2/docs/how_to/graph_mapping)[ Next How to add a semantic layer over the database ](/v0.2/docs/how_to/graph_semantic) * [Setup](#setup) * [Few-shot examples](#few-shot-examples) * [Dynamic few-shot examples](#dynamic-few-shot-examples)
null
https://js.langchain.com/v0.2/docs/how_to/chat_model_caching
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to cache chat model responses On this page How to cache chat model responses ================================= Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) * [LLMs](/v0.2/docs/concepts/#llms) LangChain provides an optional caching layer for chat models. This is useful for two reasons: It can save you money by reducing the number of API calls you make to the LLM provider, if you're often requesting the same completion multiple times. It can speed up your application by reducing the number of API calls you make to the LLM provider. import { ChatOpenAI } from "@langchain/openai";// To make the caching really obvious, lets use a slower model.const model = new ChatOpenAI({ model: "gpt-4", cache: true,}); In Memory Cache[​](#in-memory-cache "Direct link to In Memory Cache") --------------------------------------------------------------------- The default cache is stored in-memory. This means that if you restart your application, the cache will be cleared. console.time();// The first time, it is not yet in cache, so it should take longerconst res = await model.invoke("Tell me a joke!");console.log(res);console.timeEnd();/* AIMessage { lc_serializable: true, lc_kwargs: { content: "Why don't scientists trust atoms?\n\nBecause they make up everything!", additional_kwargs: { function_call: undefined, tool_calls: undefined } }, lc_namespace: [ 'langchain_core', 'messages' ], content: "Why don't scientists trust atoms?\n\nBecause they make up everything!", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined } } default: 2.224s*/ console.time();// The second time it is, so it goes fasterconst res2 = await model.invoke("Tell me a joke!");console.log(res2);console.timeEnd();/* AIMessage { lc_serializable: true, lc_kwargs: { content: "Why don't scientists trust atoms?\n\nBecause they make up everything!", additional_kwargs: { function_call: undefined, tool_calls: undefined } }, lc_namespace: [ 'langchain_core', 'messages' ], content: "Why don't scientists trust atoms?\n\nBecause they make up everything!", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined } } default: 181.98ms*/ Caching with Redis[​](#caching-with-redis "Direct link to Caching with Redis") ------------------------------------------------------------------------------ LangChain also provides a Redis-based cache. This is useful if you want to share the cache across multiple processes or servers. To use it, you'll need to install the `redis` package: * npm * Yarn * pnpm npm install ioredis @langchain/community yarn add ioredis @langchain/community pnpm add ioredis @langchain/community Then, you can pass a `cache` option when you instantiate the LLM. For example: import { ChatOpenAI } from "@langchain/openai";import { Redis } from "ioredis";import { RedisCache } from "@langchain/community/caches/ioredis";const client = new Redis("redis://localhost:6379");const cache = new RedisCache(client, { ttl: 60, // Optional key expiration value});const model = new ChatOpenAI({ cache });const response1 = await model.invoke("Do something random!");console.log(response1);/* AIMessage { content: "Sure! I'll generate a random number for you: 37", additional_kwargs: {} }*/const response2 = await model.invoke("Do something random!");console.log(response2);/* AIMessage { content: "Sure! I'll generate a random number for you: 37", additional_kwargs: {} }*/await client.disconnect(); #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [RedisCache](https://v02.api.js.langchain.com/classes/langchain_community_caches_ioredis.RedisCache.html) from `@langchain/community/caches/ioredis` Caching on the File System[​](#caching-on-the-file-system "Direct link to Caching on the File System") ------------------------------------------------------------------------------------------------------ danger This cache is not recommended for production use. It is only intended for local development. LangChain provides a simple file system cache. By default the cache is stored a temporary directory, but you can specify a custom directory if you want. const cache = await LocalFileCache.create(); Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned how to cache model responses to save time and money. Next, check out the other how-to guides on chat models, like [how to get a model to return structured output](/v0.2/docs/how_to/structured_output) or [how to create your own custom chat model](/v0.2/docs/how_to/custom_chat). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to cache model responses ](/v0.2/docs/how_to/llm_caching)[ Next How to create a custom LLM class ](/v0.2/docs/how_to/custom_llm) * [In Memory Cache](#in-memory-cache) * [Caching with Redis](#caching-with-redis) * [Caching on the File System](#caching-on-the-file-system) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/lcel_cheatsheet
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * LangChain Expression Language Cheatsheet On this page LangChain Expression Language Cheatsheet ======================================== This is a quick reference for all the most important LCEL primitives. For more advanced usage see the [LCEL how-to guides](/v0.2/docs/how_to/#langchain-expression-language-lcel) and the [full API reference](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html). ### Invoke a runnable[​](#invoke-a-runnable "Direct link to Invoke a runnable") #### [runnable.invoke()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#invoke)[​](#runnable.invoke "Direct link to runnable.invoke") import { RunnableLambda } from "@langchain/core/runnables";const runnable = RunnableLambda.from((x: number) => x.toString());await runnable.invoke(5); "5" ### Batch a runnable[​](#batch-a-runnable "Direct link to Batch a runnable") #### [runnable.batch()](hhttps://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#batch)[​](#runnable.batch "Direct link to runnable.batch") import { RunnableLambda } from "@langchain/core/runnables";const runnable = RunnableLambda.from((x: number) => x.toString());await runnable.batch([7, 8, 9]); [ "7", "8", "9" ] ### Stream a runnable[​](#stream-a-runnable "Direct link to Stream a runnable") #### [runnable.stream()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#stream)[​](#runnable.stream "Direct link to runnable.stream") import { RunnableLambda } from "@langchain/core/runnables";async function* generatorFn(x: number[]) { for (const i of x) { yield i.toString(); }}const runnable = RunnableLambda.from(generatorFn);const stream = await runnable.stream([0, 1, 2, 3, 4]);for await (const chunk of stream) { console.log(chunk); console.log("---");} 0---1---2---3---4--- ### Compose runnables[​](#compose-runnables "Direct link to Compose runnables") #### [runnable.pipe()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#pipe)[​](#runnable.pipe "Direct link to runnable.pipe") import { RunnableLambda } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from((x: any) => { return { foo: x };});const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));const chain = runnable1.pipe(runnable2);await chain.invoke(2); [ { foo: 2 }, { foo: 2 } ] #### [RunnableSequence.from()](https://api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html#from)[​](#runnablesequence.from "Direct link to runnablesequence.from") import { RunnableLambda, RunnableSequence } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from((x: any) => { return { foo: x };});const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));const chain = RunnableSequence.from([runnable1, runnable2]);await chain.invoke(2); [ { foo: 2 }, { foo: 2 } ] ### Invoke runnables in parallel[​](#invoke-runnables-in-parallel "Direct link to Invoke runnables in parallel") #### [RunnableParallel](https://api.js.langchain.com/classes/langchain_core_runnables.RunnableParallel.html)[​](#runnableparallel "Direct link to runnableparallel") import { RunnableLambda, RunnableParallel } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from((x: any) => { return { foo: x };});const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));const chain = RunnableParallel.from({ first: runnable1, second: runnable2,});await chain.invoke(2); { first: { foo: 2 }, second: [ 2, 2 ] } ### Turn a function into a runnable[​](#turn-a-function-into-a-runnable "Direct link to Turn a function into a runnable") #### [RunnableLambda](https://api.js.langchain.com/classes/langchain_core_runnables.RunnableLambda.html)[​](#runnablelambda "Direct link to runnablelambda") import { RunnableLambda } from "@langchain/core/runnables";const adder = (x: number) => { return x + 5;};const runnable = RunnableLambda.from(adder);await runnable.invoke(5); 10 ### Merge input and output dicts[​](#merge-input-and-output-dicts "Direct link to Merge input and output dicts") #### [RunnablePassthrough.assign()](https://api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html#assign)[​](#runnablepassthrough.assign "Direct link to runnablepassthrough.assign") import { RunnableLambda, RunnablePassthrough } from "@langchain/core/runnables";const runnable = RunnableLambda.from((x: { foo: number }) => { return x.foo + 7;});const chain = RunnablePassthrough.assign({ bar: runnable,});await chain.invoke({ foo: 10 }); { foo: 10, bar: 17 } ### Include input dict in output dict[​](#include-input-dict-in-output-dict "Direct link to Include input dict in output dict") #### [RunnablePassthrough](https://api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html)[​](#runnablepassthrough "Direct link to runnablepassthrough") import { RunnableLambda, RunnableParallel, RunnablePassthrough,} from "@langchain/core/runnables";const runnable = RunnableLambda.from((x: { foo: number }) => { return x.foo + 7;});const chain = RunnableParallel.from({ bar: runnable, baz: new RunnablePassthrough(),});await chain.invoke({ foo: 10 }); { baz: { foo: 10 }, bar: 17 } ### Add default invocation args[​](#add-default-invocation-args "Direct link to Add default invocation args") #### [runnable.bind()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#bind)[​](#runnable.bind "Direct link to runnable.bind") import { type RunnableConfig, RunnableLambda } from "@langchain/core/runnables";const branchedFn = (mainArg: Record<string, any>, config?: RunnableConfig) => { if (config?.configurable?.boundKey !== undefined) { return { ...mainArg, boundKey: config?.configurable?.boundKey }; } return mainArg;};const runnable = RunnableLambda.from(branchedFn);const boundRunnable = runnable.bind({ configurable: { boundKey: "goodbye!" } });await boundRunnable.invoke({ bar: "hello" }); { bar: "hello", boundKey: "goodbye!" } ### Add fallbacks[​](#add-fallbacks "Direct link to Add fallbacks") #### [runnable.withFallbacks()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#withFallbacks)[​](#runnable.withfallbacks "Direct link to runnable.withfallbacks") import { RunnableLambda } from "@langchain/core/runnables";const runnable = RunnableLambda.from((x: any) => { throw new Error("Error case");});const fallback = RunnableLambda.from((x: any) => x + x);const chain = runnable.withFallbacks({ fallbacks: [fallback] });await chain.invoke("foo"); "foofoo" ### Add retries[​](#add-retries "Direct link to Add retries") #### [runnable.withRetry()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#withRetry)[​](#runnable.withretry "Direct link to runnable.withretry") import { RunnableLambda } from "@langchain/core/runnables";let counter = 0;const retryFn = (_: any) => { counter++; console.log(`attempt with counter ${counter}`); throw new Error("Expected error");};const chain = RunnableLambda.from(retryFn).withRetry({ stopAfterAttempt: 2,});await chain.invoke(2); attempt with counter 1attempt with counter 2 Error: Expected error ### Configure runnable execution[​](#configure-runnable-execution "Direct link to Configure runnable execution") #### [RunnableConfig](https://api.js.langchain.com/interfaces/langchain_core_runnables.RunnableConfig.html)[​](#runnableconfig "Direct link to runnableconfig") import { RunnableLambda } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from(async (x: any) => { await new Promise((resolve) => setTimeout(resolve, 2000)); return { foo: x };});// Takes 4 secondsawait runnable1.batch([1, 2, 3], { maxConcurrency: 2 }); [ { foo: 1 }, { foo: 2 }, { foo: 3 } ] ### Add default config to runnable[​](#add-default-config-to-runnable "Direct link to Add default config to runnable") #### [runnable.withConfig()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#withConfig)[​](#runnable.withconfig "Direct link to runnable.withconfig") import { RunnableLambda } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from(async (x: any) => { await new Promise((resolve) => setTimeout(resolve, 2000)); return { foo: x };}).withConfig({ maxConcurrency: 2,});// Takes 4 secondsawait runnable1.batch([1, 2, 3]); [ { foo: 1 }, { foo: 2 }, { foo: 3 } ] ### Build a chain dynamically based on input[​](#build-a-chain-dynamically-based-on-input "Direct link to Build a chain dynamically based on input") import { RunnableLambda } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from((x: any) => { return { foo: x };});const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));const chain = RunnableLambda.from((x: number): any => { if (x > 6) { return runnable1; } return runnable2;});await chain.invoke(7); { foo: 7 } await chain.invoke(5); [ 5, 5 ] ### Generate a stream of internal events[​](#generate-a-stream-of-internal-events "Direct link to Generate a stream of internal events") #### [runnable.streamEvents()](https://v02.api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#streamEvents)[​](#runnable.streamevents "Direct link to runnable.streamevents") import { RunnableLambda } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from((x: number) => { return { foo: x, };}).withConfig({ runName: "first",});async function* generatorFn(x: { foo: number }) { for (let i = 0; i < x.foo; i++) { yield i.toString(); }}const runnable2 = RunnableLambda.from(generatorFn).withConfig({ runName: "second",});const chain = runnable1.pipe(runnable2);for await (const event of chain.streamEvents(2, { version: "v1" })) { console.log( `event=${event.event} | name=${event.name} | data=${JSON.stringify( event.data )}` );} event=on_chain_start | name=RunnableSequence | data={"input":2}event=on_chain_start | name=first | data={}event=on_chain_stream | name=first | data={"chunk":{"foo":2}}event=on_chain_start | name=second | data={}event=on_chain_end | name=first | data={"input":2,"output":{"foo":2}}event=on_chain_stream | name=second | data={"chunk":"0"}event=on_chain_stream | name=RunnableSequence | data={"chunk":"0"}event=on_chain_stream | name=second | data={"chunk":"1"}event=on_chain_stream | name=RunnableSequence | data={"chunk":"1"}event=on_chain_end | name=second | data={"output":"01"}event=on_chain_end | name=RunnableSequence | data={"output":"01"} ### Return a subset of keys from output object[​](#return-a-subset-of-keys-from-output-object "Direct link to Return a subset of keys from output object") #### [runnable.pick()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#pick)[​](#runnable.pick "Direct link to runnable.pick") import { RunnableLambda, RunnablePassthrough } from "@langchain/core/runnables";const runnable = RunnableLambda.from((x: { baz: number }) => { return x.baz + 5;});const chain = RunnablePassthrough.assign({ foo: runnable,}).pick(["foo", "bar"]);await chain.invoke({ bar: "hi", baz: 2 }); { foo: 7, bar: "hi" } ### Declaratively make a batched version of a runnable[​](#declaratively-make-a-batched-version-of-a-runnable "Direct link to Declaratively make a batched version of a runnable") #### [`runnable.map()`](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#map)[​](#runnable.map "Direct link to runnable.map") import { RunnableLambda } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from((x: number) => [...Array(x).keys()]);const runnable2 = RunnableLambda.from((x: number) => x + 5);const chain = runnable1.pipe(runnable2.map());await chain.invoke(3); [ 5, 6, 7 ] ### Get a graph representation of a runnable[​](#get-a-graph-representation-of-a-runnable "Direct link to Get a graph representation of a runnable") #### [runnable.getGraph()](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#getGraph)[​](#runnable.getgraph "Direct link to runnable.getgraph") import { RunnableLambda, RunnableSequence } from "@langchain/core/runnables";const runnable1 = RunnableLambda.from((x: any) => { return { foo: x };});const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));const runnable3 = RunnableLambda.from((x: any) => x.toString());const chain = RunnableSequence.from([ runnable1, { second: runnable2, third: runnable3, },]);await chain.getGraph(); Graph { nodes: { "935c67df-7ae3-4853-9d26-579003c08407": { id: "935c67df-7ae3-4853-9d26-579003c08407", data: { name: "RunnableLambdaInput", schema: ZodAny { spa: [Function: bound safeParseAsync] AsyncFunction, _def: [Object], parse: [Function: bound parse], safeParse: [Function: bound safeParse], parseAsync: [Function: bound parseAsync] AsyncFunction, safeParseAsync: [Function: bound safeParseAsync] AsyncFunction, refine: [Function: bound refine], refinement: [Function: bound refinement], superRefine: [Function: bound superRefine], optional: [Function: bound optional], nullable: [Function: bound nullable], nullish: [Function: bound nullish], array: [Function: bound array], promise: [Function: bound promise], or: [Function: bound or], and: [Function: bound and], transform: [Function: bound transform], brand: [Function: bound brand], default: [Function: bound default], catch: [Function: bound catch], describe: [Function: bound describe], pipe: [Function: bound pipe], readonly: [Function: bound readonly], isNullable: [Function: bound isNullable], isOptional: [Function: bound isOptional], _any: true } } }, "a73d7b3e-0ed7-46cf-b141-de64ea1e12de": { id: "a73d7b3e-0ed7-46cf-b141-de64ea1e12de", data: RunnableLambda { lc_serializable: false, lc_kwargs: { func: [Function (anonymous)] }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "runnables" ], func: [Function (anonymous)] } }, "ff104b34-c13b-4677-8b82-af70d3548e12": { id: "ff104b34-c13b-4677-8b82-af70d3548e12", data: RunnableMap { lc_serializable: true, lc_kwargs: { steps: [Object] }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "runnables" ], steps: { second: [RunnableLambda], third: [RunnableLambda] } } }, "2dc627dc-1c06-45b1-b14f-bb1f6e689f83": { id: "2dc627dc-1c06-45b1-b14f-bb1f6e689f83", data: { name: "RunnableMapOutput", schema: ZodAny { spa: [Function: bound safeParseAsync] AsyncFunction, _def: [Object], parse: [Function: bound parse], safeParse: [Function: bound safeParse], parseAsync: [Function: bound parseAsync] AsyncFunction, safeParseAsync: [Function: bound safeParseAsync] AsyncFunction, refine: [Function: bound refine], refinement: [Function: bound refinement], superRefine: [Function: bound superRefine], optional: [Function: bound optional], nullable: [Function: bound nullable], nullish: [Function: bound nullish], array: [Function: bound array], promise: [Function: bound promise], or: [Function: bound or], and: [Function: bound and], transform: [Function: bound transform], brand: [Function: bound brand], default: [Function: bound default], catch: [Function: bound catch], describe: [Function: bound describe], pipe: [Function: bound pipe], readonly: [Function: bound readonly], isNullable: [Function: bound isNullable], isOptional: [Function: bound isOptional], _any: true } } } }, edges: [ { source: "935c67df-7ae3-4853-9d26-579003c08407", target: "a73d7b3e-0ed7-46cf-b141-de64ea1e12de", data: undefined }, { source: "ff104b34-c13b-4677-8b82-af70d3548e12", target: "2dc627dc-1c06-45b1-b14f-bb1f6e689f83", data: undefined }, { source: "a73d7b3e-0ed7-46cf-b141-de64ea1e12de", target: "ff104b34-c13b-4677-8b82-af70d3548e12", data: undefined } ]} * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to reindex data to keep your vectorstore in-sync with the underlying data source ](/v0.2/docs/how_to/indexing)[ Next How to get log probabilities ](/v0.2/docs/how_to/logprobs) * [Invoke a runnable](#invoke-a-runnable) * [Batch a runnable](#batch-a-runnable) * [Stream a runnable](#stream-a-runnable) * [Compose runnables](#compose-runnables) * [Invoke runnables in parallel](#invoke-runnables-in-parallel) * [Turn a function into a runnable](#turn-a-function-into-a-runnable) * [Merge input and output dicts](#merge-input-and-output-dicts) * [Include input dict in output dict](#include-input-dict-in-output-dict) * [Add default invocation args](#add-default-invocation-args) * [Add fallbacks](#add-fallbacks) * [Add retries](#add-retries) * [Configure runnable execution](#configure-runnable-execution) * [Add default config to runnable](#add-default-config-to-runnable) * [Build a chain dynamically based on input](#build-a-chain-dynamically-based-on-input) * [Generate a stream of internal events](#generate-a-stream-of-internal-events) * [Return a subset of keys from output object](#return-a-subset-of-keys-from-output-object) * [Declaratively make a batched version of a runnable](#declaratively-make-a-batched-version-of-a-runnable) * [Get a graph representation of a runnable](#get-a-graph-representation-of-a-runnable)
null
https://js.langchain.com/v0.2/docs/how_to/streaming_llm
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to stream responses from an LLM On this page How to stream responses from an LLM =================================== All [`LLM`s](https://v02.api.js.langchain.com/classes/langchain_core_language_models_llms.BaseLLM.html) implement the [Runnable interface](https://v02.api.js.langchain.com/classes/langchain_core_runnables.Runnable.html), which comes with **default** implementations of standard runnable methods (i.e. `ainvoke`, `batch`, `abatch`, `stream`, `astream`, `astream_events`). The **default** streaming implementations provide an `AsyncGenerator` that yields a single value: the final output from the underlying chat model provider. The ability to stream the output token-by-token depends on whether the provider has implemented proper streaming support. See which [integrations support token-by-token streaming here](/v0.2/docs/integrations/llms/). :::{.callout-note} The **default** implementation does **not** provide support for token-by-token streaming, but it ensures that the model can be swapped in for any other model as it supports the same standard interface. ::: Using `.stream()`[​](#using-stream "Direct link to using-stream") ----------------------------------------------------------------- The easiest way to stream is to use the `.stream()` method. This returns an readable stream that you can also iterate over: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { OpenAI } from "@langchain/openai";const model = new OpenAI({ maxTokens: 25,});const stream = await model.stream("Tell me a joke.");for await (const chunk of stream) { console.log(chunk);}/*Q: What did the fish say when it hit the wall?A: Dam!*/ #### API Reference: * [OpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai` For models that do not support streaming, the entire response will be returned as a single chunk. Using a callback handler[​](#using-a-callback-handler "Direct link to Using a callback handler") ------------------------------------------------------------------------------------------------ You can also use a [`CallbackHandler`](https://v02.api.js.langchain.com/classes/langchain_core_callbacks_base.BaseCallbackHandler.html) like so: import { OpenAI } from "@langchain/openai";// To enable streaming, we pass in `streaming: true` to the LLM constructor.// Additionally, we pass in a handler for the `handleLLMNewToken` event.const model = new OpenAI({ maxTokens: 25, streaming: true,});const response = await model.invoke("Tell me a joke.", { callbacks: [ { handleLLMNewToken(token: string) { console.log({ token }); }, }, ],});console.log(response);/*{ token: '\n' }{ token: '\n' }{ token: 'Q' }{ token: ':' }{ token: ' Why' }{ token: ' did' }{ token: ' the' }{ token: ' chicken' }{ token: ' cross' }{ token: ' the' }{ token: ' playground' }{ token: '?' }{ token: '\n' }{ token: 'A' }{ token: ':' }{ token: ' To' }{ token: ' get' }{ token: ' to' }{ token: ' the' }{ token: ' other' }{ token: ' slide' }{ token: '.' }Q: Why did the chicken cross the playground?A: To get to the other slide.*/ #### API Reference: * [OpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai` We still have access to the end `LLMResult` if using `generate`. However, `tokenUsage` may not be currently supported for all model providers when streaming. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Installation ](/v0.2/docs/how_to/installation)[ Next How to stream chat model responses ](/v0.2/docs/how_to/chat_streaming) * [Using `.stream()`](#using-stream) * [Using a callback handler](#using-a-callback-handler)
null
https://js.langchain.com/v0.2/docs/how_to/custom_llm
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to create a custom LLM class On this page How to create a custom LLM class ================================ Prerequisites This guide assumes familiarity with the following concepts: * [LLMs](/v0.2/docs/concepts/#llms) This notebook goes over how to create a custom LLM wrapper, in case you want to use your own LLM or a different wrapper than one that is directly supported in LangChain. There are a few required things that a custom LLM needs to implement after extending the [`LLM` class](https://v02.api.js.langchain.com/classes/langchain_core_language_models_llms.LLM.html): * A `_call` method that takes in a string and call options (which includes things like `stop` sequences), and returns a string. * A `_llmType` method that returns a string. Used for logging purposes only. You can also implement the following optional method: * A `_streamResponseChunks` method that returns an `AsyncIterator` and yields [`GenerationChunks`](https://v02.api.js.langchain.com/classes/langchain_core_outputs.GenerationChunk.html). This allows the LLM to support streaming outputs. Let’s implement a very simple custom LLM that just echoes back the first `n` characters of the input. import { LLM, type BaseLLMParams } from "@langchain/core/language_models/llms";import type { CallbackManagerForLLMRun } from "langchain/callbacks";import { GenerationChunk } from "langchain/schema";export interface CustomLLMInput extends BaseLLMParams { n: number;}export class CustomLLM extends LLM { n: number; constructor(fields: CustomLLMInput) { super(fields); this.n = fields.n; } _llmType() { return "custom"; } async _call( prompt: string, options: this["ParsedCallOptions"], runManager: CallbackManagerForLLMRun ): Promise<string> { // Pass `runManager?.getChild()` when invoking internal runnables to enable tracing // await subRunnable.invoke(params, runManager?.getChild()); return prompt.slice(0, this.n); } async *_streamResponseChunks( prompt: string, options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): AsyncGenerator<GenerationChunk> { // Pass `runManager?.getChild()` when invoking internal runnables to enable tracing // await subRunnable.invoke(params, runManager?.getChild()); for (const letter of prompt.slice(0, this.n)) { yield new GenerationChunk({ text: letter, }); // Trigger the appropriate callback await runManager?.handleLLMNewToken(letter); } }} We can now use this as any other LLM: const llm = new CustomLLM({ n: 4 });await llm.invoke("I am an LLM"); I am And support streaming: const stream = await llm.stream("I am an LLM");for await (const chunk of stream) { console.log(chunk);} Iam Richer outputs[​](#richer-outputs "Direct link to Richer outputs") ------------------------------------------------------------------ If you want to take advantage of LangChain's callback system for functionality like token tracking, you can extend the [`BaseLLM`](https://v02.api.js.langchain.com/classes/langchain_core_language_models_llms.BaseLLM.html) class and implement the lower level `_generate` method. Rather than taking a single string as input and a single string output, it can take multiple input strings and map each to multiple string outputs. Additionally, it returns a `Generation` output with fields for additional metadata rather than just a string. import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";import { LLMResult } from "@langchain/core/outputs";import { BaseLLM, BaseLLMCallOptions, BaseLLMParams,} from "@langchain/core/language_models/llms";export interface AdvancedCustomLLMCallOptions extends BaseLLMCallOptions {}export interface AdvancedCustomLLMParams extends BaseLLMParams { n: number;}export class AdvancedCustomLLM extends BaseLLM<AdvancedCustomLLMCallOptions> { n: number; constructor(fields: AdvancedCustomLLMParams) { super(fields); this.n = fields.n; } _llmType() { return "advanced_custom_llm"; } async _generate( inputs: string[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): Promise<LLMResult> { const outputs = inputs.map((input) => input.slice(0, this.n)); // Pass `runManager?.getChild()` when invoking internal runnables to enable tracing // await subRunnable.invoke(params, runManager?.getChild()); // One input could generate multiple outputs. const generations = outputs.map((output) => [ { text: output, // Optional additional metadata for the generation generationInfo: { outputCount: 1 }, }, ]); const tokenUsage = { usedTokens: this.n, }; return { generations, llmOutput: { tokenUsage }, }; }} This will pass the additional returned information in callback events and in the \`streamEvents method: const llm = new AdvancedCustomLLM({ n: 4 });const eventStream = await llm.streamEvents("I am an LLM", { version: "v1",});for await (const event of eventStream) { if (event.event === "on_llm_end") { console.log(JSON.stringify(event, null, 2)); }} { "event": "on_llm_end", "name": "AdvancedCustomLLM", "run_id": "a883a705-c651-4236-8095-cb515e2d4885", "tags": [], "metadata": {}, "data": { "output": { "generations": [ [ { "text": "I am", "generationInfo": { "outputCount": 1 } } ] ], "llmOutput": { "tokenUsage": { "usedTokens": 4 } } } }} * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to cache chat model responses ](/v0.2/docs/how_to/chat_model_caching)[ Next How to use few shot examples ](/v0.2/docs/how_to/few_shot_examples) * [Richer outputs](#richer-outputs)
null
https://js.langchain.com/v0.2/docs/how_to/logprobs
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to get log probabilities On this page How to get log probabilities ============================ Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) Certain chat models can be configured to return token-level log probabilities representing the likelihood of a given token. This guide walks through how to get this information in LangChain. OpenAI[​](#openai "Direct link to OpenAI") ------------------------------------------ Install the `@langchain/openai` package and set your API key: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai For the OpenAI API to return log probabilities, we need to set the `logprobs` param to `true`. Then, the logprobs are included on each output [`AIMessage`](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.ai.AIMessage.html) as part of the `response_metadata`: import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-4o", logprobs: true,});const responseMessage = await model.invoke("how are you today?");responseMessage.response_metadata.logprobs.content.slice(0, 5); [ { token: "Thank", logprob: -0.70174205, bytes: [ 84, 104, 97, 110, 107 ], top_logprobs: [] }, { token: " you", logprob: 0, bytes: [ 32, 121, 111, 117 ], top_logprobs: [] }, { token: " for", logprob: -0.000004723352, bytes: [ 32, 102, 111, 114 ], top_logprobs: [] }, { token: " asking", logprob: -0.0000013856493, bytes: [ 32, 97, 115, 107, 105, 110, 103 ], top_logprobs: [] }, { token: "!", logprob: -0.00030102333, bytes: [ 33 ], top_logprobs: [] }] And are part of streamed Message chunks as well: let count = 0;const stream = await model.stream("How are you today?");let aggregateResponse;for await (const chunk of stream) { if (count > 5) { break; } if (aggregateResponse === undefined) { aggregateResponse = chunk; } else { aggregateResponse = aggregateResponse.concat(chunk); } console.log(aggregateResponse.response_metadata.logprobs?.content); count++;} [][ { token: "Thank", logprob: -0.23375113, bytes: [ 84, 104, 97, 110, 107 ], top_logprobs: [] }][ { token: "Thank", logprob: -0.23375113, bytes: [ 84, 104, 97, 110, 107 ], top_logprobs: [] }, { token: " you", logprob: 0, bytes: [ 32, 121, 111, 117 ], top_logprobs: [] }][ { token: "Thank", logprob: -0.23375113, bytes: [ 84, 104, 97, 110, 107 ], top_logprobs: [] }, { token: " you", logprob: 0, bytes: [ 32, 121, 111, 117 ], top_logprobs: [] }, { token: " for", logprob: -0.000004723352, bytes: [ 32, 102, 111, 114 ], top_logprobs: [] }][ { token: "Thank", logprob: -0.23375113, bytes: [ 84, 104, 97, 110, 107 ], top_logprobs: [] }, { token: " you", logprob: 0, bytes: [ 32, 121, 111, 117 ], top_logprobs: [] }, { token: " for", logprob: -0.000004723352, bytes: [ 32, 102, 111, 114 ], top_logprobs: [] }, { token: " asking", logprob: -0.0000029352968, bytes: [ 32, 97, 115, 107, 105, 110, 103 ], top_logprobs: [] }][ { token: "Thank", logprob: -0.23375113, bytes: [ 84, 104, 97, 110, 107 ], top_logprobs: [] }, { token: " you", logprob: 0, bytes: [ 32, 121, 111, 117 ], top_logprobs: [] }, { token: " for", logprob: -0.000004723352, bytes: [ 32, 102, 111, 114 ], top_logprobs: [] }, { token: " asking", logprob: -0.0000029352968, bytes: [ 32, 97, 115, 107, 105, 110, 103 ], top_logprobs: [] }, { token: "!", logprob: -0.00039694557, bytes: [ 33 ], top_logprobs: [] }] `topLogprobs`[​](#toplogprobs "Direct link to toplogprobs") ----------------------------------------------------------- To see alternate potential generations at each step, you can use the `topLogprobs` parameter: const model = new ChatOpenAI({ model: "gpt-4o", logprobs: true, topLogprobs: 3,});const responseMessage = await model.invoke("how are you today?");responseMessage.response_metadata.logprobs.content.slice(0, 5); [ { token: "I'm", logprob: -2.2864406, bytes: [ 73, 39, 109 ], top_logprobs: [ { token: "Thank", logprob: -0.28644064, bytes: [ 84, 104, 97, 110, 107 ] }, { token: "Hello", logprob: -2.0364406, bytes: [ 72, 101, 108, 108, 111 ] }, { token: "I'm", logprob: -2.2864406, bytes: [ 73, 39, 109 ] } ] }, { token: " just", logprob: -0.14442946, bytes: [ 32, 106, 117, 115, 116 ], top_logprobs: [ { token: " just", logprob: -0.14442946, bytes: [ 32, 106, 117, 115, 116 ] }, { token: " an", logprob: -2.2694294, bytes: [ 32, 97, 110 ] }, { token: " here", logprob: -4.0194297, bytes: [ 32, 104, 101, 114, 101 ] } ] }, { token: " a", logprob: -0.00066632946, bytes: [ 32, 97 ], top_logprobs: [ { token: " a", logprob: -0.00066632946, bytes: [ 32, 97 ] }, { token: " lines", logprob: -7.750666, bytes: [ 32, 108, 105, 110, 101, 115 ] }, { token: " an", logprob: -9.250667, bytes: [ 32, 97, 110 ] } ] }, { token: " computer", logprob: -0.015423919, bytes: [ 32, 99, 111, 109, 112, 117, 116, 101, 114 ], top_logprobs: [ { token: " computer", logprob: -0.015423919, bytes: [ 32, 99, 111, 109, 112, 117, 116, 101, 114 ] }, { token: " program", logprob: -5.265424, bytes: [ 32, 112, 114, 111, 103, 114, 97, 109 ] }, { token: " machine", logprob: -5.390424, bytes: [ 32, 109, 97, 99, 104, 105, 110, 101 ] } ] }, { token: " program", logprob: -0.0010724656, bytes: [ 32, 112, 114, 111, 103, 114, 97, 109 ], top_logprobs: [ { token: " program", logprob: -0.0010724656, bytes: [ 32, 112, 114, 111, 103, 114, 97, 109 ] }, { token: "-based", logprob: -6.8760724, bytes: [ 45, 98, 97, 115, 101, 100 ] }, { token: " algorithm", logprob: -10.626073, bytes: [ 32, 97, 108, 103, 111, 114, 105, 116, 104, 109 ] } ] }] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to get logprobs from OpenAI models in LangChain. Next, check out the other how-to guides chat models in this section, like [how to get a model to return structured output](/v0.2/docs/how_to/structured_output) or [how to track token usage](/v0.2/docs/how_to/chat_token_usage_tracking). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous LangChain Expression Language Cheatsheet ](/v0.2/docs/how_to/lcel_cheatsheet)[ Next How to merge consecutive messages of the same type ](/v0.2/docs/how_to/merge_message_runs) * [OpenAI](#openai) * [`topLogprobs`](#toplogprobs) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/indexing
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to reindex data to keep your vectorstore in-sync with the underlying data source On this page How to reindex data to keep your vectorstore in-sync with the underlying data source ==================================================================================== Prerequisites This guide assumes familiarity with the following concepts: * [Retrieval-augmented generation (RAG)](/v0.2/docs/tutorials/rag/) * [Vector stores](/v0.2/docs/concepts/#vectorstores) Here, we will look at a basic indexing workflow using the LangChain indexing API. The indexing API lets you load and keep in sync documents from any source into a vector store. Specifically, it helps: * Avoid writing duplicated content into the vector store * Avoid re-writing unchanged content * Avoid re-computing embeddings over unchanged content All of which should save you time and money, as well as improve your vector search results. Crucially, the indexing API will work even with documents that have gone through several transformation steps (e.g., via text chunking) with respect to the original source documents. How it works[​](#how-it-works "Direct link to How it works") ------------------------------------------------------------ LangChain indexing makes use of a record manager (`RecordManager`) that keeps track of document writes into the vector store. When indexing content, hashes are computed for each document, and the following information is stored in the record manager: * the document hash (hash of both page content and metadata) * write time * the source ID - each document should include information in its metadata to allow us to determine the ultimate source of this document Deletion Modes[​](#deletion-modes "Direct link to Deletion Modes") ------------------------------------------------------------------ When indexing documents into a vector store, it's possible that some existing documents in the vector store should be deleted. In certain situations you may want to remove any existing documents that are derived from the same sources as the new documents being indexed. In others you may want to delete all existing documents wholesale. The indexing API deletion modes let you pick the behavior you want: Cleanup Mode De-Duplicates Content Parallelizable Cleans Up Deleted Source Docs Cleans Up Mutations of Source Docs and/or Derived Docs Clean Up Timing None ✅ ✅ ❌ ❌ \- Incremental ✅ ✅ ❌ ✅ Continuously Full ✅ ❌ ✅ ✅ At end of indexing `None` does not do any automatic clean up, allowing the user to manually do clean up of old content. `incremental` and `full` offer the following automated clean up: * If the content of the source document or derived documents has changed, both `incremental` or `full` modes will clean up (delete) previous versions of the content. * If the source document has been deleted (meaning it is not included in the documents currently being indexed), the full cleanup mode will delete it from the vector store correctly, but the `incremental` mode will not. When content is mutated (e.g., the source PDF file was revised) there will be a period of time during indexing when both the new and old versions may be returned to the user. This happens after the new content was written, but before the old version was deleted. * `incremental` indexing minimizes this period of time as it is able to do clean up continuously, as it writes. * `full` mode does the clean up after all batches have been written. Requirements[​](#requirements "Direct link to Requirements") ------------------------------------------------------------ 1. Do not use with a store that has been pre-populated with content independently of the indexing API, as the record manager will not know that records have been inserted previously. 2. Only works with LangChain `vectorstore`'s that support: a). document addition by id (`addDocuments` method with ids argument) b). delete by id (delete method with ids argument) Compatible Vectorstores: [`PGVector`](/v0.2/docs/integrations/vectorstores/pgvector), [`Chroma`](/v0.2/docs/integrations/vectorstores/chroma), [`CloudflareVectorize`](/v0.2/docs/integrations/vectorstores/cloudflare_vectorize), [`ElasticVectorSearch`](/v0.2/docs/integrations/vectorstores/elasticsearch), [`FAISS`](/v0.2/docs/integrations/vectorstores/faiss), [`MomentoVectorIndex`](/v0.2/docs/integrations/vectorstores/momento_vector_index), [`Pinecone`](/v0.2/docs/integrations/vectorstores/pinecone), [`SupabaseVectorStore`](/v0.2/docs/integrations/vectorstores/supabase), [`VercelPostgresVectorStore`](/v0.2/docs/integrations/vectorstores/vercel_postgres), [`Weaviate`](/v0.2/docs/integrations/vectorstores/weaviate), [`Xata`](/v0.2/docs/integrations/vectorstores/xata) Caution[​](#caution "Direct link to Caution") --------------------------------------------- The record manager relies on a time-based mechanism to determine what content can be cleaned up (when using `full` or `incremental` cleanup modes). If two tasks run back-to-back, and the first task finishes before the clock time changes, then the second task may not be able to clean up content. This is unlikely to be an issue in actual settings for the following reasons: 1. The `RecordManager` uses higher resolution timestamps. 2. The data would need to change between the first and the second tasks runs, which becomes unlikely if the time interval between the tasks is small. 3. Indexing tasks typically take more than a few ms. Quickstart[​](#quickstart "Direct link to Quickstart") ------------------------------------------------------ import { PostgresRecordManager } from "@langchain/community/indexes/postgres";import { index } from "langchain/indexes";import { PGVectorStore } from "@langchain/community/vectorstores/pgvector";import { PoolConfig } from "pg";import { OpenAIEmbeddings } from "@langchain/openai";import { CharacterTextSplitter } from "@langchain/textsplitters";import { BaseDocumentLoader } from "@langchain/core/document_loaders/base";// First, follow set-up instructions at// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/pgvectorconst config = { postgresConnectionOptions: { type: "postgres", host: "127.0.0.1", port: 5432, user: "myuser", password: "ChangeMe", database: "api", } as PoolConfig, tableName: "testlangchain", columns: { idColumnName: "id", vectorColumnName: "vector", contentColumnName: "content", metadataColumnName: "metadata", },};const vectorStore = await PGVectorStore.initialize( new OpenAIEmbeddings(), config);// Create a new record managerconst recordManagerConfig = { postgresConnectionOptions: { type: "postgres", host: "127.0.0.1", port: 5432, user: "myuser", password: "ChangeMe", database: "api", } as PoolConfig, tableName: "upsertion_records",};const recordManager = new PostgresRecordManager( "test_namespace", recordManagerConfig);// Create the schema if it doesn't existawait recordManager.createSchema();// Index some documentsconst doc1 = { pageContent: "kitty", metadata: { source: "kitty.txt" },};const doc2 = { pageContent: "doggy", metadata: { source: "doggy.txt" },};/** * Hacky helper method to clear content. See the `full` mode section to to understand why it works. */async function clear() { await index({ docsSource: [], recordManager, vectorStore, options: { cleanup: "full", sourceIdKey: "source", }, });}// No cleanupawait clear();// This mode does not do automatic clean up of old versions of content; however, it still takes care of content de-duplication.console.log( await index({ docsSource: [doc1, doc1, doc1, doc1, doc1, doc1], recordManager, vectorStore, options: { cleanup: undefined, sourceIdKey: "source", }, }));/* { numAdded: 1, numUpdated: 0, numDeleted: 0, numSkipped: 0, }*/await clear();console.log( await index({ docsSource: [doc1, doc2], recordManager, vectorStore, options: { cleanup: undefined, sourceIdKey: "source", }, }));/* { numAdded: 2, numUpdated: 0, numDeleted: 0, numSkipped: 0, }*/// Second time around all content will be skippedconsole.log( await index({ docsSource: [doc1, doc2], recordManager, vectorStore, options: { cleanup: undefined, sourceIdKey: "source", }, }));/* { numAdded: 0, numUpdated: 0, numDeleted: 0, numSkipped: 2, }*/// Updated content will be added, but old won't be deletedconst doc1Updated = { pageContent: "kitty updated", metadata: { source: "kitty.txt" },};console.log( await index({ docsSource: [doc1Updated, doc2], recordManager, vectorStore, options: { cleanup: undefined, sourceIdKey: "source", }, }));/* { numAdded: 1, numUpdated: 0, numDeleted: 0, numSkipped: 1, }*//*Resulting records in the database: [ { pageContent: "kitty", metadata: { source: "kitty.txt" }, }, { pageContent: "doggy", metadata: { source: "doggy.txt" }, }, { pageContent: "kitty updated", metadata: { source: "kitty.txt" }, } ]*/// Incremental modeawait clear();console.log( await index({ docsSource: [doc1, doc2], recordManager, vectorStore, options: { cleanup: "incremental", sourceIdKey: "source", }, }));/* { numAdded: 2, numUpdated: 0, numDeleted: 0, numSkipped: 0, }*/// Indexing again should result in both documents getting skipped – also skipping the embedding operation!console.log( await index({ docsSource: [doc1, doc2], recordManager, vectorStore, options: { cleanup: "incremental", sourceIdKey: "source", }, }));/* { numAdded: 0, numUpdated: 0, numDeleted: 0, numSkipped: 2, }*/// If we provide no documents with incremental indexing mode, nothing will change.console.log( await index({ docsSource: [], recordManager, vectorStore, options: { cleanup: "incremental", sourceIdKey: "source", }, }));/* { numAdded: 0, numUpdated: 0, numDeleted: 0, numSkipped: 0, }*/// If we mutate a document, the new version will be written and all old versions sharing the same source will be deleted.// This only affects the documents with the same source id!const changedDoc1 = { pageContent: "kitty updated", metadata: { source: "kitty.txt" },};console.log( await index({ docsSource: [changedDoc1], recordManager, vectorStore, options: { cleanup: "incremental", sourceIdKey: "source", }, }));/* { numAdded: 1, numUpdated: 0, numDeleted: 1, numSkipped: 0, }*/// Full modeawait clear();// In full mode the user should pass the full universe of content that should be indexed into the indexing function.// Any documents that are not passed into the indexing function and are present in the vectorStore will be deleted!// This behavior is useful to handle deletions of source documents.const allDocs = [doc1, doc2];console.log( await index({ docsSource: allDocs, recordManager, vectorStore, options: { cleanup: "full", sourceIdKey: "source", }, }));/* { numAdded: 2, numUpdated: 0, numDeleted: 0, numSkipped: 0, }*/// Say someone deleted the first doc:const doc2Only = [doc2];// Using full mode will clean up the deleted content as well.// This afffects all documents regardless of source id!console.log( await index({ docsSource: doc2Only, recordManager, vectorStore, options: { cleanup: "full", sourceIdKey: "source", }, }));/* { numAdded: 0, numUpdated: 0, numDeleted: 1, numSkipped: 1, }*/await clear();const newDoc1 = { pageContent: "kitty kitty kitty kitty kitty", metadata: { source: "kitty.txt" },};const newDoc2 = { pageContent: "doggy doggy the doggy", metadata: { source: "doggy.txt" },};const splitter = new CharacterTextSplitter({ separator: "t", keepSeparator: true, chunkSize: 12, chunkOverlap: 2,});const newDocs = await splitter.splitDocuments([newDoc1, newDoc2]);console.log(newDocs);/*[ { pageContent: 'kitty kit', metadata: {source: 'kitty.txt'} }, { pageContent: 'tty kitty ki', metadata: {source: 'kitty.txt'} }, { pageContent: 'tty kitty', metadata: {source: 'kitty.txt'}, }, { pageContent: 'doggy doggy', metadata: {source: 'doggy.txt'}, { pageContent: 'the doggy', metadata: {source: 'doggy.txt'}, }]*/console.log( await index({ docsSource: newDocs, recordManager, vectorStore, options: { cleanup: "incremental", sourceIdKey: "source", }, }));/*{ numAdded: 5, numUpdated: 0, numDeleted: 0, numSkipped: 0,}*/const changedDoggyDocs = [ { pageContent: "woof woof", metadata: { source: "doggy.txt" }, }, { pageContent: "woof woof woof", metadata: { source: "doggy.txt" }, },];console.log( await index({ docsSource: changedDoggyDocs, recordManager, vectorStore, options: { cleanup: "incremental", sourceIdKey: "source", }, }));/*{ numAdded: 2, numUpdated: 0, numDeleted: 2, numSkipped: 0,}*/// Usage with document loaders// Create a document loaderclass MyCustomDocumentLoader extends BaseDocumentLoader { load() { return Promise.resolve([ { pageContent: "kitty", metadata: { source: "kitty.txt" }, }, { pageContent: "doggy", metadata: { source: "doggy.txt" }, }, ]); }}await clear();const loader = new MyCustomDocumentLoader();console.log( await index({ docsSource: loader, recordManager, vectorStore, options: { cleanup: "incremental", sourceIdKey: "source", }, }));/*{ numAdded: 2, numUpdated: 0, numDeleted: 0, numSkipped: 0,}*/// Closing resourcesawait recordManager.end();await vectorStore.end(); #### API Reference: * [PostgresRecordManager](https://v02.api.js.langchain.com/classes/langchain_community_indexes_postgres.PostgresRecordManager.html) from `@langchain/community/indexes/postgres` * index from `langchain/indexes` * [PGVectorStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_pgvector.PGVectorStore.html) from `@langchain/community/vectorstores/pgvector` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [CharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.CharacterTextSplitter.html) from `@langchain/textsplitters` * [BaseDocumentLoader](https://v02.api.js.langchain.com/classes/langchain_core_document_loaders_base.BaseDocumentLoader.html) from `@langchain/core/document_loaders/base` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned how to use indexing in your RAG pipelines. Next, check out some of the other sections on retrieval. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to add a semantic layer over the database ](/v0.2/docs/how_to/graph_semantic)[ Next LangChain Expression Language Cheatsheet ](/v0.2/docs/how_to/lcel_cheatsheet) * [How it works](#how-it-works) * [Deletion Modes](#deletion-modes) * [Requirements](#requirements) * [Caution](#caution) * [Quickstart](#quickstart) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/llm_caching
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to cache model responses On this page How to cache model responses ============================ LangChain provides an optional caching layer for LLMs. This is useful for two reasons: It can save you money by reducing the number of API calls you make to the LLM provider, if you're often requesting the same completion multiple times. It can speed up your application by reducing the number of API calls you make to the LLM provider. tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { OpenAI } from "@langchain/openai";const model = new OpenAI({ model: "gpt-3.5-turbo-instruct", cache: true,}); In Memory Cache[​](#in-memory-cache "Direct link to In Memory Cache") --------------------------------------------------------------------- The default cache is stored in-memory. This means that if you restart your application, the cache will be cleared. console.time();// The first time, it is not yet in cache, so it should take longerconst res = await model.invoke("Tell me a long joke");console.log(res);console.timeEnd();/* A man walks into a bar and sees a jar filled with money on the counter. Curious, he asks the bartender about it. The bartender explains, "We have a challenge for our customers. If you can complete three tasks, you win all the money in the jar." Intrigued, the man asks what the tasks are. The bartender replies, "First, you have to drink a whole bottle of tequila without making a face. Second, there's a pitbull out back with a sore tooth. You have to pull it out. And third, there's an old lady upstairs who has never had an orgasm. You have to give her one." The man thinks for a moment and then confidently says, "I'll do it." He grabs the bottle of tequila and downs it in one gulp, without flinching. He then heads to the back and after a few minutes of struggling, emerges with the pitbull's tooth in hand. The bar erupts in cheers and the bartender leads the man upstairs to the old lady's room. After a few minutes, the man walks out with a big smile on his face and the old lady is giggling with delight. The bartender hands the man the jar of money and asks, "How default: 4.187s*/ console.time();// The second time it is, so it goes fasterconst res2 = await model.invoke("Tell me a joke");console.log(res2);console.timeEnd();/* A man walks into a bar and sees a jar filled with money on the counter. Curious, he asks the bartender about it. The bartender explains, "We have a challenge for our customers. If you can complete three tasks, you win all the money in the jar." Intrigued, the man asks what the tasks are. The bartender replies, "First, you have to drink a whole bottle of tequila without making a face. Second, there's a pitbull out back with a sore tooth. You have to pull it out. And third, there's an old lady upstairs who has never had an orgasm. You have to give her one." The man thinks for a moment and then confidently says, "I'll do it." He grabs the bottle of tequila and downs it in one gulp, without flinching. He then heads to the back and after a few minutes of struggling, emerges with the pitbull's tooth in hand. The bar erupts in cheers and the bartender leads the man upstairs to the old lady's room. After a few minutes, the man walks out with a big smile on his face and the old lady is giggling with delight. The bartender hands the man the jar of money and asks, "How default: 175.74ms*/ Caching with Momento[​](#caching-with-momento "Direct link to Caching with Momento") ------------------------------------------------------------------------------------ LangChain also provides a Momento-based cache. [Momento](https://gomomento.com) is a distributed, serverless cache that requires zero setup or infrastructure maintenance. Given Momento's compatibility with Node.js, browser, and edge environments, ensure you install the relevant package. To install for **Node.js**: * npm * Yarn * pnpm npm install @gomomento/sdk yarn add @gomomento/sdk pnpm add @gomomento/sdk To install for **browser/edge workers**: * npm * Yarn * pnpm npm install @gomomento/sdk-web yarn add @gomomento/sdk-web pnpm add @gomomento/sdk-web Next you'll need to sign up and create an API key. Once you've done that, pass a `cache` option when you instantiate the LLM like this: import { OpenAI } from "@langchain/openai";import { CacheClient, Configurations, CredentialProvider,} from "@gomomento/sdk";import { MomentoCache } from "@langchain/community/caches/momento";// See https://github.com/momentohq/client-sdk-javascript for connection optionsconst client = new CacheClient({ configuration: Configurations.Laptop.v1(), credentialProvider: CredentialProvider.fromEnvironmentVariable({ environmentVariableName: "MOMENTO_API_KEY", }), defaultTtlSeconds: 60 * 60 * 24,});const cache = await MomentoCache.fromProps({ client, cacheName: "langchain",});const model = new OpenAI({ cache }); #### API Reference: * [OpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai` * [MomentoCache](https://v02.api.js.langchain.com/classes/langchain_community_caches_momento.MomentoCache.html) from `@langchain/community/caches/momento` Caching with Redis[​](#caching-with-redis "Direct link to Caching with Redis") ------------------------------------------------------------------------------ LangChain also provides a Redis-based cache. This is useful if you want to share the cache across multiple processes or servers. To use it, you'll need to install the `redis` package: * npm * Yarn * pnpm npm install ioredis yarn add ioredis pnpm add ioredis Then, you can pass a `cache` option when you instantiate the LLM. For example: import { OpenAI } from "@langchain/openai";import { RedisCache } from "@langchain/community/caches/ioredis";import { Redis } from "ioredis";// See https://github.com/redis/ioredis for connection optionsconst client = new Redis({});const cache = new RedisCache(client);const model = new OpenAI({ cache }); Caching with Upstash Redis[​](#caching-with-upstash-redis "Direct link to Caching with Upstash Redis") ------------------------------------------------------------------------------------------------------ LangChain provides an Upstash Redis-based cache. Like the Redis-based cache, this cache is useful if you want to share the cache across multiple processes or servers. The Upstash Redis client uses HTTP and supports edge environments. To use it, you'll need to install the `@upstash/redis` package: * npm * Yarn * pnpm npm install @upstash/redis yarn add @upstash/redis pnpm add @upstash/redis You'll also need an [Upstash account](https://docs.upstash.com/redis#create-account) and a [Redis database](https://docs.upstash.com/redis#create-a-database) to connect to. Once you've done that, retrieve your REST URL and REST token. Then, you can pass a `cache` option when you instantiate the LLM. For example: import { OpenAI } from "@langchain/openai";import { UpstashRedisCache } from "@langchain/community/caches/upstash_redis";// See https://docs.upstash.com/redis/howto/connectwithupstashredis#quick-start for connection optionsconst cache = new UpstashRedisCache({ config: { url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN", },});const model = new OpenAI({ cache }); #### API Reference: * [OpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai` * [UpstashRedisCache](https://v02.api.js.langchain.com/classes/langchain_community_caches_upstash_redis.UpstashRedisCache.html) from `@langchain/community/caches/upstash_redis` You can also directly pass in a previously created [@upstash/redis](https://docs.upstash.com/redis/sdks/javascriptsdk/overview) client instance: import { Redis } from "@upstash/redis";import https from "https";import { OpenAI } from "@langchain/openai";import { UpstashRedisCache } from "@langchain/community/caches/upstash_redis";// const client = new Redis({// url: process.env.UPSTASH_REDIS_REST_URL!,// token: process.env.UPSTASH_REDIS_REST_TOKEN!,// agent: new https.Agent({ keepAlive: true }),// });// Or simply call Redis.fromEnv() to automatically load the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN environment variables.const client = Redis.fromEnv({ agent: new https.Agent({ keepAlive: true }),});const cache = new UpstashRedisCache({ client });const model = new OpenAI({ cache }); #### API Reference: * [OpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai` * [UpstashRedisCache](https://v02.api.js.langchain.com/classes/langchain_community_caches_upstash_redis.UpstashRedisCache.html) from `@langchain/community/caches/upstash_redis` Caching with Cloudflare KV[​](#caching-with-cloudflare-kv "Direct link to Caching with Cloudflare KV") ------------------------------------------------------------------------------------------------------ info This integration is only supported in Cloudflare Workers. If you're deploying your project as a Cloudflare Worker, you can use LangChain's Cloudflare KV-powered LLM cache. For information on how to set up KV in Cloudflare, see [the official documentation](https://developers.cloudflare.com/kv/). **Note:** If you are using TypeScript, you may need to install types if they aren't already present: * npm * Yarn * pnpm npm install -S @cloudflare/workers-types yarn add @cloudflare/workers-types pnpm add @cloudflare/workers-types import type { KVNamespace } from "@cloudflare/workers-types";import { OpenAI } from "@langchain/openai";import { CloudflareKVCache } from "@langchain/cloudflare";export interface Env { KV_NAMESPACE: KVNamespace; OPENAI_API_KEY: string;}export default { async fetch(_request: Request, env: Env) { try { const cache = new CloudflareKVCache(env.KV_NAMESPACE); const model = new OpenAI({ cache, model: "gpt-3.5-turbo-instruct", apiKey: env.OPENAI_API_KEY, }); const response = await model.invoke("How are you today?"); return new Response(JSON.stringify(response), { headers: { "content-type": "application/json" }, }); } catch (err: any) { console.log(err.message); return new Response(err.message, { status: 500 }); } },}; #### API Reference: * [OpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai` * [CloudflareKVCache](https://v02.api.js.langchain.com/classes/langchain_cloudflare.CloudflareKVCache.html) from `@langchain/cloudflare` Caching on the File System[​](#caching-on-the-file-system "Direct link to Caching on the File System") ------------------------------------------------------------------------------------------------------ danger This cache is not recommended for production use. It is only intended for local development. LangChain provides a simple file system cache. By default the cache is stored a temporary directory, but you can specify a custom directory if you want. const cache = await LocalFileCache.create(); Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned how to cache model responses to save time and money. Next, check out the other how-to guides on LLMs, like [how to create your own custom LLM class](/v0.2/docs/how_to/custom_llm). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use few shot examples in chat models ](/v0.2/docs/how_to/few_shot_examples_chat)[ Next How to cache chat model responses ](/v0.2/docs/how_to/chat_model_caching) * [In Memory Cache](#in-memory-cache) * [Caching with Momento](#caching-with-momento) * [Caching with Redis](#caching-with-redis) * [Caching with Upstash Redis](#caching-with-upstash-redis) * [Caching with Cloudflare KV](#caching-with-cloudflare-kv) * [Caching on the File System](#caching-on-the-file-system) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/few_shot_examples_chat
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use few shot examples in chat models On this page How to use few shot examples in chat models =========================================== This guide covers how to prompt a chat model with example inputs and outputs. Providing the model with a few such examples is called few-shotting, and is a simple yet powerful way to guide generation and in some cases drastically improve model performance. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the [FewShotChatMessagePromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.FewShotChatMessagePromptTemplate.html) as a flexible starting point, and you can modify or replace them as you see fit. The goal of few-shot prompt templates are to dynamically select examples based on an input, and then format the examples in a final prompt to provide for the model. **Note:** The following code examples are for chat models only, since `FewShotChatMessagePromptTemplates` are designed to output formatted [chat messages](/v0.2/docs/concepts/#message-types) rather than pure strings. For similar few-shot prompt examples for pure string templates compatible with completion models (LLMs), see the [few-shot prompt templates](/v0.2/docs/how_to/few_shot_examples/) guide. Prerequisites This guide assumes familiarity with the following concepts: * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) * [Example selectors](/v0.2/docs/concepts/#example-selectors) * [Chat models](/v0.2/docs/concepts/#chat-model) * [Vectorstores](/v0.2/docs/concepts/#vectorstores) Fixed Examples[​](#fixed-examples "Direct link to Fixed Examples") ------------------------------------------------------------------ The most basic (and common) few-shot prompting technique is to use fixed prompt examples. This way you can select a chain, evaluate it, and avoid worrying about additional moving parts in production. The basic components of the template are: - `examples`: An array of object examples to include in the final prompt. - `examplePrompt`: converts each example into 1 or more messages through its [`formatMessages`](https://v02.api.js.langchain.com/classes/langchain_core_prompts.FewShotChatMessagePromptTemplate.html#formatMessages) method. A common example would be to convert each example into one human message and one AI message response, or a human message followed by a function call message. Below is a simple demonstration. First, define the examples you’d like to include: import { ChatPromptTemplate, FewShotChatMessagePromptTemplate,} from "@langchain/core/prompts";const examples = [ { input: "2+2", output: "4" }, { input: "2+3", output: "5" },]; Next, assemble them into the few-shot prompt template. // This is a prompt template used to format each individual example.const examplePrompt = ChatPromptTemplate.fromMessages([ ["human", "{input}"], ["ai", "{output}"],]);const fewShotPrompt = new FewShotChatMessagePromptTemplate({ examplePrompt, examples, inputVariables: [], // no input variables});const result = await fewShotPrompt.invoke({});console.log(result.toChatMessages()); [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "2+2", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "2+2", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "4", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "4", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "2+3", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "2+3", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "5", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "5", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }] Finally, we assemble the final prompt as shown below, passing `fewShotPrompt` directly into the `fromMessages` factory method, and use it with a model: const finalPrompt = ChatPromptTemplate.fromMessages([ ["system", "You are a wondrous wizard of math."], fewShotPrompt, ["human", "{input}"],]); ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); const chain = finalPrompt.pipe(model);await chain.invoke({ input: "What's the square of a triangle?" }); AIMessage { lc_serializable: true, lc_kwargs: { content: "A triangle does not have a square. The square of a number is the result of multiplying the number by"... 8 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "A triangle does not have a square. The square of a number is the result of multiplying the number by"... 8 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 23, promptTokens: 52, totalTokens: 75 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} Dynamic few-shot prompting[​](#dynamic-few-shot-prompting "Direct link to Dynamic few-shot prompting") ------------------------------------------------------------------------------------------------------ Sometimes you may want to select only a few examples from your overall set to show based on the input. For this, you can replace the `examples` passed into `FewShotChatMessagePromptTemplate` with an `exampleSelector`. The other components remain the same as above! Our dynamic few-shot prompt template would look like: * `exampleSelector`: responsible for selecting few-shot examples (and the order in which they are returned) for a given input. These implement the [BaseExampleSelector](https://v02.api.js.langchain.com/classes/langchain_core_example_selectors.BaseExampleSelector.html) interface. A common example is the vectorstore-backed [SemanticSimilarityExampleSelector](https://v02.api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html) * `examplePrompt`: convert each example into 1 or more messages through its [`formatMessages`](https://v02.api.js.langchain.com/classes/langchain_core_prompts.FewShotChatMessagePromptTemplate.html#formatMessages) method. A common example would be to convert each example into one human message and one AI message response, or a human message followed by a function call message. These once again can be composed with other messages and chat templates to assemble your final prompt. Let’s walk through an example with the `SemanticSimilarityExampleSelector`. Since this implementation uses a vectorstore to select examples based on semantic similarity, we will want to first populate the store. Since the basic idea here is that we want to search for and return examples most similar to the text input, we embed the `values` of our prompt examples rather than considering the keys: import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings } from "@langchain/openai";const examples = [ { input: "2+2", output: "4" }, { input: "2+3", output: "5" }, { input: "2+4", output: "6" }, { input: "What did the cow say to the moon?", output: "nothing at all" }, { input: "Write me a poem about the moon", output: "One for the moon, and one for me, who are we to talk about the moon?", },];const toVectorize = examples.map( (example) => `${example.input} ${example.output}`);const embeddings = new OpenAIEmbeddings();const vectorStore = await MemoryVectorStore.fromTexts( toVectorize, examples, embeddings); ### Create the `exampleSelector`[​](#create-the-exampleselector "Direct link to create-the-exampleselector") With a vectorstore created, we can create the `exampleSelector`. Here we will call it in isolation, and set `k` on it to only fetch the two example closest to the input. const exampleSelector = new SemanticSimilarityExampleSelector({ vectorStore, k: 2,});// The prompt template will load examples by passing the input do the `select_examples` methodawait exampleSelector.selectExamples({ input: "horse" }); [ { input: "What did the cow say to the moon?", output: "nothing at all" }, { input: "2+4", output: "6" }] ### Create prompt template[​](#create-prompt-template "Direct link to Create prompt template") We now assemble the prompt template, using the `exampleSelector` created above. import { ChatPromptTemplate, FewShotChatMessagePromptTemplate,} from "@langchain/core/prompts";// Define the few-shot prompt.const fewShotPrompt = new FewShotChatMessagePromptTemplate({ // The input variables select the values to pass to the example_selector inputVariables: ["input"], exampleSelector, // Define how ech example will be formatted. // In this case, each example will become 2 messages: // 1 human, and 1 AI examplePrompt: ChatPromptTemplate.fromMessages([ ["human", "{input}"], ["ai", "{output}"], ]),});const results = await fewShotPrompt.invoke({ input: "What's 3+3?" });console.log(results.toChatMessages()); [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "2+3", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "2+3", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "5", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "5", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "2+2", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "2+2", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "4", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "4", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }] And we can pass this few-shot chat message prompt template into another chat prompt template: const finalPrompt = ChatPromptTemplate.fromMessages([ ["system", "You are a wondrous wizard of math."], fewShotPrompt, ["human", "{input}"],]);const result = await fewShotPrompt.invoke({ input: "What's 3+3?" });console.log(result); ChatPromptValue { lc_serializable: true, lc_kwargs: { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "2+3", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "2+3", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "5", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "5", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "2+2", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "2+2", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "4", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "4", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] } ] }, lc_namespace: [ "langchain_core", "prompt_values" ], messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "2+3", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "2+3", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "5", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "5", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "2+2", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "2+2", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "4", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "4", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] } ]} ### Use with an chat model[​](#use-with-an-chat-model "Direct link to Use with an chat model") Finally, you can connect your model to the few-shot prompt. ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); const chain = finalPrompt.pipe(model);await chain.invoke({ input: "What's 3+3?" }); AIMessage { lc_serializable: true, lc_kwargs: { content: "6", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "6", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 1, promptTokens: 51, totalTokens: 52 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to add few-shot examples to your chat prompts. Next, check out the other how-to guides on prompt templates in this section, the related how-to guide on [few shotting with text completion models](/v0.2/docs/how_to/few_shot_examples), or the other [example selector how-to guides](/v0.2/docs/how_to/example_selectors/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to embed text data ](/v0.2/docs/how_to/embed_text)[ Next How to cache model responses ](/v0.2/docs/how_to/llm_caching) * [Fixed Examples](#fixed-examples) * [Dynamic few-shot prompting](#dynamic-few-shot-prompting) * [Create the `exampleSelector`](#create-the-exampleselector) * [Create prompt template](#create-prompt-template) * [Use with an chat model](#use-with-an-chat-model) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.1/docs/get_started/introduction/
* [](/v0.1/) * [Get started](/v0.1/docs/get_started/) * Introduction On this page Introduction ============ **LangChain** is a framework for developing applications powered by language models. It enables applications that: * **Are context-aware**: connect a language model to sources of context (prompt instructions, few shot examples, content to ground its response in, etc.) * **Reason**: rely on a language model to reason (about how to answer based on provided context, what actions to take, etc.) This framework consists of several parts. * **LangChain Libraries**: The Python and JavaScript libraries. Contains interfaces and integrations for a myriad of components, a basic run time for combining these components into chains and agents, and off-the-shelf implementations of chains and agents. * **[LangChain Templates](https://python.langchain.com/docs/templates)**: A collection of easily deployable reference architectures for a wide variety of tasks. (_Python only_) * **[LangServe](https://python.langchain.com/docs/langserve)**: A library for deploying LangChain chains as a REST API. (_Python only_) * **[LangSmith](https://smith.langchain.com/)**: A developer platform that lets you debug, test, evaluate, and monitor chains built on any LLM framework and seamlessly integrates with LangChain. ![LangChain Diagram](/v0.1/assets/images/langchain_stack_feb_2024-101939844004a99c1b676723fc0ee5e9.webp) Together, these products simplify the entire application lifecycle: * **Develop**: Write your applications in LangChain/LangChain.js. Hit the ground running using Templates for reference. * **Productionize**: Use LangSmith to inspect, test and monitor your chains, so that you can constantly improve and deploy with confidence. * **Deploy**: Turn any chain into an API with LangServe. LangChain Libraries[​](#langchain-libraries "Direct link to LangChain Libraries") --------------------------------------------------------------------------------- The main value props of the LangChain packages are: 1. **Components**: composable tools and integrations for working with language models. Components are modular and easy-to-use, whether you are using the rest of the LangChain framework or not 2. **Off-the-shelf chains**: built-in assemblages of components for accomplishing higher-level tasks Off-the-shelf chains make it easy to get started. Components make it easy to customize existing chains and build new ones. Get started[​](#get-started "Direct link to Get started") --------------------------------------------------------- [Here's](/v0.1/docs/get_started/installation/) how to install LangChain, set up your environment, and start building. We recommend following our [Quickstart](/v0.1/docs/get_started/quickstart/) guide to familiarize yourself with the framework by building your first LangChain application. Read up on our [Security](/v0.1/docs/security/) best practices to make sure you're developing safely with LangChain. note These docs focus on the JS/TS LangChain library. [Head here](https://python.langchain.com) for docs on the Python LangChain library. LangChain Expression Language (LCEL)[​](#langchain-expression-language-lcel "Direct link to LangChain Expression Language (LCEL)") ---------------------------------------------------------------------------------------------------------------------------------- LCEL is a declarative way to compose chains. LCEL was designed from day 1 to support putting prototypes in production, with no code changes, from the simplest “prompt + LLM” chain to the most complex chains. * **[Overview](/v0.1/docs/expression_language/)**: LCEL and its benefits * **[Interface](/v0.1/docs/expression_language/interface/)**: The standard interface for LCEL objects * **[How-to](/v0.1/docs/expression_language/how_to/routing/)**: Key features of LCEL * **[Cookbook](/v0.1/docs/expression_language/cookbook/)**: Example code for accomplishing common tasks Modules[​](#modules "Direct link to Modules") --------------------------------------------- LangChain provides standard, extendable interfaces and integrations for the following modules: #### [Model I/O](/v0.1/docs/modules/model_io/)[​](#model-io "Direct link to model-io") Interface with language models #### [Retrieval](/v0.1/docs/modules/data_connection/)[​](#retrieval "Direct link to retrieval") Interface with application-specific data #### [Agents](/v0.1/docs/modules/agents/)[​](#agents "Direct link to agents") Let models choose which tools to use given high-level directives Examples, ecosystem, and resources[​](#examples-ecosystem-and-resources "Direct link to Examples, ecosystem, and resources") ---------------------------------------------------------------------------------------------------------------------------- ### [Use cases](/v0.1/docs/use_cases/)[​](#use-cases "Direct link to use-cases") Walkthroughs and techniques for common end-to-end use cases, like: * [Document question answering](/v0.1/docs/use_cases/question_answering/) * [RAG](/v0.1/docs/use_cases/question_answering/) * [Agents](/v0.1/docs/use_cases/autonomous_agents/) * and much more... ### [Integrations](/v0.1/docs/integrations/platforms/)[​](#integrations "Direct link to integrations") LangChain is part of a rich ecosystem of tools that integrate with our framework and build on top of it. Check out our growing list of [integrations](/v0.1/docs/integrations/platforms/). ### [API reference](https://api.js.langchain.com)[​](#api-reference "Direct link to api-reference") Head to the reference section for full documentation of all classes and methods in the LangChain and LangChain Experimental packages. ### [Developer's guide](/v0.1/docs/contributing/)[​](#developers-guide "Direct link to developers-guide") Check out the developer's guide for guidelines on contributing and help getting your dev environment set up. ### [Community](/v0.1/docs/community/)[​](#community "Direct link to community") Head to the [Community navigator](/v0.1/docs/community/) to find places to ask questions, share feedback, meet other developers, and dream about the future of LLM's. * * * #### Help us out by providing feedback on this documentation page: [ Previous Get started ](/v0.1/docs/get_started/)[ Next Installation ](/v0.1/docs/get_started/installation/) * [LangChain Libraries](#langchain-libraries) * [Get started](#get-started) * [LangChain Expression Language (LCEL)](#langchain-expression-language-lcel) * [Modules](#modules) * [Examples, ecosystem, and resources](#examples-ecosystem-and-resources) * [Use cases](#use-cases) * [Integrations](#integrations) * [API reference](#api-reference) * [Developer's guide](#developers-guide) * [Community](#community)
null
https://js.langchain.com/v0.2/
!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())
null
https://js.langchain.com/v0.2/docs/how_to/merge_message_runs
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to merge consecutive messages of the same type On this page How to merge consecutive messages of the same type ================================================== The `mergeMessageRuns` function is available in `@langchain/core` version `0.2.8` and above. Certain models do not support passing in consecutive messages of the same type (a.k.a. “runs” of the same message type). The `mergeMessageRuns` utility makes it easy to merge consecutive messages of the same type. Basic usage[​](#basic-usage "Direct link to Basic usage") --------------------------------------------------------- import { HumanMessage, SystemMessage, AIMessage, mergeMessageRuns,} from "@langchain/core/messages";const messages = [ new SystemMessage("you're a good assistant."), new SystemMessage("you always respond with a joke."), new HumanMessage({ content: [{ type: "text", text: "i wonder why it's called langchain" }], }), new HumanMessage("and who is harrison chasing anyways"), new AIMessage( 'Well, I guess they thought "WordRope" and "SentenceString" just didn\'t have the same ring to it!' ), new AIMessage( "Why, he's probably chasing after the last cup of coffee in the office!" ),];const merged = mergeMessageRuns(messages);console.log( merged .map((x) => JSON.stringify( { role: x._getType(), content: x.content, }, null, 2 ) ) .join("\n\n")); { "role": "system", "content": "you're a good assistant.\nyou always respond with a joke."}{ "role": "human", "content": [ { "type": "text", "text": "i wonder why it's called langchain" }, { "type": "text", "text": "and who is harrison chasing anyways" } ]}{ "role": "ai", "content": "Well, I guess they thought \"WordRope\" and \"SentenceString\" just didn't have the same ring to it!\nWhy, he's probably chasing after the last cup of coffee in the office!"} Notice that if the contents of one of the messages to merge is a list of content blocks then the merged message will have a list of content blocks. And if both messages to merge have string contents then those are concatenated with a newline character. Chaining[​](#chaining "Direct link to Chaining") ------------------------------------------------ `mergeMessageRuns` can be used in an imperatively (like above) or declaratively, making it easy to compose with other components in a chain: import { ChatAnthropic } from "@langchain/anthropic";import { mergeMessageRuns } from "@langchain/core/messages";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0,});// Notice we don't pass in messages. This creates// a RunnableLambda that takes messages as inputconst merger = mergeMessageRuns();const chain = merger.pipe(llm);await chain.invoke(messages); AIMessage { lc_serializable: true, lc_kwargs: { content: [], additional_kwargs: { id: 'msg_01LsdS4bjQ3EznH7Tj4xujV1', type: 'message', role: 'assistant', model: 'claude-3-sonnet-20240229', stop_reason: 'end_turn', stop_sequence: null, usage: [Object] }, tool_calls: [], usage_metadata: { input_tokens: 84, output_tokens: 3, total_tokens: 87 }, invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ 'langchain_core', 'messages' ], content: [], name: undefined, additional_kwargs: { id: 'msg_01LsdS4bjQ3EznH7Tj4xujV1', type: 'message', role: 'assistant', model: 'claude-3-sonnet-20240229', stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 84, output_tokens: 3 } }, response_metadata: { id: 'msg_01LsdS4bjQ3EznH7Tj4xujV1', model: 'claude-3-sonnet-20240229', stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 84, output_tokens: 3 } }, id: undefined, tool_calls: [], invalid_tool_calls: [], usage_metadata: { input_tokens: 84, output_tokens: 3, total_tokens: 87 }} Looking at [the LangSmith trace](https://smith.langchain.com/public/48d256fb-fd7e-48a0-bdfd-217ab74ad01d/r) we can see that before the messages are passed to the model they are merged. Looking at just the merger, we can see that it’s a Runnable object that can be invoked like all Runnables: await merger.invoke(messages); [ SystemMessage { lc_serializable: true, lc_kwargs: { content: "you're a good assistant.\nyou always respond with a joke.", name: undefined, additional_kwargs: {}, response_metadata: {}, id: undefined }, lc_namespace: [ 'langchain_core', 'messages' ], content: "you're a good assistant.\nyou always respond with a joke.", name: undefined, additional_kwargs: {}, response_metadata: {}, id: undefined }, HumanMessage { lc_serializable: true, lc_kwargs: { content: [Array], name: undefined, additional_kwargs: {}, response_metadata: {}, id: undefined }, lc_namespace: [ 'langchain_core', 'messages' ], content: [ [Object], [Object] ], name: undefined, additional_kwargs: {}, response_metadata: {}, id: undefined }, AIMessage { lc_serializable: true, lc_kwargs: { content: `Well, I guess they thought "WordRope" and "SentenceString" just didn't have the same ring to it!\n` + "Why, he's probably chasing after the last cup of coffee in the office!", name: undefined, additional_kwargs: {}, response_metadata: {}, id: undefined, tool_calls: [], invalid_tool_calls: [], usage_metadata: undefined }, lc_namespace: [ 'langchain_core', 'messages' ], content: `Well, I guess they thought "WordRope" and "SentenceString" just didn't have the same ring to it!\n` + "Why, he's probably chasing after the last cup of coffee in the office!", name: undefined, additional_kwargs: {}, response_metadata: {}, id: undefined, tool_calls: [], invalid_tool_calls: [], usage_metadata: undefined }] API reference[​](#api-reference "Direct link to API reference") --------------------------------------------------------------- For a complete description of all arguments head to the [API reference](https://api.js.langchain.com/functions/langchain_core_messages.mergeMessageRuns.html). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to get log probabilities ](/v0.2/docs/how_to/logprobs)[ Next How to add message history ](/v0.2/docs/how_to/message_history) * [Basic usage](#basic-usage) * [Chaining](#chaining) * [API reference](#api-reference)
null
https://js.langchain.com/v0.2/docs/how_to/few_shot_examples
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use few shot examples On this page How to use few shot examples ============================ In this guide, we’ll learn how to create a simple prompt template that provides the model with example inputs and outputs when generating. Providing the LLM with a few such examples is called few-shotting, and is a simple yet powerful way to guide generation and in some cases drastically improve model performance. A few-shot prompt template can be constructed from either a set of examples, or from an [Example Selector](https://v02.api.js.langchain.com/classes/langchain_core_example_selectors.BaseExampleSelector.html) class responsible for choosing a subset of examples from the defined set. This guide will cover few-shotting with string prompt templates. For a guide on few-shotting with chat messages for chat models, see [here](/v0.2/docs/how_to/few_shot_examples_chat/). Prerequisites This guide assumes familiarity with the following concepts: * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) * [Example selectors](/v0.2/docs/concepts/#example-selectors) * [LLMs](/v0.2/docs/concepts/#llms) * [Vectorstores](/v0.2/docs/concepts/#vectorstores) Create a formatter for the few-shot examples[​](#create-a-formatter-for-the-few-shot-examples "Direct link to Create a formatter for the few-shot examples") ------------------------------------------------------------------------------------------------------------------------------------------------------------ Configure a formatter that will format the few-shot examples into a string. This formatter should be a `PromptTemplate` object. import { PromptTemplate } from "@langchain/core/prompts";const examplePrompt = PromptTemplate.fromTemplate( "Question: {question}\n{answer}"); Creating the example set[​](#creating-the-example-set "Direct link to Creating the example set") ------------------------------------------------------------------------------------------------ Next, we’ll create a list of few-shot examples. Each example should be a dictionary representing an example input to the formatter prompt we defined above. const examples = [ { question: "Who lived longer, Muhammad Ali or Alan Turing?", answer: ` Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate answer: Alan Turing was 41 years old when he died. So the final answer is: Muhammad Ali `, }, { question: "When was the founder of craigslist born?", answer: ` Are follow up questions needed here: Yes. Follow up: Who was the founder of craigslist? Intermediate answer: Craigslist was founded by Craig Newmark. Follow up: When was Craig Newmark born? Intermediate answer: Craig Newmark was born on December 6, 1952. So the final answer is: December 6, 1952 `, }, { question: "Who was the maternal grandfather of George Washington?", answer: ` Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball `, }, { question: "Are both the directors of Jaws and Casino Royale from the same country?", answer: ` Are follow up questions needed here: Yes. Follow up: Who is the director of Jaws? Intermediate Answer: The director of Jaws is Steven Spielberg. Follow up: Where is Steven Spielberg from? Intermediate Answer: The United States. Follow up: Who is the director of Casino Royale? Intermediate Answer: The director of Casino Royale is Martin Campbell. Follow up: Where is Martin Campbell from? Intermediate Answer: New Zealand. So the final answer is: No `, },]; ### Pass the examples and formatter to `FewShotPromptTemplate`[​](#pass-the-examples-and-formatter-to-fewshotprompttemplate "Direct link to pass-the-examples-and-formatter-to-fewshotprompttemplate") Finally, create a [`FewShotPromptTemplate`](https://v02.api.js.langchain.com/classes/langchain_core_prompts.FewShotPromptTemplate.html) object. This object takes in the few-shot examples and the formatter for the few-shot examples. When this `FewShotPromptTemplate` is formatted, it formats the passed examples using the `examplePrompt`, then and adds them to the final prompt before `suffix`: import { FewShotPromptTemplate } from "@langchain/core/prompts";const prompt = new FewShotPromptTemplate({ examples, examplePrompt, suffix: "Question: {input}", inputVariables: ["input"],});const formatted = await prompt.format({ input: "Who was the father of Mary Ball Washington?",});console.log(formatted.toString()); Question: Who lived longer, Muhammad Ali or Alan Turing? Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate answer: Alan Turing was 41 years old when he died. So the final answer is: Muhammad AliQuestion: When was the founder of craigslist born? Are follow up questions needed here: Yes. Follow up: Who was the founder of craigslist? Intermediate answer: Craigslist was founded by Craig Newmark. Follow up: When was Craig Newmark born? Intermediate answer: Craig Newmark was born on December 6, 1952. So the final answer is: December 6, 1952Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph BallQuestion: Are both the directors of Jaws and Casino Royale from the same country? Are follow up questions needed here: Yes. Follow up: Who is the director of Jaws? Intermediate Answer: The director of Jaws is Steven Spielberg. Follow up: Where is Steven Spielberg from? Intermediate Answer: The United States. Follow up: Who is the director of Casino Royale? Intermediate Answer: The director of Casino Royale is Martin Campbell. Follow up: Where is Martin Campbell from? Intermediate Answer: New Zealand. So the final answer is: NoQuestion: Who was the father of Mary Ball Washington? By providing the model with examples like this, we can guide the model to a better response. Using an example selector[​](#using-an-example-selector "Direct link to Using an example selector") --------------------------------------------------------------------------------------------------- We will reuse the example set and the formatter from the previous section. However, instead of feeding the examples directly into the `FewShotPromptTemplate` object, we will feed them into an implementation of `ExampleSelector` called [`SemanticSimilarityExampleSelector`](https://v02.api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html) instance. This class selects few-shot examples from the initial set based on their similarity to the input. It uses an embedding model to compute the similarity between the input and the few-shot examples, as well as a vector store to perform the nearest neighbor search. To show what it looks like, let’s initialize an instance and call it in isolation: Set your OpenAI API key for the embeddings model export OPENAI_API_KEY="..." import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings } from "@langchain/openai";const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( // This is the list of examples available to select from. examples, // This is the embedding class used to produce embeddings which are used to measure semantic similarity. new OpenAIEmbeddings(), // This is the VectorStore class that is used to store the embeddings and do a similarity search over. MemoryVectorStore, { // This is the number of examples to produce. k: 1, });// Select the most similar example to the input.const question = "Who was the father of Mary Ball Washington?";const selectedExamples = await exampleSelector.selectExamples({ question });console.log(`Examples most similar to the input: ${question}`);for (const example of selectedExamples) { console.log("\n"); console.log( Object.entries(example) .map(([k, v]) => `${k}: ${v}`) .join("\n") );} Examples most similar to the input: Who was the father of Mary Ball Washington?question: Who was the maternal grandfather of George Washington?answer: Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball Now, let’s create a `FewShotPromptTemplate` object. This object takes in the example selector and the formatter prompt for the few-shot examples. const prompt = new FewShotPromptTemplate({ exampleSelector, examplePrompt, suffix: "Question: {input}", inputVariables: ["input"],});const formatted = await prompt.invoke({ input: "Who was the father of Mary Ball Washington?",});console.log(formatted.toString()); Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph BallQuestion: Who was the father of Mary Ball Washington? Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to add few-shot examples to your prompts. Next, check out the other how-to guides on prompt templates in this section, the related how-to guide on [few shotting with chat models](/v0.2/docs/how_to/few_shot_examples_chat), or the other [example selector how-to guides](/v0.2/docs/how_to/example_selectors/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to create a custom LLM class ](/v0.2/docs/how_to/custom_llm)[ Next How to use output parsers to parse an LLM response into structured format ](/v0.2/docs/how_to/output_parser_structured) * [Create a formatter for the few-shot examples](#create-a-formatter-for-the-few-shot-examples) * [Creating the example set](#creating-the-example-set) * [Pass the examples and formatter to `FewShotPromptTemplate`](#pass-the-examples-and-formatter-to-fewshotprompttemplate) * [Using an example selector](#using-an-example-selector) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/structured_output
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to return structured data from a model On this page How to return structured data from a model ========================================== It is often useful to have a model return output that matches some specific schema. One common use-case is extracting data from arbitrary text to insert into a traditional database or use with some other downstrem system. This guide will show you a few different strategies you can use to do this. Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) The `.withStructuredOutput()` method[​](#the-.withstructuredoutput-method "Direct link to the-.withstructuredoutput-method") ---------------------------------------------------------------------------------------------------------------------------- There are several strategies that models can use under the hood. For some of the most popular model providers, including [Anthropic](/v0.2/docs/integrations/platforms/anthropic/), [Google VertexAI](/v0.2/docs/integrations/platforms/google/), [Mistral](/v0.2/docs/integrations/chat/mistral/), and [OpenAI](/v0.2/docs/integrations/platforms/openai/) LangChain implements a common interface that abstracts away these strategies called `.withStructuredOutput`. By invoking this method (and passing in [JSON schema](https://json-schema.org/) or a [Zod schema](https://zod.dev/)) the model will add whatever model parameters + output parsers are necessary to get back structured output matching the requested schema. If the model supports more than one way to do this (e.g., function calling vs JSON mode) - you can configure which method to use by passing into that method. Let’s look at some examples of this in action! We’ll use Zod to create a simple response schema. ### Pick your chat model: * OpenAI * Anthropic * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { z } from "zod";const joke = z.object({ setup: z.string().describe("The setup of the joke"), punchline: z.string().describe("The punchline to the joke"), rating: z.number().optional().describe("How funny the joke is, from 1 to 10"),});const structuredLlm = model.withStructuredOutput(joke);await structuredLlm.invoke("Tell me a joke about cats"); { setup: "Why don't cats play poker in the wild?", punchline: "Too many cheetahs.", rating: 7} One key point is that though we set our Zod schema as a variable named `joke`, Zod is not able to access that variable name, and therefore cannot pass it to the model. Though it is not required, we can pass a name for our schema in order to give the model additional context as to what our schema represents, improving performance: const structuredLlm = model.withStructuredOutput(joke, { name: "joke" });await structuredLlm.invoke("Tell me a joke about cats"); { setup: "Why don't cats play poker in the wild?", punchline: "Too many cheetahs!", rating: 7} The result is a JSON object. We can also pass in an OpenAI-style JSON schema dict if you prefer not to use Zod. This object should contain three properties: * `name`: The name of the schema to output. * `description`: A high level description of the schema to output. * `parameters`: The nested details of the schema you want to extract, formatted as a [JSON schema](https://json-schema.org/) dict. In this case, the response is also a dict: const structuredLlm = model.withStructuredOutput({ name: "joke", description: "Joke to tell user.", parameters: { title: "Joke", type: "object", properties: { setup: { type: "string", description: "The setup for the joke" }, punchline: { type: "string", description: "The joke's punchline" }, }, required: ["setup", "punchline"], },});await structuredLlm.invoke("Tell me a joke about cats"); { setup: "Why was the cat sitting on the computer?", punchline: "Because it wanted to keep an eye on the mouse!"} If you are using JSON Schema, you can take advantage of other more complex schema descriptions to create a similar effect. You can also use tool calling directly to allow the model to choose between options, if your chosen model supports it. This involves a bit more parsing and setup. See [this how-to guide](/v0.2/docs/how_to/tool_calling/) for more details. ### Specifying the output method (Advanced)[​](#specifying-the-output-method-advanced "Direct link to Specifying the output method (Advanced)") For models that support more than one means of outputting data, you can specify the preferred one like this: const structuredLlm = model.withStructuredOutput(joke, { method: "json_mode", name: "joke",});await structuredLlm.invoke( "Tell me a joke about cats, respond in JSON with `setup` and `punchline` keys"); { setup: "Why don't cats play poker in the jungle?", punchline: "Too many cheetahs!"} In the above example, we use OpenAI’s alternate JSON mode capability along with a more specific prompt. For specifics about the model you choose, peruse its entry in the [API reference pages](https://v02.api.js.langchain.com/). Prompting techniques[​](#prompting-techniques "Direct link to Prompting techniques") ------------------------------------------------------------------------------------ You can also prompt models to outputting information in a given format. This approach relies on designing good prompts and then parsing the output of the models. This is the only option for models that don’t support `.with_structured_output()` or other built-in approaches. ### Using `JsonOutputParser`[​](#using-jsonoutputparser "Direct link to using-jsonoutputparser") The following example uses the built-in [`JsonOutputParser`](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.JsonOutputParser.html) to parse the output of a chat model prompted to match a the given JSON schema. Note that we are adding `format_instructions` directly to the prompt from a method on the parser: import { JsonOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";type Person = { name: string; height_in_meters: number;};type People = { people: Person[];};const formatInstructions = `Respond only in valid JSON. The JSON object you return should match the following schema:{{ people: [{{ name: "string", height_in_meters: "number" }}] }}Where people is an array of objects, each with a name and height_in_meters field.`;// Set up a parserconst parser = new JsonOutputParser<People>();// Promptconst prompt = await ChatPromptTemplate.fromMessages([ [ "system", "Answer the user query. Wrap the output in `json` tags\n{format_instructions}", ], ["human", "{query}"],]).partial({ format_instructions: formatInstructions,}); Let’s take a look at what information is sent to the model: const query = "Anna is 23 years old and she is 6 feet tall";console.log((await prompt.format({ query })).toString()); System: Answer the user query. Wrap the output in `json` tagsRespond only in valid JSON. The JSON object you return should match the following schema:{{ people: [{{ name: "string", height_in_meters: "number" }}] }}Where people is an array of objects, each with a name and height_in_meters field.Human: Anna is 23 years old and she is 6 feet tall And now let’s invoke it: const chain = prompt.pipe(model).pipe(parser);await chain.invoke({ query }); { people: [ { name: "Anna", height_in_meters: 1.83 } ] } For a deeper dive into using output parsers with prompting techniques for structured output, see [this guide](/v0.2/docs/how_to/output_parser_structured). ### Custom Parsing[​](#custom-parsing "Direct link to Custom Parsing") You can also create a custom prompt and parser with [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language), using a plain function to parse the output from the model: import { AIMessage } from "@langchain/core/messages";import { ChatPromptTemplate } from "@langchain/core/prompts";type Person = { name: string; height_in_meters: number;};type People = { people: Person[];};const schema = `{{ people: [{{ name: "string", height_in_meters: "number" }}] }}`;// Promptconst prompt = await ChatPromptTemplate.fromMessages([ [ "system", `Answer the user query. Output your answer as JSON thatmatches the given schema: \`\`\`json\n{schema}\n\`\`\`.Make sure to wrap the answer in \`\`\`json and \`\`\` tags`, ], ["human", "{query}"],]).partial({ schema,});/** * Custom extractor * * Extracts JSON content from a string where * JSON is embedded between ```json and ``` tags. */const extractJson = (output: AIMessage): Array<People> => { const text = output.content as string; // Define the regular expression pattern to match JSON blocks const pattern = /```json(.*?)```/gs; // Find all non-overlapping matches of the pattern in the string const matches = text.match(pattern); // Process each match, attempting to parse it as JSON try { return ( matches?.map((match) => { // Remove the markdown code block syntax to isolate the JSON string const jsonStr = match.replace(/```json|```/g, "").trim(); return JSON.parse(jsonStr); }) ?? [] ); } catch (error) { throw new Error(`Failed to parse: ${output}`); }}; Here is the prompt sent to the model: const query = "Anna is 23 years old and she is 6 feet tall";console.log((await prompt.format({ query })).toString()); System: Answer the user query. Output your answer as JSON thatmatches the given schema: ```json{{ people: [{{ name: "string", height_in_meters: "number" }}] }}```.Make sure to wrap the answer in ```json and ``` tagsHuman: Anna is 23 years old and she is 6 feet tall And here’s what it looks like when we invoke it: import { RunnableLambda } from "@langchain/core/runnables";const chain = prompt .pipe(model) .pipe(new RunnableLambda({ func: extractJson }));await chain.invoke({ query }); [ { people: [ { name: "Anna", height_in_meters: 1.83 } ] }] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ Now you’ve learned a few methods to make a model output structured data. To learn more, check out the other how-to guides in this section, or the conceptual guide on tool calling. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use output parsers to parse an LLM response into structured format ](/v0.2/docs/how_to/output_parser_structured)[ Next How to add ad-hoc tool calling capability to LLMs and Chat Models ](/v0.2/docs/how_to/tools_prompting) * [The `.withStructuredOutput()` method](#the-.withstructuredoutput-method) * [Specifying the output method (Advanced)](#specifying-the-output-method-advanced) * [Prompting techniques](#prompting-techniques) * [Using `JsonOutputParser`](#using-jsonoutputparser) * [Custom Parsing](#custom-parsing) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/integrations/platforms/
* [](/v0.2/) * Providers On this page Providers ========= LangChain integrates with many providers. Partner Packages[​](#partner-packages "Direct link to Partner Packages") ------------------------------------------------------------------------ These providers have standalone `@langchain/{provider}` packages for improved versioning, dependency management and testing. * [Anthropic](https://www.npmjs.com/package/@langchain/anthropic) * [Cloudflare](https://www.npmjs.com/package/@langchain/cloudflare) * [Cohere](https://www.npmjs.com/package/@langchain/cohere) * [Exa](https://www.npmjs.com/package/@langchain/exa) * [Google GenAI](https://www.npmjs.com/package/@langchain/google-genai) * [Google VertexAI](https://www.npmjs.com/package/@langchain/google-vertexai) * [Google VertexAI Web](https://www.npmjs.com/package/@langchain/google-vertexai-web) * [Groq](https://www.npmjs.com/package/@langchain/groq) * [MistralAI](https://www.npmjs.com/package/@langchain/mistralai) * [MongoDB](https://www.npmjs.com/package/@langchain/mongodb) * [Nomic](https://www.npmjs.com/package/@langchain/nomic) * [OpenAI](https://www.npmjs.com/package/@langchain/openai) * [Pinecone](https://www.npmjs.com/package/@langchain/pinecone) * [Qdrant](https://www.npmjs.com/package/@langchain/qdrant) * [Redis](https://www.npmjs.com/package/@langchain/redis) * [Weaviate](https://www.npmjs.com/package/@langchain/weaviate) * [Yandex](https://www.npmjs.com/package/@langchain/yandex) * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Next Providers ](/v0.2/docs/integrations/platforms/) * [Partner Packages](#partner-packages)
null
https://js.langchain.com/v0.2/docs/how_to/tools_prompting
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to add ad-hoc tool calling capability to LLMs and Chat Models On this page How to add ad-hoc tool calling capability to LLMs and Chat Models ================================================================= Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) * [Chaining runnables](/v0.2/docs/how_to/sequence/) * [Tool calling](/v0.2/docs/how_to/tool_calling/) In this guide we’ll build a Chain that does not rely on any special model APIs (like tool calling, which we showed in the [Quickstart](/v0.2/docs/how_to/tool_calling)) and instead just prompts the model directly to invoke tools. Setup[​](#setup "Direct link to Setup") --------------------------------------- We’ll need to install the following packages: * npm * yarn * pnpm npm i @langchain/core zod yarn add @langchain/core zod pnpm add @langchain/core zod #### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") # Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true Create a tool[​](#create-a-tool "Direct link to Create a tool") --------------------------------------------------------------- First, we need to create a tool to call. For this example, we will create a custom tool from a function. For more information on all details related to creating custom tools, please see [this guide](/v0.2/docs/how_to/custom_tools). import { StructuredTool } from "@langchain/core/tools";import { z } from "zod";class Multiply extends StructuredTool { schema = z.object({ first_int: z.number(), second_int: z.number(), }); name = "multiply"; description = "Multiply two integers together."; async _call(input: z.infer<typeof this.schema>) { return (input.first_int * input.second_int).toString(); }}const multiply = new Multiply(); console.log(multiply.name);console.log(multiply.description); multiplyMultiply two integers together. await multiply.invoke({ first_int: 4, second_int: 5 }); 20 Creating our prompt[​](#creating-our-prompt "Direct link to Creating our prompt") --------------------------------------------------------------------------------- We’ll want to write a prompt that specifies the tools the model has access to, the arguments to those tools, and the desired output format of the model. In this case we’ll instruct it to output a JSON blob of the form `{"name": "...", "arguments": {...}}`. import { renderTextDescription } from "langchain/tools/render";const renderedTools = renderTextDescription([multiply]); import { ChatPromptTemplate } from "@langchain/core/prompts";const systemPrompt = `You are an assistant that has access to the following set of tools. Here are the names and descriptions for each tool:{rendered_tools}Given the user input, return the name and input of the tool to use. Return your response as a JSON blob with 'name' and 'arguments' keys.`;const prompt = ChatPromptTemplate.fromMessages([ ["system", systemPrompt], ["user", "{input}"],]); Adding an output parser[​](#adding-an-output-parser "Direct link to Adding an output parser") --------------------------------------------------------------------------------------------- We’ll use the `JsonOutputParser` for parsing our models output to JSON. ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { JsonOutputParser } from "@langchain/core/output_parsers";const chain = prompt.pipe(model).pipe(new JsonOutputParser());await chain.invoke({ input: "what's thirteen times 4", rendered_tools: renderedTools,}); { name: 'multiply', arguments: [ 13, 4 ] } Invoking the tool[​](#invoking-the-tool "Direct link to Invoking the tool") --------------------------------------------------------------------------- We can invoke the tool as part of the chain by passing along the model-generated “arguments” to it: import { RunnableLambda, RunnablePick } from "@langchain/core/runnables";const chain = prompt .pipe(model) .pipe(new JsonOutputParser()) .pipe(new RunnablePick("arguments")) .pipe( new RunnableLambda({ func: (input) => multiply.invoke({ first_int: input[0], second_int: input[1], }), }) );await chain.invoke({ input: "what's thirteen times 4", rendered_tools: renderedTools,}); 52 Choosing from multiple tools[​](#choosing-from-multiple-tools "Direct link to Choosing from multiple tools") ------------------------------------------------------------------------------------------------------------ Suppose we have multiple tools we want the chain to be able to choose from: class Add extends StructuredTool { schema = z.object({ first_int: z.number(), second_int: z.number(), }); name = "add"; description = "Add two integers together."; async _call(input: z.infer<typeof this.schema>) { return (input.first_int + input.second_int).toString(); }}const add = new Add();class Exponentiate extends StructuredTool { schema = z.object({ first_int: z.number(), second_int: z.number(), }); name = "exponentiate"; description = "Exponentiate the base to the exponent power."; async _call(input: z.infer<typeof this.schema>) { return Math.pow(input.first_int, input.second_int).toString(); }}const exponentiate = new Exponentiate(); With function calling, we can do this like so: If we want to run the model selected tool, we can do so using a function that returns the tool based on the model output. Specifically, our function will action return it’s own subchain that gets the “arguments” part of the model output and passes it to the chosen tool: import { StructuredToolInterface } from "@langchain/core/tools";const tools = [add, exponentiate, multiply];const toolChain = (modelOutput) => { const toolMap: Record<string, StructuredToolInterface> = Object.fromEntries( tools.map((tool) => [tool.name, tool]) ); const chosenTool = toolMap[modelOutput.name]; return new RunnablePick("arguments").pipe( new RunnableLambda({ func: (input) => chosenTool.invoke({ first_int: input[0], second_int: input[1], }), }) );};const toolChainRunnable = new RunnableLambda({ func: toolChain,});const renderedTools = renderTextDescription(tools);const systemPrompt = `You are an assistant that has access to the following set of tools. Here are the names and descriptions for each tool:{rendered_tools}Given the user input, return the name and input of the tool to use. Return your response as a JSON blob with 'name' and 'arguments' keys.`;const prompt = ChatPromptTemplate.fromMessages([ ["system", systemPrompt], ["user", "{input}"],]);const chain = prompt .pipe(model) .pipe(new JsonOutputParser()) .pipe(toolChainRunnable);await chain.invoke({ input: "what's 3 plus 1132", rendered_tools: renderedTools,}); 1135 Returning tool inputs[​](#returning-tool-inputs "Direct link to Returning tool inputs") --------------------------------------------------------------------------------------- It can be helpful to return not only tool outputs but also tool inputs. We can easily do this with LCEL by `RunnablePassthrough.assign`\-ing the tool output. This will take whatever the input is to the RunnablePassrthrough components (assumed to be a dictionary) and add a key to it while still passing through everything that’s currently in the input: import { RunnablePassthrough } from "@langchain/core/runnables";const chain = prompt .pipe(model) .pipe(new JsonOutputParser()) .pipe(RunnablePassthrough.assign({ output: toolChainRunnable }));await chain.invoke({ input: "what's 3 plus 1132", rendered_tools: renderedTools,}); { name: 'add', arguments: [ 3, 1132 ], output: '1135' } What’s next?[​](#whats-next "Direct link to What’s next?") ---------------------------------------------------------- This how-to guide shows the “happy path” when the model correctly outputs all the required tool information. In reality, if you’re using more complex tools, you will start encountering errors from the model, especially for models that have not been fine tuned for tool calling and for less capable models. You will need to be prepared to add strategies to improve the output from the model; e.g., * Provide few shot examples. * Add error handling (e.g., catch the exception and feed it back to the LLM to ask it to correct its previous output). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to return structured data from a model ](/v0.2/docs/how_to/structured_output)[ Next How to create a custom chat model class ](/v0.2/docs/how_to/custom_chat) * [Setup](#setup) * [Create a tool](#create-a-tool) * [Creating our prompt](#creating-our-prompt) * [Adding an output parser](#adding-an-output-parser) * [Invoking the tool](#invoking-the-tool) * [Choosing from multiple tools](#choosing-from-multiple-tools) * [Returning tool inputs](#returning-tool-inputs) * [What’s next?](#whats-next)
null
https://js.langchain.com/v0.2/docs/how_to/output_parser_structured
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use output parsers to parse an LLM response into structured format On this page How to use output parsers to parse an LLM response into structured format ========================================================================= Prerequisites This guide assumes familiarity with the following concepts: * [Output parsers](/v0.2/docs/concepts#output-parsers) * [Chat models](/v0.2/docs/concepts#chat-models) Language models output text. But there are times where you want to get more structured information than just text back. While some model providers support [built-in ways to return structured output](/v0.2/docs/how_to/structured_output), not all do. For these providers, you must use prompting to encourage the model to return structured data in the desired format. LangChain has [output parsers](/v0.2/docs/concepts#output-parsers) which can help parse model outputs into usable objects. We’ll go over a few examples below. Get started[​](#get-started "Direct link to Get started") --------------------------------------------------------- The primary type of output parser for working with structured data in model responses is the [`StructuredOutputParser`](https://api.js.langchain.com/classes/langchain_core_output_parsers.StructuredOutputParser.html). In the below example, we define a schema for the type of output we expect from the model using [`zod`](https://zod.dev). First, let’s see the default formatting instructions we’ll plug into the prompt: ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { z } from "zod";import { RunnableSequence } from "@langchain/core/runnables";import { StructuredOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";const zodSchema = z.object({ answer: z.string().describe("answer to the user's question"), source: z .string() .describe( "source used to answer the user's question, should be a website." ),});const parser = StructuredOutputParser.fromZodSchema(zodSchema);const chain = RunnableSequence.from([ ChatPromptTemplate.fromTemplate( "Answer the users question as best as possible.\n{format_instructions}\n{question}" ), model, parser,]);console.log(parser.getFormatInstructions()); You must format your output as a JSON value that adheres to a given "JSON Schema" instance."JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:```json{"type":"object","properties":{"answer":{"type":"string","description":"answer to the user's question"},"source":{"type":"string","description":"source used to answer the user's question, should be a website."}},"required":["answer","source"],"additionalProperties":false,"$schema":"http://json-schema.org/draft-07/schema#"}``` Next, let’s invoke the chain: const response = await chain.invoke({ question: "What is the capital of France?", format_instructions: parser.getFormatInstructions(),});console.log(response); { answer: "The capital of France is Paris.", source: "https://en.wikipedia.org/wiki/Paris"} Output parsers implement the [Runnable interface](/v0.2/docs/how_to/#langchain-expression-language-lcel), the basic building block of the [LangChain Expression Language (LCEL)](/v0.2/docs/how_to/#langchain-expression-language-lcel). This means they support `invoke`, `stream`, `batch`, `streamLog` calls. Validation[​](#validation "Direct link to Validation") ------------------------------------------------------ One feature of the `StructuredOutputParser` is that it supports stricter Zod validations. For example, if you pass a simulated model output that does not conform to the schema, we get a detailed type error: import { AIMessage } from "@langchain/core/messages";await parser.invoke(new AIMessage(`{"badfield": "foo"}`)); Error: Failed to parse. Text: "{"badfield": "foo"}". Error: [ { "code": "invalid_type", "expected": "string", "received": "undefined", "path": [ "answer" ], "message": "Required" }, { "code": "invalid_type", "expected": "string", "received": "undefined", "path": [ "source" ], "message": "Required" }] Compared to: await parser.invoke( new AIMessage(`{"answer": "Paris", "source": "I made it up"}`)); { answer: "Paris", source: "I made it up" } More advanced Zod validations are supported as well. To learn more, check out the [Zod documentation](https://zod.dev). Streaming[​](#streaming "Direct link to Streaming") --------------------------------------------------- While all parsers are runnables and support the streaming interface, only certain parsers can stream through partially parsed objects, since this is highly dependent on the output type. The `StructuredOutputParser` does not support partial streaming because it validates the output at each step. If you try to stream using a chain with this output parser, the chain will simply yield the fully parsed output: const stream = await chain.stream({ question: "What is the capital of France?", format_instructions: parser.getFormatInstructions(),});for await (const s of stream) { console.log(s);} { answer: "The capital of France is Paris.", source: "https://en.wikipedia.org/wiki/Paris"} The simpler [`JsonOutputParser`](https://api.js.langchain.com/classes/langchain_core_output_parsers.JsonOutputParser.html), however, supports streaming through partial outputs: import { JsonOutputParser } from "@langchain/core/output_parsers";const template = `Return a JSON object with a single key named "answer" that answers the following question: {question}.Do not wrap the JSON output in markdown blocks.`;const jsonPrompt = ChatPromptTemplate.fromTemplate(template);const jsonParser = new JsonOutputParser();const jsonChain = jsonPrompt.pipe(model).pipe(jsonParser);const stream = await jsonChain.stream({ question: "Who invented the microscope?",});for await (const s of stream) { console.log(s);} {}{ answer: "" }{ answer: "The" }{ answer: "The invention" }{ answer: "The invention of" }{ answer: "The invention of the" }{ answer: "The invention of the microscope" }{ answer: "The invention of the microscope is" }{ answer: "The invention of the microscope is attributed" }{ answer: "The invention of the microscope is attributed to" }{ answer: "The invention of the microscope is attributed to Hans" }{ answer: "The invention of the microscope is attributed to Hans L" }{ answer: "The invention of the microscope is attributed to Hans Lippers"}{ answer: "The invention of the microscope is attributed to Hans Lippershey"}{ answer: "The invention of the microscope is attributed to Hans Lippershey,"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zach"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Jans"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen,"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Anton"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 4 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 8 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 12 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 13 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 18 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 20 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 26 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 29 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 33 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 38 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 43 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 48 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 51 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 52 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 57 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 63 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 73 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 80 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 81 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 85 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 94 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 99 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 108 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 112 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 118 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 127 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 138 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 145 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 149 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 150 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 151 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 157 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 159 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 163 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 167 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 171 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 175 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 176 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 181 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 186 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 190 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 202 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 203 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 209 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 214 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 226 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 239 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 242 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 246 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 253 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 257 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 262 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 265 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 268 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 273 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 288 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 300 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 303 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 311 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 316 more characters}{ answer: "The invention of the microscope is attributed to Hans Lippershey, Zacharias Janssen, and Antonie van"... 317 more characters} Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve learned about using output parsers to parse structured outputs from prompted model outputs. Next, check out the [guide on tool calling](/v0.2/docs/how_to/tool_calling), a more built-in way of obtaining structured output that some model providers support, or read more about output parsers for other types of structured data like [XML](/v0.2/docs/how_to/output_parser_xml). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use few shot examples ](/v0.2/docs/how_to/few_shot_examples)[ Next How to return structured data from a model ](/v0.2/docs/how_to/structured_output) * [Get started](#get-started) * [Validation](#validation) * [Streaming](#streaming) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/migrate_agent
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to migrate from legacy LangChain agents to LangGraph On this page How to migrate from legacy LangChain agents to LangGraph ======================================================== Here we focus on how to move from legacy LangChain agents to LangGraph agents. LangChain agents (the [`AgentExecutor`](https://api.js.langchain.com/classes/langchain_agents.AgentExecutor.html) in particular) have multiple configuration parameters. In this notebook we will show how those parameters map to the LangGraph [react agent executor](https://langchain-ai.github.io/langgraphjs/reference/functions/prebuilt.createReactAgent.html). For more information on how to build agentic workflows in LangGraph, check out the [docs here](https://langchain-ai.github.io/langgraphjs/how-tos/). #### Prerequisites[​](#prerequisites "Direct link to Prerequisites") This how-to guide uses Anthropic’s `"claude-3-haiku-20240307"` as the LLM. If you are running this guide as a notebook, set your Anthropic API key to run. // process.env.ANTHROPIC_API_KEY = "sk-...";// Optional, add tracing in LangSmith// process.env.LANGCHAIN_API_KEY = "ls...";// process.env.LANGCHAIN_CALLBACKS_BACKGROUND = "true";// process.env.LANGCHAIN_TRACING_V2 = "true";// process.env.LANGCHAIN_PROJECT = "How to migrate: LangGraphJS"; Basic Usage[​](#basic-usage "Direct link to Basic Usage") --------------------------------------------------------- For basic creation and usage of a tool-calling ReAct-style agent, the functionality is the same. First, let’s define a model and tool(s), then we’ll use those to create an agent. The `tool` function is available in `@langchain/core` version 0.2.7 and above. If you are on an older version of core, you should use instantiate and use [`DynamicStructuredTool`](https://api.js.langchain.com/classes/langchain_core_tools.DynamicStructuredTool.html) instead. import { tool } from "@langchain/core/tools";import { z } from "zod";import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-haiku-20240307", temperature: 0,});const magicTool = tool( async ({ input }: { input: number }) => { return `${input + 2}`; }, { name: "magic_function", description: "Applies a magic function to an input.", schema: z.object({ input: z.number(), }), });const tools = [magicTool];const query = "what is the value of magic_function(3)?"; For the LangChain [`AgentExecutor`](https://api.js.langchain.com/classes/langchain_agents.AgentExecutor.html), we define a prompt with a placeholder for the agent’s scratchpad. The agent can be invoked as follows: import { ChatPromptTemplate } from "@langchain/core/prompts";import { createToolCallingAgent } from "langchain/agents";import { AgentExecutor } from "langchain/agents";const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant"], ["placeholder", "{chat_history}"], ["human", "{input}"], ["placeholder", "{agent_scratchpad}"],]);const agent = createToolCallingAgent({ llm, tools, prompt });const agentExecutor = new AgentExecutor({ agent, tools });await agentExecutor.invoke({ input: query }); { input: "what is the value of magic_function(3)?", output: "The value of magic_function(3) is 5."} LangGraph’s off-the-shelf [react agent executor](https://langchain-ai.github.io/langgraphjs/reference/functions/prebuilt.createReactAgent.html) manages a state that is defined by a list of messages. In a similar way to the `AgentExecutor`, it will continue to process the list until there are no tool calls in the agent’s output. To kick it off, we input a list of messages. The output will contain the entire state of the graph - in this case, the conversation history and messages representing intermediate tool calls: import { createReactAgent } from "@langchain/langgraph/prebuilt";import { HumanMessage } from "@langchain/core/messages";const app = createReactAgent({ llm, tools });let agentOutput = await app.invoke({ messages: [new HumanMessage(query)],});console.log(agentOutput); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "what is the value of magic_function(3)?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "what is the value of magic_function(3)?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: [ [Object] ], additional_kwargs: { id: "msg_015jSku8UgrtRQ2kNQuTsvi1", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: [Object] }, tool_calls: [ [Object] ], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: [ { type: "tool_use", id: "toolu_01WCezi2ywMPnRm1xbrXYPoB", name: "magic_function", input: [Object] } ], name: undefined, additional_kwargs: { id: "msg_015jSku8UgrtRQ2kNQuTsvi1", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: { input_tokens: 365, output_tokens: 53 } }, response_metadata: { id: "msg_015jSku8UgrtRQ2kNQuTsvi1", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: { input_tokens: 365, output_tokens: 53 } }, tool_calls: [ { name: "magic_function", args: [Object], id: "toolu_01WCezi2ywMPnRm1xbrXYPoB" } ], invalid_tool_calls: [] }, ToolMessage { lc_serializable: true, lc_kwargs: { name: "magic_function", content: "5", tool_call_id: "toolu_01WCezi2ywMPnRm1xbrXYPoB", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "5", name: "magic_function", additional_kwargs: {}, response_metadata: {}, tool_call_id: "toolu_01WCezi2ywMPnRm1xbrXYPoB" }, AIMessage { lc_serializable: true, lc_kwargs: { content: "The value of magic_function(3) is 5.", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_01FbyPvpxtczu2Cmd4vKcPQm", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: [Object] }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "The value of magic_function(3) is 5.", name: undefined, additional_kwargs: { id: "msg_01FbyPvpxtczu2Cmd4vKcPQm", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 431, output_tokens: 17 } }, response_metadata: { id: "msg_01FbyPvpxtczu2Cmd4vKcPQm", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 431, output_tokens: 17 } }, tool_calls: [], invalid_tool_calls: [] } ]} const messageHistory = agentOutput.messages;const newQuery = "Pardon?";agentOutput = await app.invoke({ messages: [...messageHistory, new HumanMessage(newQuery)],}); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "what is the value of magic_function(3)?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "what is the value of magic_function(3)?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: [ [Object] ], additional_kwargs: { id: "msg_015jSku8UgrtRQ2kNQuTsvi1", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: [Object] }, tool_calls: [ [Object] ], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: [ { type: "tool_use", id: "toolu_01WCezi2ywMPnRm1xbrXYPoB", name: "magic_function", input: [Object] } ], name: undefined, additional_kwargs: { id: "msg_015jSku8UgrtRQ2kNQuTsvi1", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: { input_tokens: 365, output_tokens: 53 } }, response_metadata: { id: "msg_015jSku8UgrtRQ2kNQuTsvi1", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: { input_tokens: 365, output_tokens: 53 } }, tool_calls: [ { name: "magic_function", args: [Object], id: "toolu_01WCezi2ywMPnRm1xbrXYPoB" } ], invalid_tool_calls: [] }, ToolMessage { lc_serializable: true, lc_kwargs: { name: "magic_function", content: "5", tool_call_id: "toolu_01WCezi2ywMPnRm1xbrXYPoB", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "5", name: "magic_function", additional_kwargs: {}, response_metadata: {}, tool_call_id: "toolu_01WCezi2ywMPnRm1xbrXYPoB" }, AIMessage { lc_serializable: true, lc_kwargs: { content: "The value of magic_function(3) is 5.", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_01FbyPvpxtczu2Cmd4vKcPQm", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: [Object] }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "The value of magic_function(3) is 5.", name: undefined, additional_kwargs: { id: "msg_01FbyPvpxtczu2Cmd4vKcPQm", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 431, output_tokens: 17 } }, response_metadata: { id: "msg_01FbyPvpxtczu2Cmd4vKcPQm", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 431, output_tokens: 17 } }, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "Pardon?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Pardon?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "I apologize for the confusion. Let me explain the steps I took to arrive at the result:\n" + "\n" + "1. You aske"... 52 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_012yLSnnf1c64NWKS9K58hcN", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: [Object] }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "I apologize for the confusion. Let me explain the steps I took to arrive at the result:\n" + "\n" + "1. You aske"... 52 more characters, name: undefined, additional_kwargs: { id: "msg_012yLSnnf1c64NWKS9K58hcN", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 455, output_tokens: 137 } }, response_metadata: { id: "msg_012yLSnnf1c64NWKS9K58hcN", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 455, output_tokens: 137 } }, tool_calls: [], invalid_tool_calls: [] } ]} Prompt Templates[​](#prompt-templates "Direct link to Prompt Templates") ------------------------------------------------------------------------ With legacy LangChain agents you have to pass in a prompt template. You can use this to control the agent. With LangGraph [react agent executor](https://langchain-ai.github.io/langgraphjs/reference/functions/prebuilt.createReactAgent.html), by default there is no prompt. You can achieve similar control over the agent in a few ways: 1. Pass in a system message as input 2. Initialize the agent with a system message 3. Initialize the agent with a function to transform messages before passing to the model. Let’s take a look at all of these below. We will pass in custom instructions to get the agent to respond in Spanish. First up, using LangChain’s `AgentExecutor`: const spanishPrompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant. Respond only in Spanish."], ["placeholder", "{chat_history}"], ["human", "{input}"], ["placeholder", "{agent_scratchpad}"],]);const spanishAgent = createToolCallingAgent({ llm, tools, prompt: spanishPrompt,});const spanishAgentExecutor = new AgentExecutor({ agent: spanishAgent, tools,});await spanishAgentExecutor.invoke({ input: query }); { input: "what is the value of magic_function(3)?", output: "El valor de magic_function(3) es 5."} Now, let’s pass a custom system message to [react agent executor](https://langchain-ai.github.io/langgraphjs/reference/functions/prebuilt.createReactAgent.html). This can either be a string or a LangChain `SystemMessage`. import { SystemMessage } from "@langchain/core/messages";const systemMessage = "You are a helpful assistant. Respond only in Spanish.";// This could also be a SystemMessage object// const systemMessage = new SystemMessage("You are a helpful assistant. Respond only in Spanish.");const appWithSystemMessage = createReactAgent({ llm, tools, messageModifier: systemMessage,});agentOutput = await appWithSystemMessage.invoke({ messages: [new HumanMessage(query)],});agentOutput.messages[agentOutput.messages.length - 1]; AIMessage { lc_serializable: true, lc_kwargs: { content: "El valor de magic_function(3) es 5.", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_01P5VUYbBZoeMaReqBgqFJZa", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 444, output_tokens: 17 } }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "El valor de magic_function(3) es 5.", name: undefined, additional_kwargs: { id: "msg_01P5VUYbBZoeMaReqBgqFJZa", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 444, output_tokens: 17 } }, response_metadata: { id: "msg_01P5VUYbBZoeMaReqBgqFJZa", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 444, output_tokens: 17 } }, tool_calls: [], invalid_tool_calls: []} We can also pass in an arbitrary function. This function should take in a list of messages and output a list of messages. We can do all types of arbitrary formatting of messages here. In this cases, let’s just add a `SystemMessage` to the start of the list of messages. import { BaseMessage, SystemMessage } from "@langchain/core/messages";const modifyMessages = (messages: BaseMessage[]) => { return [ new SystemMessage("You are a helpful assistant. Respond only in Spanish."), ...messages, new HumanMessage("Also say 'Pandemonium!' after the answer."), ];};const appWithMessagesModifier = createReactAgent({ llm, tools, messageModifier: modifyMessages,});agentOutput = await appWithMessagesModifier.invoke({ messages: [new HumanMessage(query)],});console.log({ input: query, output: agentOutput.messages[agentOutput.messages.length - 1].content,}); { input: "what is the value of magic_function(3)?", output: "5. ¡Pandemonium!"} Memory[​](#memory "Direct link to Memory") ------------------------------------------ With LangChain’s [`AgentExecutor`](https://api.js.langchain.com/classes/langchain_agents.AgentExecutor.html), you could add chat memory classes so it can engage in a multi-turn conversation. import { ChatMessageHistory } from "@langchain/community/stores/message/in_memory";import { RunnableWithMessageHistory } from "@langchain/core/runnables";const memory = new ChatMessageHistory();const agentExecutorWithMemory = new RunnableWithMessageHistory({ runnable: agentExecutor, getMessageHistory: () => memory, inputMessagesKey: "input", historyMessagesKey: "chat_history",});const config = { configurable: { sessionId: "test-session" } };agentOutput = await agentExecutorWithMemory.invoke( { input: "Hi, I'm polly! What's the output of magic_function of 3?" }, config);console.log(agentOutput.output);agentOutput = await agentExecutorWithMemory.invoke( { input: "Remember my name?" }, config);console.log("---");console.log(agentOutput.output);console.log("---");agentOutput = await agentExecutorWithMemory.invoke( { input: "what was that output again?" }, config);console.log(agentOutput.output); The magic_function takes an input number and applies some magic to it, returning the output. For an input of 3, the output is 5.---Okay, I remember your name is Polly.---So the output of the magic_function with an input of 3 is 5. #### In LangGraph[​](#in-langgraph "Direct link to In LangGraph") The equivalent to this type of memory in LangGraph is [persistence](https://langchain-ai.github.io/langgraphjs/how-tos/persistence/), and [checkpointing](https://langchain-ai.github.io/langgraphjs/reference/interfaces/index.Checkpoint.html). Add a `checkpointer` to the agent and you get chat memory for free. You’ll need to also pass a `thread_id` within the `configurable` field in the `config` parameter. Notice that we only pass one message into each request, but the model still has context from previous runs: import { MemorySaver } from "@langchain/langgraph";const memory = new MemorySaver();const appWithMemory = createReactAgent({ llm, tools, checkpointSaver: memory,});const config = { configurable: { thread_id: "test-thread", },};agentOutput = await appWithMemory.invoke( { messages: [ new HumanMessage( "Hi, I'm polly! What's the output of magic_function of 3?" ), ], }, config);console.log(agentOutput.messages[agentOutput.messages.length - 1].content);console.log("---");agentOutput = await appWithMemory.invoke( { messages: [new HumanMessage("Remember my name?")], }, config);console.log(agentOutput.messages[agentOutput.messages.length - 1].content);console.log("---");agentOutput = await appWithMemory.invoke( { messages: [new HumanMessage("what was that output again?")], }, config);console.log(agentOutput.messages[agentOutput.messages.length - 1].content); The magic_function takes an input number and applies some magic to it, returning the output. For an input of 3, the magic_function returns 5.---Ah yes, I remember your name is Polly! It's nice to meet you Polly.---So the magic_function returned an output of 5 for an input of 3. Iterating through steps[​](#iterating-through-steps "Direct link to Iterating through steps") --------------------------------------------------------------------------------------------- With LangChain’s [`AgentExecutor`](https://api.js.langchain.com/classes/langchain_agents.AgentExecutor.html), you could iterate over the steps using the [`stream`](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#stream) method: const langChainStream = await agentExecutor.stream({ input: query });for await (const step of langChainStream) { console.log(step);} { intermediateSteps: [ { action: { tool: "magic_function", toolInput: { input: 3 }, toolCallId: "toolu_01KCJJ8kyiY5LV4RHbVPzK8v", log: 'Invoking "magic_function" with {"input":3}\n' + '[{"type":"tool_use","id":"toolu_01KCJJ8kyiY5LV4RHbVPzK8v"'... 46 more characters, messageLog: [ [AIMessageChunk] ] }, observation: "5" } ]}{ output: "The value of magic_function(3) is 5." } #### In LangGraph[​](#in-langgraph-1 "Direct link to In LangGraph") In LangGraph, things are handled natively using the stream method. const langGraphStream = await app.stream( { messages: [new HumanMessage(query)] }, { streamMode: "updates" });for await (const step of langGraphStream) { console.log(step);} { agent: { messages: [ AIMessage { lc_serializable: true, lc_kwargs: { content: [Array], additional_kwargs: [Object], tool_calls: [Array], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: [ [Object] ], name: undefined, additional_kwargs: { id: "msg_01WWYeJvJroT82QhJQZKdwSt", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: [Object] }, response_metadata: { id: "msg_01WWYeJvJroT82QhJQZKdwSt", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: [Object] }, tool_calls: [ [Object] ], invalid_tool_calls: [] } ] }}{ tools: { messages: [ ToolMessage { lc_serializable: true, lc_kwargs: { name: "magic_function", content: "5", tool_call_id: "toolu_01X9pwxuroTWNVqiwQTL1U8C", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "5", name: "magic_function", additional_kwargs: {}, response_metadata: {}, tool_call_id: "toolu_01X9pwxuroTWNVqiwQTL1U8C" } ] }}{ agent: { messages: [ AIMessage { lc_serializable: true, lc_kwargs: { content: "The value of magic_function(3) is 5.", tool_calls: [], invalid_tool_calls: [], additional_kwargs: [Object], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "The value of magic_function(3) is 5.", name: undefined, additional_kwargs: { id: "msg_012kQPkxt2CrsFw4CsdfNTWr", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: [Object] }, response_metadata: { id: "msg_012kQPkxt2CrsFw4CsdfNTWr", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: [Object] }, tool_calls: [], invalid_tool_calls: [] } ] }} `returnIntermediateSteps`[​](#returnintermediatesteps "Direct link to returnintermediatesteps") ----------------------------------------------------------------------------------------------- Setting this parameter on AgentExecutor allows users to access intermediate\_steps, which pairs agent actions (e.g., tool invocations) with their outcomes. const agentExecutorWithIntermediateSteps = new AgentExecutor({ agent, tools, returnIntermediateSteps: true,});const result = await agentExecutorWithIntermediateSteps.invoke({ input: query,});console.log(result.intermediateSteps); [ { action: { tool: "magic_function", toolInput: { input: 3 }, toolCallId: "toolu_0126dJXbjwLC5daAScz8bw1k", log: 'Invoking "magic_function" with {"input":3}\n' + '[{"type":"tool_use","id":"toolu_0126dJXbjwLC5daAScz8bw1k"'... 46 more characters, messageLog: [ AIMessageChunk { lc_serializable: true, lc_kwargs: [Object], lc_namespace: [Array], content: [Array], name: undefined, additional_kwargs: [Object], response_metadata: {}, tool_calls: [Array], invalid_tool_calls: [], tool_call_chunks: [Array] } ] }, observation: "5" }] By default the [react agent executor](https://langchain-ai.github.io/langgraphjs/reference/functions/prebuilt.createReactAgent.html) in LangGraph appends all messages to the central state. Therefore, it is easy to see any intermediate steps by just looking at the full state. agentOutput = await app.invoke({ messages: [new HumanMessage(query)],});console.log(agentOutput.messages); [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "what is the value of magic_function(3)?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "what is the value of magic_function(3)?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: [ { type: "tool_use", id: "toolu_01L2N6TKrZxyUWRCQZ5qLYVj", name: "magic_function", input: [Object] } ], additional_kwargs: { id: "msg_01BhXyjA2PTwGC5J3JNnfAXY", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: { input_tokens: 365, output_tokens: 53 } }, tool_calls: [ { name: "magic_function", args: [Object], id: "toolu_01L2N6TKrZxyUWRCQZ5qLYVj" } ], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: [ { type: "tool_use", id: "toolu_01L2N6TKrZxyUWRCQZ5qLYVj", name: "magic_function", input: { input: 3 } } ], name: undefined, additional_kwargs: { id: "msg_01BhXyjA2PTwGC5J3JNnfAXY", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: { input_tokens: 365, output_tokens: 53 } }, response_metadata: { id: "msg_01BhXyjA2PTwGC5J3JNnfAXY", model: "claude-3-haiku-20240307", stop_reason: "tool_use", stop_sequence: null, usage: { input_tokens: 365, output_tokens: 53 } }, tool_calls: [ { name: "magic_function", args: { input: 3 }, id: "toolu_01L2N6TKrZxyUWRCQZ5qLYVj" } ], invalid_tool_calls: [] }, ToolMessage { lc_serializable: true, lc_kwargs: { name: "magic_function", content: "5", tool_call_id: "toolu_01L2N6TKrZxyUWRCQZ5qLYVj", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "5", name: "magic_function", additional_kwargs: {}, response_metadata: {}, tool_call_id: "toolu_01L2N6TKrZxyUWRCQZ5qLYVj" }, AIMessage { lc_serializable: true, lc_kwargs: { content: "The value of magic_function(3) is 5.", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_01ABtcXJ4CwMHphYYmffQZoF", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 431, output_tokens: 17 } }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "The value of magic_function(3) is 5.", name: undefined, additional_kwargs: { id: "msg_01ABtcXJ4CwMHphYYmffQZoF", type: "message", role: "assistant", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 431, output_tokens: 17 } }, response_metadata: { id: "msg_01ABtcXJ4CwMHphYYmffQZoF", model: "claude-3-haiku-20240307", stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 431, output_tokens: 17 } }, tool_calls: [], invalid_tool_calls: [] }] `maxIterations`[​](#maxiterations "Direct link to maxiterations") ----------------------------------------------------------------- `AgentExecutor` implements a `maxIterations` parameter, whereas this is controlled via `recursionLimit` in LangGraph. Note that in the LangChain `AgentExecutor`, an “iteration” includes a full turn of tool invocation and execution. In LangGraph, each step contributes to the recursion limit, so we will need to multiply by two (and add one) to get equivalent results. If the recursion limit is reached, LangGraph raises a specific exception type, that we can catch and manage similarly to AgentExecutor. const badMagicTool = tool( async ({ input }) => { return "Sorry, there was an error. Please try again."; }, { name: "magic_function", description: "Applies a magic function to an input.", schema: z.object({ input: z.string(), }), });const badTools = [badMagicTool];const spanishAgentExecutorWithMaxIterations = new AgentExecutor({ agent: createToolCallingAgent({ llm, tools: badTools, prompt: spanishPrompt, }), tools: badTools, verbose: true, maxIterations: 2,});await spanishAgentExecutorWithMaxIterations.invoke({ input: query }); [chain/start] [1:chain:AgentExecutor] Entering Chain run with input: { "input": "what is the value of magic_function(3)?"}[chain/start] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent] Entering Chain run with input: { "input": "what is the value of magic_function(3)?", "steps": []}[chain/start] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 3:chain:RunnableAssign] Entering Chain run with input: { "input": ""}[chain/start] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 3:chain:RunnableAssign > 4:chain:RunnableMap] Entering Chain run with input: { "input": ""}[chain/start] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 3:chain:RunnableAssign > 4:chain:RunnableMap > 5:chain:RunnableLambda] Entering Chain run with input: { "input": ""}[chain/end] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 3:chain:RunnableAssign > 4:chain:RunnableMap > 5:chain:RunnableLambda] [0ms] Exiting Chain run with output: { "output": []}[chain/end] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 3:chain:RunnableAssign > 4:chain:RunnableMap] [1ms] Exiting Chain run with output: { "agent_scratchpad": []}[chain/end] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 3:chain:RunnableAssign] [1ms] Exiting Chain run with output: { "input": "what is the value of magic_function(3)?", "steps": [], "agent_scratchpad": []}[chain/start] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 6:prompt:ChatPromptTemplate] Entering Chain run with input: { "input": "what is the value of magic_function(3)?", "steps": [], "agent_scratchpad": []}[chain/end] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 6:prompt:ChatPromptTemplate] [0ms] Exiting Chain run with output: { "lc": 1, "type": "constructor", "id": [ "langchain_core", "prompt_values", "ChatPromptValue" ], "kwargs": { "messages": [ { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "SystemMessage" ], "kwargs": { "content": "You are a helpful assistant. Respond only in Spanish.", "additional_kwargs": {}, "response_metadata": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "HumanMessage" ], "kwargs": { "content": "what is the value of magic_function(3)?", "additional_kwargs": {}, "response_metadata": {} } } ] }}[llm/start] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 7:llm:ChatAnthropic] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "SystemMessage" ], "kwargs": { "content": "You are a helpful assistant. Respond only in Spanish.", "additional_kwargs": {}, "response_metadata": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "HumanMessage" ], "kwargs": { "content": "what is the value of magic_function(3)?", "additional_kwargs": {}, "response_metadata": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 7:llm:ChatAnthropic] [1.56s] Exiting LLM run with output: { "generations": [ [ { "text": "Lo siento, pero la función \"magic_function\" espera un parámetro de tipo \"string\", no un número entero. Por favor, proporciona una entrada de tipo cadena de texto para que pueda aplicar la función mágica.", "message": { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessageChunk" ], "kwargs": { "content": "Lo siento, pero la función \"magic_function\" espera un parámetro de tipo \"string\", no un número entero. Por favor, proporciona una entrada de tipo cadena de texto para que pueda aplicar la función mágica.", "additional_kwargs": { "id": "msg_011b4GnLtiCRnCzZiqUBAZeH", "type": "message", "role": "assistant", "model": "claude-3-haiku-20240307", "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 378, "output_tokens": 59 } }, "tool_call_chunks": [], "tool_calls": [], "invalid_tool_calls": [], "response_metadata": {} } } } ] ]}[chain/start] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 8:parser:ToolCallingAgentOutputParser] Entering Chain run with input: { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessageChunk" ], "kwargs": { "content": "Lo siento, pero la función \"magic_function\" espera un parámetro de tipo \"string\", no un número entero. Por favor, proporciona una entrada de tipo cadena de texto para que pueda aplicar la función mágica.", "additional_kwargs": { "id": "msg_011b4GnLtiCRnCzZiqUBAZeH", "type": "message", "role": "assistant", "model": "claude-3-haiku-20240307", "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 378, "output_tokens": 59 } }, "tool_call_chunks": [], "tool_calls": [], "invalid_tool_calls": [], "response_metadata": {} }}[chain/end] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent > 8:parser:ToolCallingAgentOutputParser] [0ms] Exiting Chain run with output: { "returnValues": { "output": "Lo siento, pero la función \"magic_function\" espera un parámetro de tipo \"string\", no un número entero. Por favor, proporciona una entrada de tipo cadena de texto para que pueda aplicar la función mágica." }, "log": "Lo siento, pero la función \"magic_function\" espera un parámetro de tipo \"string\", no un número entero. Por favor, proporciona una entrada de tipo cadena de texto para que pueda aplicar la función mágica."}[chain/end] [1:chain:AgentExecutor > 2:chain:ToolCallingAgent] [1.56s] Exiting Chain run with output: { "returnValues": { "output": "Lo siento, pero la función \"magic_function\" espera un parámetro de tipo \"string\", no un número entero. Por favor, proporciona una entrada de tipo cadena de texto para que pueda aplicar la función mágica." }, "log": "Lo siento, pero la función \"magic_function\" espera un parámetro de tipo \"string\", no un número entero. Por favor, proporciona una entrada de tipo cadena de texto para que pueda aplicar la función mágica."}[chain/end] [1:chain:AgentExecutor] [1.56s] Exiting Chain run with output: { "input": "what is the value of magic_function(3)?", "output": "Lo siento, pero la función \"magic_function\" espera un parámetro de tipo \"string\", no un número entero. Por favor, proporciona una entrada de tipo cadena de texto para que pueda aplicar la función mágica."} { input: "what is the value of magic_function(3)?", output: 'Lo siento, pero la función "magic_function" espera un parámetro de tipo "string", no un número enter'... 103 more characters} import { GraphRecursionError } from "@langchain/langgraph";const RECURSION_LIMIT = 2 * 2 + 1;const appWithBadTools = createReactAgent({ llm, tools: badTools });try { await appWithBadTools.invoke( { messages: [new HumanMessage(query)], }, { recursionLimit: RECURSION_LIMIT, } );} catch (e) { if (e instanceof GraphRecursionError) { console.log("Recursion limit reached."); } else { throw e; }} Recursion limit reached. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to add message history ](/v0.2/docs/how_to/message_history)[ Next How to generate multiple embeddings per document ](/v0.2/docs/how_to/multi_vector) * [Basic Usage](#basic-usage) * [Prompt Templates](#prompt-templates) * [Memory](#memory) * [Iterating through steps](#iterating-through-steps) * [`returnIntermediateSteps`](#returnintermediatesteps) * [`maxIterations`](#maxiterations)
null
https://js.langchain.com/v0.2/docs/people/
People ====== There are some incredible humans from all over the world who have been instrumental in helping the LangChain community flourish 🌐! This page highlights a few of those folks who have dedicated their time to the open-source repo in the form of direct contributions and reviews. Top reviewers[​](#top-reviewers "Direct link to Top reviewers") --------------------------------------------------------------- As LangChain has grown, the amount of surface area that maintainers cover has grown as well. Thank you to the following folks who have gone above and beyond in reviewing incoming PRs 🙏! [![Avatar for afirstenberg](https://avatars.githubusercontent.com/u/3507578?v=4)](https://github.com/afirstenberg)[@afirstenberg](https://github.com/afirstenberg) [![Avatar for sullivan-sean](https://avatars.githubusercontent.com/u/22581534?u=8f88473db2f929a965b6371733efda28e3fa1948&v=4)](https://github.com/sullivan-sean)[@sullivan-sean](https://github.com/sullivan-sean) [![Avatar for tomasonjo](https://avatars.githubusercontent.com/u/19948365?v=4)](https://github.com/tomasonjo)[@tomasonjo](https://github.com/tomasonjo) [![Avatar for ppramesi](https://avatars.githubusercontent.com/u/6775031?v=4)](https://github.com/ppramesi)[@ppramesi](https://github.com/ppramesi) [![Avatar for jacobrosenthal](https://avatars.githubusercontent.com/u/455796?v=4)](https://github.com/jacobrosenthal)[@jacobrosenthal](https://github.com/jacobrosenthal) [![Avatar for mieslep](https://avatars.githubusercontent.com/u/5420540?u=8f038c002fbce42427999eb715dc9f868cef1c84&v=4)](https://github.com/mieslep)[@mieslep](https://github.com/mieslep) Top recent contributors[​](#top-recent-contributors "Direct link to Top recent contributors") --------------------------------------------------------------------------------------------- The list below contains contributors who have had the most PRs merged in the last three months, weighted (imperfectly) by impact. Thank you all so much for your time and efforts in making LangChain better ❤️! [![Avatar for sinedied](https://avatars.githubusercontent.com/u/593151?u=08557bbdd96221813b8aec932dd7de895ac040ea&v=4)](https://github.com/sinedied)[@sinedied](https://github.com/sinedied) [![Avatar for easwee](https://avatars.githubusercontent.com/u/2518825?u=a24026bc5ed35688174b1a36f3c29eda594d38d7&v=4)](https://github.com/easwee)[@easwee](https://github.com/easwee) [![Avatar for afirstenberg](https://avatars.githubusercontent.com/u/3507578?v=4)](https://github.com/afirstenberg)[@afirstenberg](https://github.com/afirstenberg) [![Avatar for Anush008](https://avatars.githubusercontent.com/u/46051506?u=026f5f140e8b7ba4744bf971f9ebdea9ebab67ca&v=4)](https://github.com/Anush008)[@Anush008](https://github.com/Anush008) [![Avatar for jeasonnow](https://avatars.githubusercontent.com/u/16950207?u=ab2d0d4f1574398ac842e6bb3c2ba020ab7711eb&v=4)](https://github.com/jeasonnow)[@jeasonnow](https://github.com/jeasonnow) [![Avatar for rahilvora](https://avatars.githubusercontent.com/u/5127548?u=0cd74312c28da39646785409fb0a37a9b3d3420a&v=4)](https://github.com/rahilvora)[@rahilvora](https://github.com/rahilvora) [![Avatar for lukywong](https://avatars.githubusercontent.com/u/1433871?v=4)](https://github.com/lukywong)[@lukywong](https://github.com/lukywong) [![Avatar for fahreddinozcan](https://avatars.githubusercontent.com/u/88107904?v=4)](https://github.com/fahreddinozcan)[@fahreddinozcan](https://github.com/fahreddinozcan) [![Avatar for tomasonjo](https://avatars.githubusercontent.com/u/19948365?v=4)](https://github.com/tomasonjo)[@tomasonjo](https://github.com/tomasonjo) [![Avatar for nicoloboschi](https://avatars.githubusercontent.com/u/23314389?u=2014e20e246530fa89bd902fe703b6f9e6ecf833&v=4)](https://github.com/nicoloboschi)[@nicoloboschi](https://github.com/nicoloboschi) [![Avatar for davidfant](https://avatars.githubusercontent.com/u/17096641?u=9b935c68c077d53642c1b4aff62f04d08e2ffac7&v=4)](https://github.com/davidfant)[@davidfant](https://github.com/davidfant) [![Avatar for mishushakov](https://avatars.githubusercontent.com/u/10400064?u=581d97314df325c15ec221f64834003d3bba5cc1&v=4)](https://github.com/mishushakov)[@mishushakov](https://github.com/mishushakov) [![Avatar for lokesh-couchbase](https://avatars.githubusercontent.com/u/113521973?v=4)](https://github.com/lokesh-couchbase)[@lokesh-couchbase](https://github.com/lokesh-couchbase) [![Avatar for CahidArda](https://avatars.githubusercontent.com/u/57228345?v=4)](https://github.com/CahidArda)[@CahidArda](https://github.com/CahidArda) [![Avatar for sarangan12](https://avatars.githubusercontent.com/u/602456?u=d39962c60b0ac5fea4e97cb67433a42c736c3c5b&v=4)](https://github.com/sarangan12)[@sarangan12](https://github.com/sarangan12) [![Avatar for MJDeligan](https://avatars.githubusercontent.com/u/48515433?v=4)](https://github.com/MJDeligan)[@MJDeligan](https://github.com/MJDeligan) [![Avatar for karol-f](https://avatars.githubusercontent.com/u/893082?u=0cda88d40a24ee696580f2e62f5569f49117cf40&v=4)](https://github.com/karol-f)[@karol-f](https://github.com/karol-f) [![Avatar for janvi-kalra](https://avatars.githubusercontent.com/u/119091286?u=ed9e9d72bbf9964b80f81e5ba8d1d5b2f860c23f&v=4)](https://github.com/janvi-kalra)[@janvi-kalra](https://github.com/janvi-kalra) [![Avatar for TeCHiScy](https://avatars.githubusercontent.com/u/741195?u=e5937011ef84ff8a4b4b62ac1926a291c04f5d8b&v=4)](https://github.com/TeCHiScy)[@TeCHiScy](https://github.com/TeCHiScy) [![Avatar for cinqisap](https://avatars.githubusercontent.com/u/158295355?v=4)](https://github.com/cinqisap)[@cinqisap](https://github.com/cinqisap) Core maintainers[​](#core-maintainers "Direct link to Core maintainers") ------------------------------------------------------------------------ Hello there 👋! We're LangChain's core maintainers. If you've spent time in the community, you've probably crossed paths with at least one of us already. [![Avatar for bracesproul](https://avatars.githubusercontent.com/u/46789226?u=83f467441c4b542b900fe2bb8fe45e26bf918da0&v=4)](https://github.com/bracesproul)[@bracesproul](https://github.com/bracesproul) [![Avatar for dqbd](https://avatars.githubusercontent.com/u/1443449?u=fe32372ae8f497065ef0a1c54194d9dff36fb81d&v=4)](https://github.com/dqbd)[@dqbd](https://github.com/dqbd) [![Avatar for hwchase17](https://avatars.githubusercontent.com/u/11986836?u=f4c4f21a82b2af6c9f91e1f1d99ea40062f7a101&v=4)](https://github.com/hwchase17)[@hwchase17](https://github.com/hwchase17) [![Avatar for nfcampos](https://avatars.githubusercontent.com/u/56902?u=fdb30e802c68bc338dd9c0820f713e4fdac75db7&v=4)](https://github.com/nfcampos)[@nfcampos](https://github.com/nfcampos) [![Avatar for jacoblee93](https://avatars.githubusercontent.com/u/6952323?u=d785f9406c5a78ebd75922567b2693fb643c3bb0&v=4)](https://github.com/jacoblee93)[@jacoblee93](https://github.com/jacoblee93) Top all-time contributors[​](#top-all-time-contributors "Direct link to Top all-time contributors") --------------------------------------------------------------------------------------------------- And finally, this is an all-time list of all-stars who have made significant contributions to the framework 🌟: [![Avatar for afirstenberg](https://avatars.githubusercontent.com/u/3507578?v=4)](https://github.com/afirstenberg)[@afirstenberg](https://github.com/afirstenberg) [![Avatar for ppramesi](https://avatars.githubusercontent.com/u/6775031?v=4)](https://github.com/ppramesi)[@ppramesi](https://github.com/ppramesi) [![Avatar for jacobrosenthal](https://avatars.githubusercontent.com/u/455796?v=4)](https://github.com/jacobrosenthal)[@jacobrosenthal](https://github.com/jacobrosenthal) [![Avatar for sullivan-sean](https://avatars.githubusercontent.com/u/22581534?u=8f88473db2f929a965b6371733efda28e3fa1948&v=4)](https://github.com/sullivan-sean)[@sullivan-sean](https://github.com/sullivan-sean) [![Avatar for sinedied](https://avatars.githubusercontent.com/u/593151?u=08557bbdd96221813b8aec932dd7de895ac040ea&v=4)](https://github.com/sinedied)[@sinedied](https://github.com/sinedied) [![Avatar for tomasonjo](https://avatars.githubusercontent.com/u/19948365?v=4)](https://github.com/tomasonjo)[@tomasonjo](https://github.com/tomasonjo) [![Avatar for skarard](https://avatars.githubusercontent.com/u/602085?u=f8a9736cfa9fe8875d19861b0276e24de8f3d0a0&v=4)](https://github.com/skarard)[@skarard](https://github.com/skarard) [![Avatar for chasemcdo](https://avatars.githubusercontent.com/u/74692158?u=9c25a170d24cc30f10eafc4d44a38067cdf5eed8&v=4)](https://github.com/chasemcdo)[@chasemcdo](https://github.com/chasemcdo) [![Avatar for MaximeThoonsen](https://avatars.githubusercontent.com/u/4814551?u=efb35c6a7dc1ce99dfa8ac8f0f1314cdb4fddfe1&v=4)](https://github.com/MaximeThoonsen)[@MaximeThoonsen](https://github.com/MaximeThoonsen) [![Avatar for easwee](https://avatars.githubusercontent.com/u/2518825?u=a24026bc5ed35688174b1a36f3c29eda594d38d7&v=4)](https://github.com/easwee)[@easwee](https://github.com/easwee) [![Avatar for mieslep](https://avatars.githubusercontent.com/u/5420540?u=8f038c002fbce42427999eb715dc9f868cef1c84&v=4)](https://github.com/mieslep)[@mieslep](https://github.com/mieslep) [![Avatar for ysnows](https://avatars.githubusercontent.com/u/11255869?u=b0b519b6565c43d01795ba092521c8677f30134c&v=4)](https://github.com/ysnows)[@ysnows](https://github.com/ysnows) [![Avatar for tyumentsev4](https://avatars.githubusercontent.com/u/56769451?u=088102b6160822bc68c25a2a5df170080d0b16a2&v=4)](https://github.com/tyumentsev4)[@tyumentsev4](https://github.com/tyumentsev4) [![Avatar for nickscamara](https://avatars.githubusercontent.com/u/20311743?u=29bf2391ae34297a12a88d813731b0bdf289e4a5&v=4)](https://github.com/nickscamara)[@nickscamara](https://github.com/nickscamara) [![Avatar for nigel-daniels](https://avatars.githubusercontent.com/u/4641452?v=4)](https://github.com/nigel-daniels)[@nigel-daniels](https://github.com/nigel-daniels) [![Avatar for MJDeligan](https://avatars.githubusercontent.com/u/48515433?v=4)](https://github.com/MJDeligan)[@MJDeligan](https://github.com/MJDeligan) [![Avatar for malandis](https://avatars.githubusercontent.com/u/3690240?v=4)](https://github.com/malandis)[@malandis](https://github.com/malandis) [![Avatar for danielchalef](https://avatars.githubusercontent.com/u/131175?u=332fe36f12d9ffe9e4414dc776b381fe801a9c53&v=4)](https://github.com/danielchalef)[@danielchalef](https://github.com/danielchalef) [![Avatar for Anush008](https://avatars.githubusercontent.com/u/46051506?u=026f5f140e8b7ba4744bf971f9ebdea9ebab67ca&v=4)](https://github.com/Anush008)[@Anush008](https://github.com/Anush008) [![Avatar for mfortman11](https://avatars.githubusercontent.com/u/6100513?u=c758a02fc05dc36315fcfadfccd6208883436cb8&v=4)](https://github.com/mfortman11)[@mfortman11](https://github.com/mfortman11) [![Avatar for kwkr](https://avatars.githubusercontent.com/u/20127759?v=4)](https://github.com/kwkr)[@kwkr](https://github.com/kwkr) [![Avatar for fahreddinozcan](https://avatars.githubusercontent.com/u/88107904?v=4)](https://github.com/fahreddinozcan)[@fahreddinozcan](https://github.com/fahreddinozcan) [![Avatar for ewfian](https://avatars.githubusercontent.com/u/12423122?u=681de0c470e9b349963ee935ddfd6b2e097e7181&v=4)](https://github.com/ewfian)[@ewfian](https://github.com/ewfian) [![Avatar for Swimburger](https://avatars.githubusercontent.com/u/3382717?u=5a84a173b0e80effc9161502c0848bf06c84bde9&v=4)](https://github.com/Swimburger)[@Swimburger](https://github.com/Swimburger) [![Avatar for jeasonnow](https://avatars.githubusercontent.com/u/16950207?u=ab2d0d4f1574398ac842e6bb3c2ba020ab7711eb&v=4)](https://github.com/jeasonnow)[@jeasonnow](https://github.com/jeasonnow) [![Avatar for sarangan12](https://avatars.githubusercontent.com/u/602456?u=d39962c60b0ac5fea4e97cb67433a42c736c3c5b&v=4)](https://github.com/sarangan12)[@sarangan12](https://github.com/sarangan12) [![Avatar for jasondotparse](https://avatars.githubusercontent.com/u/13938372?u=0e3f80aa515c41b7d9084b73d761cad378ebdc7a&v=4)](https://github.com/jasondotparse)[@jasondotparse](https://github.com/jasondotparse) [![Avatar for mishushakov](https://avatars.githubusercontent.com/u/10400064?u=581d97314df325c15ec221f64834003d3bba5cc1&v=4)](https://github.com/mishushakov)[@mishushakov](https://github.com/mishushakov) [![Avatar for kristianfreeman](https://avatars.githubusercontent.com/u/922353?u=ad00df1efd8f04a469de6087ee3cd7d7012533f7&v=4)](https://github.com/kristianfreeman)[@kristianfreeman](https://github.com/kristianfreeman) [![Avatar for neebdev](https://avatars.githubusercontent.com/u/94310799?u=b6f604bc6c3a6380f0b83025ca94e2e22179ac2a&v=4)](https://github.com/neebdev)[@neebdev](https://github.com/neebdev) [![Avatar for tsg](https://avatars.githubusercontent.com/u/101817?u=39f31ff29d2589046148c6ed1c1c923982d86b1a&v=4)](https://github.com/tsg)[@tsg](https://github.com/tsg) [![Avatar for lokesh-couchbase](https://avatars.githubusercontent.com/u/113521973?v=4)](https://github.com/lokesh-couchbase)[@lokesh-couchbase](https://github.com/lokesh-couchbase) [![Avatar for nicoloboschi](https://avatars.githubusercontent.com/u/23314389?u=2014e20e246530fa89bd902fe703b6f9e6ecf833&v=4)](https://github.com/nicoloboschi)[@nicoloboschi](https://github.com/nicoloboschi) [![Avatar for zackproser](https://avatars.githubusercontent.com/u/1769996?u=3555434bbfa99f2267f30ded67a15132e3a7bd27&v=4)](https://github.com/zackproser)[@zackproser](https://github.com/zackproser) [![Avatar for justindra](https://avatars.githubusercontent.com/u/4289486?v=4)](https://github.com/justindra)[@justindra](https://github.com/justindra) [![Avatar for vincelwt](https://avatars.githubusercontent.com/u/5092466?u=713f9947e4315b6f0ef62ec5cccd978133006783&v=4)](https://github.com/vincelwt)[@vincelwt](https://github.com/vincelwt) [![Avatar for cwoolum](https://avatars.githubusercontent.com/u/942415?u=8210ef711d1666ec234db9a0c4a9b32fd9f36593&v=4)](https://github.com/cwoolum)[@cwoolum](https://github.com/cwoolum) [![Avatar for sunner](https://avatars.githubusercontent.com/u/255413?v=4)](https://github.com/sunner)[@sunner](https://github.com/sunner) [![Avatar for rahilvora](https://avatars.githubusercontent.com/u/5127548?u=0cd74312c28da39646785409fb0a37a9b3d3420a&v=4)](https://github.com/rahilvora)[@rahilvora](https://github.com/rahilvora) [![Avatar for lukywong](https://avatars.githubusercontent.com/u/1433871?v=4)](https://github.com/lukywong)[@lukywong](https://github.com/lukywong) [![Avatar for mayooear](https://avatars.githubusercontent.com/u/107035552?u=708ca9b002559f6175803a80a1e47f3e84ba91e2&v=4)](https://github.com/mayooear)[@mayooear](https://github.com/mayooear) [![Avatar for chitalian](https://avatars.githubusercontent.com/u/26822232?u=accedd106a5e9d8335cb631c1bfe84b8cc494083&v=4)](https://github.com/chitalian)[@chitalian](https://github.com/chitalian) [![Avatar for paaatrrrick](https://avatars.githubusercontent.com/u/88113528?u=23275c7b8928a38b34195358ea9f4d057fe1e171&v=4)](https://github.com/paaatrrrick)[@paaatrrrick](https://github.com/paaatrrrick) [![Avatar for alexleventer](https://avatars.githubusercontent.com/u/3254549?u=794d178a761379e162a1092c556e98a9ec5c2410&v=4)](https://github.com/alexleventer)[@alexleventer](https://github.com/alexleventer) [![Avatar for 3eif](https://avatars.githubusercontent.com/u/29833473?u=37b8f7a25883ee98bc6b6bd6029c6d5479724e2f&v=4)](https://github.com/3eif)[@3eif](https://github.com/3eif) [![Avatar for BitVoyagerMan](https://avatars.githubusercontent.com/u/121993229?u=717ed7012c040d5bf3a8ff1fd695a6a4f1ff0626&v=4)](https://github.com/BitVoyagerMan)[@BitVoyagerMan](https://github.com/BitVoyagerMan) [![Avatar for xixixao](https://avatars.githubusercontent.com/u/1473433?u=c4bf1cf9f8699c8647894cd226c0bf9124bdad58&v=4)](https://github.com/xixixao)[@xixixao](https://github.com/xixixao) [![Avatar for jo32](https://avatars.githubusercontent.com/u/501632?u=a714d65c000d8f489f9fc2363f9a372b0dba05e3&v=4)](https://github.com/jo32)[@jo32](https://github.com/jo32) [![Avatar for RohitMidha23](https://avatars.githubusercontent.com/u/38888530?u=5c4b99eff970e551e5b756f270aa5234bc666316&v=4)](https://github.com/RohitMidha23)[@RohitMidha23](https://github.com/RohitMidha23) [![Avatar for karol-f](https://avatars.githubusercontent.com/u/893082?u=0cda88d40a24ee696580f2e62f5569f49117cf40&v=4)](https://github.com/karol-f)[@karol-f](https://github.com/karol-f) [![Avatar for konstantinov-raft](https://avatars.githubusercontent.com/u/105433902?v=4)](https://github.com/konstantinov-raft)[@konstantinov-raft](https://github.com/konstantinov-raft) [![Avatar for volodymyr-memsql](https://avatars.githubusercontent.com/u/57520563?v=4)](https://github.com/volodymyr-memsql)[@volodymyr-memsql](https://github.com/volodymyr-memsql) [![Avatar for jameshfisher](https://avatars.githubusercontent.com/u/166966?u=b78059abca798fbce8c9da4f6ddfb72ea03b20bb&v=4)](https://github.com/jameshfisher)[@jameshfisher](https://github.com/jameshfisher) [![Avatar for the-powerpointer](https://avatars.githubusercontent.com/u/134403026?u=ddd77b62b35c5497ae3d846f8917bdd81e5ef19e&v=4)](https://github.com/the-powerpointer)[@the-powerpointer](https://github.com/the-powerpointer) [![Avatar for davidfant](https://avatars.githubusercontent.com/u/17096641?u=9b935c68c077d53642c1b4aff62f04d08e2ffac7&v=4)](https://github.com/davidfant)[@davidfant](https://github.com/davidfant) [![Avatar for MthwRobinson](https://avatars.githubusercontent.com/u/1635179?u=0631cb84ca580089198114f94d9c27efe730220e&v=4)](https://github.com/MthwRobinson)[@MthwRobinson](https://github.com/MthwRobinson) [![Avatar for SimonPrammer](https://avatars.githubusercontent.com/u/44960995?u=a513117a60e9f1aa09247ec916018ee272897169&v=4)](https://github.com/SimonPrammer)[@SimonPrammer](https://github.com/SimonPrammer) [![Avatar for munkhorgil](https://avatars.githubusercontent.com/u/978987?u=eff77a6f7bc4edbace4929731638d4727923013f&v=4)](https://github.com/munkhorgil)[@munkhorgil](https://github.com/munkhorgil) [![Avatar for alx13](https://avatars.githubusercontent.com/u/1572864?v=4)](https://github.com/alx13)[@alx13](https://github.com/alx13) [![Avatar for castroCrea](https://avatars.githubusercontent.com/u/20707343?u=25e872c764bd31b71148f2dec896f64be5e034ff&v=4)](https://github.com/castroCrea)[@castroCrea](https://github.com/castroCrea) [![Avatar for samheutmaker](https://avatars.githubusercontent.com/u/1767032?u=a50f2b3b339eb965b9c812977aa10d64202e2e95&v=4)](https://github.com/samheutmaker)[@samheutmaker](https://github.com/samheutmaker) [![Avatar for archie-swif](https://avatars.githubusercontent.com/u/2158707?u=8a0aeee45e93ba575321804a7b709bf8897941de&v=4)](https://github.com/archie-swif)[@archie-swif](https://github.com/archie-swif) [![Avatar for valdo99](https://avatars.githubusercontent.com/u/41517614?u=ba37c9a21db3068953ae50d90c1cd07c3dec3abd&v=4)](https://github.com/valdo99)[@valdo99](https://github.com/valdo99) [![Avatar for gmpetrov](https://avatars.githubusercontent.com/u/4693180?u=8cf781d9099d6e2f2d2caf7612a5c2811ba13ef8&v=4)](https://github.com/gmpetrov)[@gmpetrov](https://github.com/gmpetrov) [![Avatar for mattzcarey](https://avatars.githubusercontent.com/u/77928207?u=fc8febe2a4b67384046eb4041b325bb34665d59c&v=4)](https://github.com/mattzcarey)[@mattzcarey](https://github.com/mattzcarey) [![Avatar for albertpurnama](https://avatars.githubusercontent.com/u/14824254?u=b3acdfc46d3d26d44f66a7312b102172c7ff9722&v=4)](https://github.com/albertpurnama)[@albertpurnama](https://github.com/albertpurnama) [![Avatar for CahidArda](https://avatars.githubusercontent.com/u/57228345?v=4)](https://github.com/CahidArda)[@CahidArda](https://github.com/CahidArda) [![Avatar for yroc92](https://avatars.githubusercontent.com/u/17517541?u=7405432fa828c094e130e8193be3cae04ac96d11&v=4)](https://github.com/yroc92)[@yroc92](https://github.com/yroc92) [![Avatar for Basti-an](https://avatars.githubusercontent.com/u/42387209?u=43ac44545861ce4adec99f973aeea3e6cf9a1bc0&v=4)](https://github.com/Basti-an)[@Basti-an](https://github.com/Basti-an) [![Avatar for CarlosZiegler](https://avatars.githubusercontent.com/u/38855507?u=65c19ae772581fb7367f646ed90be44311e60e70&v=4)](https://github.com/CarlosZiegler)[@CarlosZiegler](https://github.com/CarlosZiegler) [![Avatar for iloveitaly](https://avatars.githubusercontent.com/u/150855?v=4)](https://github.com/iloveitaly)[@iloveitaly](https://github.com/iloveitaly) [![Avatar for dilling](https://avatars.githubusercontent.com/u/5846912?v=4)](https://github.com/dilling)[@dilling](https://github.com/dilling) [![Avatar for anselm94](https://avatars.githubusercontent.com/u/9033201?u=e5f657c3a1657c089d7cb88121e544ae7212e6f1&v=4)](https://github.com/anselm94)[@anselm94](https://github.com/anselm94) [![Avatar for gramliu](https://avatars.githubusercontent.com/u/24856195?u=9f55337506cdcac3146772c56b4634e6b46a5e46&v=4)](https://github.com/gramliu)[@gramliu](https://github.com/gramliu) [![Avatar for jeffchuber](https://avatars.githubusercontent.com/u/891664?u=722172a0061f68ab22819fa88a354ec973f70a63&v=4)](https://github.com/jeffchuber)[@jeffchuber](https://github.com/jeffchuber) [![Avatar for ywkim](https://avatars.githubusercontent.com/u/588581?u=df702e5b817a56476cb0cd8e7587b9be844d2850&v=4)](https://github.com/ywkim)[@ywkim](https://github.com/ywkim) [![Avatar for jirimoravcik](https://avatars.githubusercontent.com/u/951187?u=e80c215810058f57145042d12360d463e3a53443&v=4)](https://github.com/jirimoravcik)[@jirimoravcik](https://github.com/jirimoravcik) [![Avatar for janvi-kalra](https://avatars.githubusercontent.com/u/119091286?u=ed9e9d72bbf9964b80f81e5ba8d1d5b2f860c23f&v=4)](https://github.com/janvi-kalra)[@janvi-kalra](https://github.com/janvi-kalra) [![Avatar for yuku](https://avatars.githubusercontent.com/u/96157?v=4)](https://github.com/yuku)[@yuku](https://github.com/yuku) [![Avatar for conroywhitney](https://avatars.githubusercontent.com/u/249891?u=36703ce68261be59109622877012be08fbc090da&v=4)](https://github.com/conroywhitney)[@conroywhitney](https://github.com/conroywhitney) [![Avatar for Czechh](https://avatars.githubusercontent.com/u/4779936?u=ab072503433effc18c071b31adda307988877d5e&v=4)](https://github.com/Czechh)[@Czechh](https://github.com/Czechh) [![Avatar for adam101](https://avatars.githubusercontent.com/u/1535782?v=4)](https://github.com/adam101)[@adam101](https://github.com/adam101) [![Avatar for OlegIvaniv](https://avatars.githubusercontent.com/u/12657221?v=4)](https://github.com/OlegIvaniv)[@OlegIvaniv](https://github.com/OlegIvaniv) [![Avatar for jaclar](https://avatars.githubusercontent.com/u/362704?u=52d868cc75c793fa895ef7035ae45516bd915e84&v=4)](https://github.com/jaclar)[@jaclar](https://github.com/jaclar) [![Avatar for TeCHiScy](https://avatars.githubusercontent.com/u/741195?u=e5937011ef84ff8a4b4b62ac1926a291c04f5d8b&v=4)](https://github.com/TeCHiScy)[@TeCHiScy](https://github.com/TeCHiScy) [![Avatar for ivoneijr](https://avatars.githubusercontent.com/u/6401435?u=96c11b6333636bd784ffbff72998591f3b3f087b&v=4)](https://github.com/ivoneijr)[@ivoneijr](https://github.com/ivoneijr) [![Avatar for tonisives](https://avatars.githubusercontent.com/u/1083534?v=4)](https://github.com/tonisives)[@tonisives](https://github.com/tonisives) [![Avatar for Njuelle](https://avatars.githubusercontent.com/u/3192870?u=e126aae39f36565450ebc854b35c6e890b705e71&v=4)](https://github.com/Njuelle)[@Njuelle](https://github.com/Njuelle) [![Avatar for Roland0511](https://avatars.githubusercontent.com/u/588050?u=3c91917389117ee84843d961252ab7a2b9097e0e&v=4)](https://github.com/Roland0511)[@Roland0511](https://github.com/Roland0511) [![Avatar for SebastjanPrachovskij](https://avatars.githubusercontent.com/u/86522260?u=66898c89771c7b8ff38958e9fb9563a1cf7f8004&v=4)](https://github.com/SebastjanPrachovskij)[@SebastjanPrachovskij](https://github.com/SebastjanPrachovskij) [![Avatar for cinqisap](https://avatars.githubusercontent.com/u/158295355?v=4)](https://github.com/cinqisap)[@cinqisap](https://github.com/cinqisap) [![Avatar for dylanintech](https://avatars.githubusercontent.com/u/86082012?u=6516bbf39c5af198123d8ed2e35fff5d200f4d2e&v=4)](https://github.com/dylanintech)[@dylanintech](https://github.com/dylanintech) [![Avatar for andrewnguonly](https://avatars.githubusercontent.com/u/7654246?u=b8599019655adaada3cdc3c3006798df42c44494&v=4)](https://github.com/andrewnguonly)[@andrewnguonly](https://github.com/andrewnguonly) [![Avatar for ShaunBaker](https://avatars.githubusercontent.com/u/1176557?u=c2e8ecfb45b736fc4d3bbfe182e26936bd519fd3&v=4)](https://github.com/ShaunBaker)[@ShaunBaker](https://github.com/ShaunBaker) [![Avatar for machulav](https://avatars.githubusercontent.com/u/2857712?u=6809bef8bf07c46b39cd2fcd6027ed86e76372cd&v=4)](https://github.com/machulav)[@machulav](https://github.com/machulav) [![Avatar for dersia](https://avatars.githubusercontent.com/u/1537958?u=5da46ca1cd93c6fed927c612fc454ba51d0a36b1&v=4)](https://github.com/dersia)[@dersia](https://github.com/dersia) [![Avatar for joshsny](https://avatars.githubusercontent.com/u/7135900?u=109e43c5e906a8ecc1a2d465c4457f5cf29328a5&v=4)](https://github.com/joshsny)[@joshsny](https://github.com/joshsny) [![Avatar for jl4nz](https://avatars.githubusercontent.com/u/94814971?u=266358610eeb54c3393dc127718dd6a997fdbf52&v=4)](https://github.com/jl4nz)[@jl4nz](https://github.com/jl4nz) [![Avatar for eactisgrosso](https://avatars.githubusercontent.com/u/2279003?u=d122874eedb211359d4bf0119877d74ea7d5bcab&v=4)](https://github.com/eactisgrosso)[@eactisgrosso](https://github.com/eactisgrosso) [![Avatar for frankolson](https://avatars.githubusercontent.com/u/6773706?u=738775762205a07fd7de297297c99f781e957c58&v=4)](https://github.com/frankolson)[@frankolson](https://github.com/frankolson) [![Avatar for uthmanmoh](https://avatars.githubusercontent.com/u/83053931?u=5c715d2d4f6786fa749276de8eced710be8bfa99&v=4)](https://github.com/uthmanmoh)[@uthmanmoh](https://github.com/uthmanmoh) [![Avatar for Jordan-Gilliam](https://avatars.githubusercontent.com/u/25993686?u=319a6ed2119197d4d11301614a104ae686f9fc70&v=4)](https://github.com/Jordan-Gilliam)[@Jordan-Gilliam](https://github.com/Jordan-Gilliam) [![Avatar for winor30](https://avatars.githubusercontent.com/u/12413150?u=691a5e076bdd8c9e9fd637a41496b29e11b0c82f&v=4)](https://github.com/winor30)[@winor30](https://github.com/winor30) [![Avatar for willemmulder](https://avatars.githubusercontent.com/u/70933?u=206fafc72fd14b4291cb29269c5e1cc8081d043b&v=4)](https://github.com/willemmulder)[@willemmulder](https://github.com/willemmulder) [![Avatar for aixgeek](https://avatars.githubusercontent.com/u/9697715?u=d139c5568375c2472ac6142325e6856cd766d88d&v=4)](https://github.com/aixgeek)[@aixgeek](https://github.com/aixgeek) [![Avatar for seuha516](https://avatars.githubusercontent.com/u/79067549?u=de7a2688cb44010afafd055d707f3463585494df&v=4)](https://github.com/seuha516)[@seuha516](https://github.com/seuha516) [![Avatar for mhart](https://avatars.githubusercontent.com/u/367936?v=4)](https://github.com/mhart)[@mhart](https://github.com/mhart) [![Avatar for mvaker](https://avatars.githubusercontent.com/u/5671913?u=2e237cb1dd51f9d0dd01f0deb80003163641fc49&v=4)](https://github.com/mvaker)[@mvaker](https://github.com/mvaker) [![Avatar for vitaly-ps](https://avatars.githubusercontent.com/u/141448200?u=a3902a9c11399c916f1af2bf0ead901e7afe1a67&v=4)](https://github.com/vitaly-ps)[@vitaly-ps](https://github.com/vitaly-ps) [![Avatar for cbh123](https://avatars.githubusercontent.com/u/14149230?u=ca710ca2a64391470163ddef6b5ea7633ab26872&v=4)](https://github.com/cbh123)[@cbh123](https://github.com/cbh123) [![Avatar for Neverland3124](https://avatars.githubusercontent.com/u/52025513?u=865e861a1abb0d78be587f685d28fe8a00aee8fe&v=4)](https://github.com/Neverland3124)[@Neverland3124](https://github.com/Neverland3124) [![Avatar for jasonnathan](https://avatars.githubusercontent.com/u/780157?u=d5efec16b5e3a9913dc44967059a70d9a610755d&v=4)](https://github.com/jasonnathan)[@jasonnathan](https://github.com/jasonnathan) [![Avatar for Maanethdesilva](https://avatars.githubusercontent.com/u/94875583?v=4)](https://github.com/Maanethdesilva)[@Maanethdesilva](https://github.com/Maanethdesilva) [![Avatar for fuleinist](https://avatars.githubusercontent.com/u/1163738?v=4)](https://github.com/fuleinist)[@fuleinist](https://github.com/fuleinist) [![Avatar for kwadhwa18](https://avatars.githubusercontent.com/u/6015244?u=a127081404b8dc16ac0e84a869dfff4ac82bbab2&v=4)](https://github.com/kwadhwa18)[@kwadhwa18](https://github.com/kwadhwa18) [![Avatar for sousousore1](https://avatars.githubusercontent.com/u/624438?v=4)](https://github.com/sousousore1)[@sousousore1](https://github.com/sousousore1) [![Avatar for seth-25](https://avatars.githubusercontent.com/u/49222652?u=203c2bef6cbb77668a289b8272aea4fb654558d5&v=4)](https://github.com/seth-25)[@seth-25](https://github.com/seth-25) [![Avatar for tomi-mercado](https://avatars.githubusercontent.com/u/60221771?u=f8c1214535e402b0ff5c3428bfe98b586b517106&v=4)](https://github.com/tomi-mercado)[@tomi-mercado](https://github.com/tomi-mercado) [![Avatar for JHeidinga](https://avatars.githubusercontent.com/u/1702015?u=fa33fb709707e2429f10fbb824abead61628d50c&v=4)](https://github.com/JHeidinga)[@JHeidinga](https://github.com/JHeidinga) [![Avatar for niklas-lohmann](https://avatars.githubusercontent.com/u/68230177?v=4)](https://github.com/niklas-lohmann)[@niklas-lohmann](https://github.com/niklas-lohmann) [![Avatar for Durisvk](https://avatars.githubusercontent.com/u/8467003?u=f07b8c070eaed3ad8972be4f4ca91afb1ae6e2c0&v=4)](https://github.com/Durisvk)[@Durisvk](https://github.com/Durisvk) [![Avatar for BjoernRave](https://avatars.githubusercontent.com/u/36173920?u=c3acae11221a037c16254e2187555ea6259d89c3&v=4)](https://github.com/BjoernRave)[@BjoernRave](https://github.com/BjoernRave) [![Avatar for crazyurus](https://avatars.githubusercontent.com/u/2209055?u=b39f7e70f137ff3d1785d261cb15067f0d91ae05&v=4)](https://github.com/crazyurus)[@crazyurus](https://github.com/crazyurus) [![Avatar for qalqi](https://avatars.githubusercontent.com/u/1781048?u=837879a7e62c6b3736dc39a31ff42873bee2c532&v=4)](https://github.com/qalqi)[@qalqi](https://github.com/qalqi) [![Avatar for katarinasupe](https://avatars.githubusercontent.com/u/61758502?u=20cdcb0bae81b9eb330c94f7cfae462327785219&v=4)](https://github.com/katarinasupe)[@katarinasupe](https://github.com/katarinasupe) [![Avatar for andrewlei](https://avatars.githubusercontent.com/u/1158058?v=4)](https://github.com/andrewlei)[@andrewlei](https://github.com/andrewlei) [![Avatar for floomby](https://avatars.githubusercontent.com/u/3113021?v=4)](https://github.com/floomby)[@floomby](https://github.com/floomby) [![Avatar for milanjrodd](https://avatars.githubusercontent.com/u/121220673?u=55636f26ea48e77e0372008089ff2c38691eaa0a&v=4)](https://github.com/milanjrodd)[@milanjrodd](https://github.com/milanjrodd) [![Avatar for NickMandylas](https://avatars.githubusercontent.com/u/19514618?u=95f8c29ed06696260722c2c6aa7bac3a1136d7a2&v=4)](https://github.com/NickMandylas)[@NickMandylas](https://github.com/NickMandylas) [![Avatar for DravenCat](https://avatars.githubusercontent.com/u/55412122?v=4)](https://github.com/DravenCat)[@DravenCat](https://github.com/DravenCat) [![Avatar for Alireza29675](https://avatars.githubusercontent.com/u/2771377?u=65ec71f9860ac2610e1cb5028173f67713a174d7&v=4)](https://github.com/Alireza29675)[@Alireza29675](https://github.com/Alireza29675) [![Avatar for zhengxs2018](https://avatars.githubusercontent.com/u/7506913?u=42c32ca59ae2e44532cd45027e5b62d2712cf2a2&v=4)](https://github.com/zhengxs2018)[@zhengxs2018](https://github.com/zhengxs2018) [![Avatar for clemenspeters](https://avatars.githubusercontent.com/u/13015002?u=059c556d90a2e5639dee42123077d51223c190f0&v=4)](https://github.com/clemenspeters)[@clemenspeters](https://github.com/clemenspeters) [![Avatar for cmtoomey](https://avatars.githubusercontent.com/u/12201602?u=ea5cbb8d158980f6050dd41ae41b7f72e0a47337&v=4)](https://github.com/cmtoomey)[@cmtoomey](https://github.com/cmtoomey) [![Avatar for igorshapiro](https://avatars.githubusercontent.com/u/1085209?u=16b60724316a7ed8e8b52af576c121215461922a&v=4)](https://github.com/igorshapiro)[@igorshapiro](https://github.com/igorshapiro) [![Avatar for ezynda3](https://avatars.githubusercontent.com/u/5308871?v=4)](https://github.com/ezynda3)[@ezynda3](https://github.com/ezynda3) [![Avatar for more-by-more](https://avatars.githubusercontent.com/u/67614844?u=d3d818efb3e3e2ddda589d6157f853922a460f5b&v=4)](https://github.com/more-by-more)[@more-by-more](https://github.com/more-by-more) [![Avatar for noble-varghese](https://avatars.githubusercontent.com/u/109506617?u=c1d2a1813c51bff89bfa85d533633ed4c201ba2e&v=4)](https://github.com/noble-varghese)[@noble-varghese](https://github.com/noble-varghese) [![Avatar for SananR](https://avatars.githubusercontent.com/u/14956384?u=538ff9bf09497059b312067333f68eba75594802&v=4)](https://github.com/SananR)[@SananR](https://github.com/SananR) [![Avatar for fraserxu](https://avatars.githubusercontent.com/u/1183541?v=4)](https://github.com/fraserxu)[@fraserxu](https://github.com/fraserxu) [![Avatar for ashvardanian](https://avatars.githubusercontent.com/u/1983160?u=536f2558c6ac33b74a6d89520dcb27ba46954070&v=4)](https://github.com/ashvardanian)[@ashvardanian](https://github.com/ashvardanian) [![Avatar for adeelehsan](https://avatars.githubusercontent.com/u/8156837?u=99cacfbd962ff58885bdf68e5fc640fc0d3cb87c&v=4)](https://github.com/adeelehsan)[@adeelehsan](https://github.com/adeelehsan) [![Avatar for henriquegdantas](https://avatars.githubusercontent.com/u/12974790?u=80d76f256a7854da6ae441b6ee078119877398e7&v=4)](https://github.com/henriquegdantas)[@henriquegdantas](https://github.com/henriquegdantas) [![Avatar for evad1n](https://avatars.githubusercontent.com/u/50718218?u=ee35784971ef8dcdfdb25cfe0a8284ca48724938&v=4)](https://github.com/evad1n)[@evad1n](https://github.com/evad1n) [![Avatar for benjibc](https://avatars.githubusercontent.com/u/1585539?u=654a21985c875f78a20eda7e4884e8d64de86fba&v=4)](https://github.com/benjibc)[@benjibc](https://github.com/benjibc) [![Avatar for P-E-B](https://avatars.githubusercontent.com/u/38215315?u=3985b6a3ecb0e8338c5912ea9e20787152d0ad7a&v=4)](https://github.com/P-E-B)[@P-E-B](https://github.com/P-E-B) [![Avatar for omikader](https://avatars.githubusercontent.com/u/16735699?u=29fc7c7c777c3cabc22449b68bbb01fe2fa0b574&v=4)](https://github.com/omikader)[@omikader](https://github.com/omikader) [![Avatar for jasongill](https://avatars.githubusercontent.com/u/241711?v=4)](https://github.com/jasongill)[@jasongill](https://github.com/jasongill) [![Avatar for Luisotee](https://avatars.githubusercontent.com/u/50471205?u=059d6ab166e5a32c496ff50ef6e3fb0ca04a50ad&v=4)](https://github.com/Luisotee)[@Luisotee](https://github.com/Luisotee) [![Avatar for puigde](https://avatars.githubusercontent.com/u/83642160?u=7e76b13b7484e4601bea47dc6e238c89d453a24d&v=4)](https://github.com/puigde)[@puigde](https://github.com/puigde) [![Avatar for Adrastopoulos](https://avatars.githubusercontent.com/u/76796897?u=0bd50d301b4c7025f29396af44c8e1829eff1db6&v=4)](https://github.com/Adrastopoulos)[@Adrastopoulos](https://github.com/Adrastopoulos) [![Avatar for chase-crumbaugh](https://avatars.githubusercontent.com/u/90289500?u=0129550ecfbb4a92922fff7a406566a47a23dfb0&v=4)](https://github.com/chase-crumbaugh)[@chase-crumbaugh](https://github.com/chase-crumbaugh) [![Avatar for Zeneos](https://avatars.githubusercontent.com/u/95008961?v=4)](https://github.com/Zeneos)[@Zeneos](https://github.com/Zeneos) [![Avatar for joseanu](https://avatars.githubusercontent.com/u/2730127?u=9fe1d593bd63c7f116b9c46e9cbd359a2e4304f0&v=4)](https://github.com/joseanu)[@joseanu](https://github.com/joseanu) [![Avatar for JackFener](https://avatars.githubusercontent.com/u/20380671?u=b51d10b71850203e6360655fa59cc679c5a498e6&v=4)](https://github.com/JackFener)[@JackFener](https://github.com/JackFener) [![Avatar for swyxio](https://avatars.githubusercontent.com/u/6764957?u=97ad815028595b73b06ee4b0510e66bbe391228d&v=4)](https://github.com/swyxio)[@swyxio](https://github.com/swyxio) [![Avatar for pczekaj](https://avatars.githubusercontent.com/u/1460539?u=24c2db4a29757f608a54a062340a466cad843825&v=4)](https://github.com/pczekaj)[@pczekaj](https://github.com/pczekaj) [![Avatar for devinburnette](https://avatars.githubusercontent.com/u/13012689?u=7b68c67ea1bbc272c35be7c0bcf1c66a04554179&v=4)](https://github.com/devinburnette)[@devinburnette](https://github.com/devinburnette) [![Avatar for ananis25](https://avatars.githubusercontent.com/u/16446513?u=5026326ed39bfee8325c30cdbd24ac20519d21b8&v=4)](https://github.com/ananis25)[@ananis25](https://github.com/ananis25) [![Avatar for joaopcm](https://avatars.githubusercontent.com/u/58827242?u=3e03812a1074f2ce888b751c48e78a849c7e0aff&v=4)](https://github.com/joaopcm)[@joaopcm](https://github.com/joaopcm) [![Avatar for SalehHindi](https://avatars.githubusercontent.com/u/15721377?u=37fadd6a7bf9dfa63ceb866bda23ca44a7b2c0c2&v=4)](https://github.com/SalehHindi)[@SalehHindi](https://github.com/SalehHindi) [![Avatar for JamsheedMistri](https://avatars.githubusercontent.com/u/13024750?u=6ae631199ec7c0bb34eb8d56200023cdd94720d3&v=4)](https://github.com/JamsheedMistri)[@JamsheedMistri](https://github.com/JamsheedMistri) [![Avatar for cmanou](https://avatars.githubusercontent.com/u/683160?u=e9050e4341c2c9d46b035ea17ea94234634e1b2c&v=4)](https://github.com/cmanou)[@cmanou](https://github.com/cmanou) [![Avatar for micahriggan](https://avatars.githubusercontent.com/u/3626473?u=508e8c831d8eb804e95985d5191a08c761544fad&v=4)](https://github.com/micahriggan)[@micahriggan](https://github.com/micahriggan) [![Avatar for ovuruska](https://avatars.githubusercontent.com/u/75265893?u=7f11152d07f1719da22084388c09b5fc64ab6c89&v=4)](https://github.com/ovuruska)[@ovuruska](https://github.com/ovuruska) [![Avatar for w00ing](https://avatars.githubusercontent.com/u/29723695?u=563d4a628c9af35f827f476e38635310f1cec114&v=4)](https://github.com/w00ing)[@w00ing](https://github.com/w00ing) [![Avatar for madmed88](https://avatars.githubusercontent.com/u/1579388?u=62ca1bfe7c271b5fd1d77abc470aa5e535b1ed83&v=4)](https://github.com/madmed88)[@madmed88](https://github.com/madmed88) [![Avatar for ardsh](https://avatars.githubusercontent.com/u/23664687?u=158ef7e156a7881b8647ece63683aca2c28f132e&v=4)](https://github.com/ardsh)[@ardsh](https://github.com/ardsh) [![Avatar for JoeABCDEF](https://avatars.githubusercontent.com/u/39638510?u=f5fac0a3578572817b37a6dfc00adacb705ec7d0&v=4)](https://github.com/JoeABCDEF)[@JoeABCDEF](https://github.com/JoeABCDEF) [![Avatar for saul-jb](https://avatars.githubusercontent.com/u/2025187?v=4)](https://github.com/saul-jb)[@saul-jb](https://github.com/saul-jb) [![Avatar for JTCorrin](https://avatars.githubusercontent.com/u/73115680?v=4)](https://github.com/JTCorrin)[@JTCorrin](https://github.com/JTCorrin) [![Avatar for zandko](https://avatars.githubusercontent.com/u/37948383?u=04ccf6e060b27e39c931c2608381351cf236a28f&v=4)](https://github.com/zandko)[@zandko](https://github.com/zandko) [![Avatar for federicoestevez](https://avatars.githubusercontent.com/u/10424147?v=4)](https://github.com/federicoestevez)[@federicoestevez](https://github.com/federicoestevez) [![Avatar for martinseanhunt](https://avatars.githubusercontent.com/u/65744?u=ddac1e773828d8058a40bca680cf549e955f69ae&v=4)](https://github.com/martinseanhunt)[@martinseanhunt](https://github.com/martinseanhunt) [![Avatar for functorism](https://avatars.githubusercontent.com/u/17207277?u=4df9bc30a55b4da4b3d6fd20a2956afd722bde24&v=4)](https://github.com/functorism)[@functorism](https://github.com/functorism) [![Avatar for erictt](https://avatars.githubusercontent.com/u/9592198?u=567fa49c73e824525d33eefd836ece16ab9964c8&v=4)](https://github.com/erictt)[@erictt](https://github.com/erictt) [![Avatar for WilliamEspegren](https://avatars.githubusercontent.com/u/131612909?v=4)](https://github.com/WilliamEspegren)[@WilliamEspegren](https://github.com/WilliamEspegren) [![Avatar for lesters](https://avatars.githubusercontent.com/u/5798036?u=4eba31d63c3818d17fb8f9aa923599ac63ebfea8&v=4)](https://github.com/lesters)[@lesters](https://github.com/lesters) [![Avatar for my8bit](https://avatars.githubusercontent.com/u/782268?u=d83da3e6269d53a828bbeb6d661049a1ed185cb0&v=4)](https://github.com/my8bit)[@my8bit](https://github.com/my8bit) [![Avatar for erhant](https://avatars.githubusercontent.com/u/16037166?u=9d056a2f5059684620e22aa4d880e38183309b51&v=4)](https://github.com/erhant)[@erhant](https://github.com/erhant) We're so thankful for your support! And one more thank you to [@tiangolo](https://github.com/tiangolo) for inspiration via FastAPI's [excellent people page](https://fastapi.tiangolo.com/fastapi-people). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E).
null
https://js.langchain.com/v0.2/docs/how_to/message_history
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to add message history On this page How to add message history ========================== Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) * [Chaining runnables](/v0.2/docs/how_to/sequence/) * [Configuring chain parameters at runtime](/v0.2/docs/how_to/binding) * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) * [Chat Messages](/v0.2/docs/concepts/#message-types) The `RunnableWithMessageHistory` lets us add message history to certain types of chains. Specifically, it can be used for any Runnable that takes as input one of * a sequence of [`BaseMessages`](/v0.2/docs/concepts/#message-types) * a dict with a key that takes a sequence of `BaseMessage` * a dict with a key that takes the latest message(s) as a string or sequence of `BaseMessage`, and a separate key that takes historical messages And returns as output one of * a string that can be treated as the contents of an `AIMessage` * a sequence of `BaseMessage` * a dict with a key that contains a sequence of `BaseMessage` Let's take a look at some examples to see how it works. Setup[​](#setup "Direct link to Setup") --------------------------------------- We'll use Upstash to store our chat message histories and Anthropic's claude-2 model so we'll need to install the following dependencies: * npm * Yarn * pnpm npm install @langchain/anthropic @langchain/community @upstash/redis yarn add @langchain/anthropic @langchain/community @upstash/redis pnpm add @langchain/anthropic @langchain/community @upstash/redis You'll need to set environment variables for `ANTHROPIC_API_KEY` and grab your Upstash REST url and secret token. ### [LangSmith](https://smith.langchain.com/)[​](#langsmith "Direct link to langsmith") LangSmith is especially useful for something like message history injection, where it can be hard to otherwise understand what the inputs are to various parts of the chain. Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to uncoment the below and set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2="true"export LANGCHAIN_API_KEY="<your-api-key>" Let's create a simple runnable that takes a dict as input and returns a `BaseMessage`. In this case the `"question"` key in the input represents our input message, and the `"history"` key is where our historical messages will be injected. import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";import { ChatAnthropic } from "@langchain/anthropic";import { UpstashRedisChatMessageHistory } from "@langchain/community/stores/message/upstash_redis";// For demos, you can also use an in-memory store:// import { ChatMessageHistory } from "langchain/stores/message/in_memory";const prompt = ChatPromptTemplate.fromMessages([ ["system", "You're an assistant who's good at {ability}"], new MessagesPlaceholder("history"), ["human", "{question}"],]);const chain = prompt.pipe( new ChatAnthropic({ model: "claude-3-sonnet-20240229" })); ### Adding message history[​](#adding-message-history "Direct link to Adding message history") To add message history to our original chain we wrap it in the `RunnableWithMessageHistory` class. Crucially, we also need to define a `getMessageHistory()` method that takes a `sessionId` string and based on it returns a `BaseChatMessageHistory`. Given the same input, this method should return an equivalent output. In this case, we'll also want to specify `inputMessagesKey` (the key to be treated as the latest input message) and `historyMessagesKey` (the key to add historical messages to). import { RunnableWithMessageHistory } from "@langchain/core/runnables";const chainWithHistory = new RunnableWithMessageHistory({ runnable: chain, getMessageHistory: (sessionId) => new UpstashRedisChatMessageHistory({ sessionId, config: { url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN!, }, }), inputMessagesKey: "question", historyMessagesKey: "history",}); Invoking with config[​](#invoking-with-config "Direct link to Invoking with config") ------------------------------------------------------------------------------------ Whenever we call our chain with message history, we need to include an additional config object that contains the `session_id` { configurable: { sessionId: "<SESSION_ID>"; }} Given the same configuration, our chain should be pulling from the same chat message history. const result = await chainWithHistory.invoke( { ability: "math", question: "What does cosine mean?", }, { configurable: { sessionId: "foobarbaz", }, });console.log(result);/* AIMessage { content: 'Cosine refers to one of the basic trigonometric functions. Specifically:\n' + '\n' + '- Cosine is one of the three main trigonometric functions, along with sine and tangent. It is often abbreviated as cos.\n' + '\n' + '- For a right triangle with sides a, b, and c (where c is the hypotenuse), cosine represents the ratio of the length of the adjacent side (a) to the length of the hypotenuse (c). So cos(A) = a/c, where A is the angle opposite side a.\n' + '\n' + '- On the Cartesian plane, cosine represents the x-coordinate of a point on the unit circle for a given angle. So if you take an angle θ on the unit circle, the cosine of θ gives you the x-coordinate of where the terminal side of that angle intersects the circle.\n' + '\n' + '- The cosine function has a periodic waveform that oscillates between 1 and -1. Its graph forms a cosine wave.\n' + '\n' + 'So in essence, cosine helps relate an angle in a right triangle to the ratio of two of its sides. Along with sine and tangent, it is foundational to trigonometry and mathematical modeling of periodic functions.', name: undefined, additional_kwargs: { id: 'msg_01QnnAkKEz7WvhJrwLWGbLBm', type: 'message', role: 'assistant', model: 'claude-3-sonnet-20240229', stop_reason: 'end_turn', stop_sequence: null } }*/const result2 = await chainWithHistory.invoke( { ability: "math", question: "What's its inverse?", }, { configurable: { sessionId: "foobarbaz", }, });console.log(result2);/* AIMessage { content: 'The inverse of the cosine function is the arcsine or inverse sine function, often written as sin−1(x) or sin^{-1}(x).\n' + '\n' + 'Some key properties of the inverse cosine function:\n' + '\n' + '- It accepts values between -1 and 1 as inputs and returns angles from 0 to π radians (0 to 180 degrees). This is the inverse of the regular cosine function, which takes angles and returns the cosine ratio.\n' + '\n' + '- It is also called cos−1(x) or cos^{-1}(x) (read as "cosine inverse of x").\n' + '\n' + '- The notation sin−1(x) is usually preferred over cos−1(x) since it relates more directly to the unit circle definition of cosine. sin−1(x) gives the angle whose sine equals x.\n' + '\n' + '- The arcsine function is one-to-one on the domain [-1, 1]. This means every output angle maps back to exactly one input ratio x. This one-to-one mapping is what makes it the mathematical inverse of cosine.\n' + '\n' + 'So in summary, arcsine or inverse sine, written as sin−1(x) or sin^{-1}(x), gives you the angle whose cosine evaluates to the input x, undoing the cosine function. It is used throughout trigonometry and calculus.', additional_kwargs: { id: 'msg_01PYRhpoUudApdJvxug6R13W', type: 'message', role: 'assistant', model: 'claude-3-sonnet-20240229', stop_reason: 'end_turn', stop_sequence: null } }*/ tip [Langsmith trace](https://smith.langchain.com/public/50377a89-d0b8-413b-8cd7-8e6618835e00/r) Looking at the Langsmith trace for the second call, we can see that when constructing the prompt, a "history" variable has been injected which is a list of two messages (our first input and first output). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to merge consecutive messages of the same type ](/v0.2/docs/how_to/merge_message_runs)[ Next How to migrate from legacy LangChain agents to LangGraph ](/v0.2/docs/how_to/migrate_agent) * [Setup](#setup) * [LangSmith](#langsmith) * [Adding message history](#adding-message-history) * [Invoking with config](#invoking-with-config)
null
https://js.langchain.com/v0.2/docs/how_to/multi_vector
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to generate multiple embeddings per document On this page How to generate multiple embeddings per document ================================================ Prerequisites This guide assumes familiarity with the following concepts: * [Retrievers](/v0.2/docs/concepts/#retrievers) * [Text splitters](/v0.2/docs/concepts/#text-splitters) * [Retrieval-augmented generation (RAG)](/v0.2/docs/tutorials/rag) Embedding different representations of an original document, then returning the original document when any of the representations result in a search hit, can allow you to tune and improve your retrieval performance. LangChain has a base [`MultiVectorRetriever`](https://v02.api.js.langchain.com/classes/langchain_retrievers_multi_vector.MultiVectorRetriever.html) designed to do just this! A lot of the complexity lies in how to create the multiple vectors per document. This guide covers some of the common ways to create those vectors and use the `MultiVectorRetriever`. Some methods to create multiple vectors per document include: * smaller chunks: split a document into smaller chunks, and embed those (e.g. the [`ParentDocumentRetriever`](/v0.2/docs/how_to/parent_document_retriever)) * summary: create a summary for each document, embed that along with (or instead of) the document * hypothetical questions: create hypothetical questions that each document would be appropriate to answer, embed those along with (or instead of) the document Note that this also enables another method of adding embeddings - manually. This is great because you can explicitly add questions or queries that should lead to a document being recovered, giving you more control. Smaller chunks[​](#smaller-chunks "Direct link to Smaller chunks") ------------------------------------------------------------------ Often times it can be useful to retrieve larger chunks of information, but embed smaller chunks. This allows for embeddings to capture the semantic meaning as closely as possible, but for as much context as possible to be passed downstream. NOTE: this is what the ParentDocumentRetriever does. Here we show what is going on under the hood. tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai @langchain/community yarn add @langchain/openai @langchain/community pnpm add @langchain/openai @langchain/community import * as uuid from "uuid";import { MultiVectorRetriever } from "langchain/retrievers/multi_vector";import { FaissStore } from "@langchain/community/vectorstores/faiss";import { OpenAIEmbeddings } from "@langchain/openai";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { InMemoryStore } from "@langchain/core/stores";import { TextLoader } from "langchain/document_loaders/fs/text";import { Document } from "@langchain/core/documents";const textLoader = new TextLoader("../examples/state_of_the_union.txt");const parentDocuments = await textLoader.load();const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 10000, chunkOverlap: 20,});const docs = await splitter.splitDocuments(parentDocuments);const idKey = "doc_id";const docIds = docs.map((_) => uuid.v4());const childSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 400, chunkOverlap: 0,});const subDocs = [];for (let i = 0; i < docs.length; i += 1) { const childDocs = await childSplitter.splitDocuments([docs[i]]); const taggedChildDocs = childDocs.map((childDoc) => { // eslint-disable-next-line no-param-reassign childDoc.metadata[idKey] = docIds[i]; return childDoc; }); subDocs.push(...taggedChildDocs);}// The byteStore to use to store the original chunksconst byteStore = new InMemoryStore<Uint8Array>();// The vectorstore to use to index the child chunksconst vectorstore = await FaissStore.fromDocuments( subDocs, new OpenAIEmbeddings());const retriever = new MultiVectorRetriever({ vectorstore, byteStore, idKey, // Optional `k` parameter to search for more child documents in VectorStore. // Note that this does not exactly correspond to the number of final (parent) documents // retrieved, as multiple child documents can point to the same parent. childK: 20, // Optional `k` parameter to limit number of final, parent documents returned from this // retriever and sent to LLM. This is an upper-bound, and the final count may be lower than this. parentK: 5,});const keyValuePairs: [string, Document][] = docs.map((originalDoc, i) => [ docIds[i], originalDoc,]);// Use the retriever to add the original chunks to the document storeawait retriever.docstore.mset(keyValuePairs);// Vectorstore alone retrieves the small chunksconst vectorstoreResult = await retriever.vectorstore.similaritySearch( "justice breyer");console.log(vectorstoreResult[0].pageContent.length);/* 390*/// Retriever returns larger resultconst retrieverResult = await retriever.invoke("justice breyer");console.log(retrieverResult[0].pageContent.length);/* 9770*/ #### API Reference: * [MultiVectorRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_multi_vector.MultiVectorRetriever.html) from `langchain/retrievers/multi_vector` * [FaissStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_faiss.FaissStore.html) from `@langchain/community/vectorstores/faiss` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [InMemoryStore](https://v02.api.js.langchain.com/classes/langchain_core_stores.InMemoryStore.html) from `@langchain/core/stores` * [TextLoader](https://v02.api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text` * [Document](https://v02.api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents` Summary[​](#summary "Direct link to Summary") --------------------------------------------- Oftentimes a summary may be able to distill more accurately what a chunk is about, leading to better retrieval. Here we show how to create summaries, and then embed those. import * as uuid from "uuid";import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";import { MultiVectorRetriever } from "langchain/retrievers/multi_vector";import { FaissStore } from "@langchain/community/vectorstores/faiss";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { InMemoryStore } from "@langchain/core/stores";import { TextLoader } from "langchain/document_loaders/fs/text";import { PromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnableSequence } from "@langchain/core/runnables";import { Document } from "@langchain/core/documents";const textLoader = new TextLoader("../examples/state_of_the_union.txt");const parentDocuments = await textLoader.load();const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 10000, chunkOverlap: 20,});const docs = await splitter.splitDocuments(parentDocuments);const chain = RunnableSequence.from([ { content: (doc: Document) => doc.pageContent }, PromptTemplate.fromTemplate(`Summarize the following document:\n\n{content}`), new ChatOpenAI({ maxRetries: 0, }), new StringOutputParser(),]);const summaries = await chain.batch(docs, { maxConcurrency: 5,});const idKey = "doc_id";const docIds = docs.map((_) => uuid.v4());const summaryDocs = summaries.map((summary, i) => { const summaryDoc = new Document({ pageContent: summary, metadata: { [idKey]: docIds[i], }, }); return summaryDoc;});// The byteStore to use to store the original chunksconst byteStore = new InMemoryStore<Uint8Array>();// The vectorstore to use to index the child chunksconst vectorstore = await FaissStore.fromDocuments( summaryDocs, new OpenAIEmbeddings());const retriever = new MultiVectorRetriever({ vectorstore, byteStore, idKey,});const keyValuePairs: [string, Document][] = docs.map((originalDoc, i) => [ docIds[i], originalDoc,]);// Use the retriever to add the original chunks to the document storeawait retriever.docstore.mset(keyValuePairs);// We could also add the original chunks to the vectorstore if we wish// const taggedOriginalDocs = docs.map((doc, i) => {// doc.metadata[idKey] = docIds[i];// return doc;// });// retriever.vectorstore.addDocuments(taggedOriginalDocs);// Vectorstore alone retrieves the small chunksconst vectorstoreResult = await retriever.vectorstore.similaritySearch( "justice breyer");console.log(vectorstoreResult[0].pageContent.length);/* 1118*/// Retriever returns larger resultconst retrieverResult = await retriever.invoke("justice breyer");console.log(retrieverResult[0].pageContent.length);/* 9770*/ #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [MultiVectorRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_multi_vector.MultiVectorRetriever.html) from `langchain/retrievers/multi_vector` * [FaissStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_faiss.FaissStore.html) from `@langchain/community/vectorstores/faiss` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [InMemoryStore](https://v02.api.js.langchain.com/classes/langchain_core_stores.InMemoryStore.html) from `@langchain/core/stores` * [TextLoader](https://v02.api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text` * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` * [StringOutputParser](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [Document](https://v02.api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents` Hypothetical queries[​](#hypothetical-queries "Direct link to Hypothetical queries") ------------------------------------------------------------------------------------ An LLM can also be used to generate a list of hypothetical questions that could be asked of a particular document. These questions can then be embedded and used to retrieve the original document: import * as uuid from "uuid";import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";import { MultiVectorRetriever } from "langchain/retrievers/multi_vector";import { FaissStore } from "@langchain/community/vectorstores/faiss";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { InMemoryStore } from "@langchain/core/stores";import { TextLoader } from "langchain/document_loaders/fs/text";import { PromptTemplate } from "@langchain/core/prompts";import { RunnableSequence } from "@langchain/core/runnables";import { Document } from "@langchain/core/documents";import { JsonKeyOutputFunctionsParser } from "@langchain/core/output_parsers/openai_functions";const textLoader = new TextLoader("../examples/state_of_the_union.txt");const parentDocuments = await textLoader.load();const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 10000, chunkOverlap: 20,});const docs = await splitter.splitDocuments(parentDocuments);const functionsSchema = [ { name: "hypothetical_questions", description: "Generate hypothetical questions", parameters: { type: "object", properties: { questions: { type: "array", items: { type: "string", }, }, }, required: ["questions"], }, },];const functionCallingModel = new ChatOpenAI({ maxRetries: 0, model: "gpt-4",}).bind({ functions: functionsSchema, function_call: { name: "hypothetical_questions" },});const chain = RunnableSequence.from([ { content: (doc: Document) => doc.pageContent }, PromptTemplate.fromTemplate( `Generate a list of 3 hypothetical questions that the below document could be used to answer:\n\n{content}` ), functionCallingModel, new JsonKeyOutputFunctionsParser<string[]>({ attrName: "questions" }),]);const hypotheticalQuestions = await chain.batch(docs, { maxConcurrency: 5,});const idKey = "doc_id";const docIds = docs.map((_) => uuid.v4());const hypotheticalQuestionDocs = hypotheticalQuestions .map((questionArray, i) => { const questionDocuments = questionArray.map((question) => { const questionDocument = new Document({ pageContent: question, metadata: { [idKey]: docIds[i], }, }); return questionDocument; }); return questionDocuments; }) .flat();// The byteStore to use to store the original chunksconst byteStore = new InMemoryStore<Uint8Array>();// The vectorstore to use to index the child chunksconst vectorstore = await FaissStore.fromDocuments( hypotheticalQuestionDocs, new OpenAIEmbeddings());const retriever = new MultiVectorRetriever({ vectorstore, byteStore, idKey,});const keyValuePairs: [string, Document][] = docs.map((originalDoc, i) => [ docIds[i], originalDoc,]);// Use the retriever to add the original chunks to the document storeawait retriever.docstore.mset(keyValuePairs);// We could also add the original chunks to the vectorstore if we wish// const taggedOriginalDocs = docs.map((doc, i) => {// doc.metadata[idKey] = docIds[i];// return doc;// });// retriever.vectorstore.addDocuments(taggedOriginalDocs);// Vectorstore alone retrieves the small chunksconst vectorstoreResult = await retriever.vectorstore.similaritySearch( "justice breyer");console.log(vectorstoreResult[0].pageContent);/* "What measures will be taken to crack down on corporations overcharging American businesses and consumers?"*/// Retriever returns larger resultconst retrieverResult = await retriever.invoke("justice breyer");console.log(retrieverResult[0].pageContent.length);/* 9770*/ #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [MultiVectorRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_multi_vector.MultiVectorRetriever.html) from `langchain/retrievers/multi_vector` * [FaissStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_faiss.FaissStore.html) from `@langchain/community/vectorstores/faiss` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [InMemoryStore](https://v02.api.js.langchain.com/classes/langchain_core_stores.InMemoryStore.html) from `@langchain/core/stores` * [TextLoader](https://v02.api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text` * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [Document](https://v02.api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents` * [JsonKeyOutputFunctionsParser](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers_openai_functions.JsonKeyOutputFunctionsParser.html) from `@langchain/core/output_parsers/openai_functions` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned a few ways to generate multiple embeddings per document. Next, check out the individual sections for deeper dives on specific retrievers, the [broader tutorial on RAG](/v0.2/docs/tutorials/rag), or this section to learn how to [create your own custom retriever over any data source](/v0.2/docs/how_to/custom_retriever/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to migrate from legacy LangChain agents to LangGraph ](/v0.2/docs/how_to/migrate_agent)[ Next How to pass multimodal data directly to models ](/v0.2/docs/how_to/multimodal_inputs) * [Smaller chunks](#smaller-chunks) * [Summary](#summary) * [Hypothetical queries](#hypothetical-queries) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/custom_chat
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to create a custom chat model class On this page How to create a custom chat model class ======================================= Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) This notebook goes over how to create a custom chat model wrapper, in case you want to use your own chat model or a different wrapper than one that is directly supported in LangChain. There are a few required things that a chat model needs to implement after extending the [`SimpleChatModel` class](https://v02.api.js.langchain.com/classes/langchain_core_language_models_chat_models.SimpleChatModel.html): * A `_call` method that takes in a list of messages and call options (which includes things like `stop` sequences), and returns a string. * A `_llmType` method that returns a string. Used for logging purposes only. You can also implement the following optional method: * A `_streamResponseChunks` method that returns an `AsyncGenerator` and yields [`ChatGenerationChunks`](https://v02.api.js.langchain.com/classes/langchain_core_outputs.ChatGenerationChunk.html). This allows the LLM to support streaming outputs. Let's implement a very simple custom chat model that just echoes back the first `n` characters of the input. import { SimpleChatModel, type BaseChatModelParams,} from "@langchain/core/language_models/chat_models";import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";import { AIMessageChunk, type BaseMessage } from "@langchain/core/messages";import { ChatGenerationChunk } from "@langchain/core/outputs";export interface CustomChatModelInput extends BaseChatModelParams { n: number;}export class CustomChatModel extends SimpleChatModel { n: number; constructor(fields: CustomChatModelInput) { super(fields); this.n = fields.n; } _llmType() { return "custom"; } async _call( messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): Promise<string> { if (!messages.length) { throw new Error("No messages provided."); } // Pass `runManager?.getChild()` when invoking internal runnables to enable tracing // await subRunnable.invoke(params, runManager?.getChild()); if (typeof messages[0].content !== "string") { throw new Error("Multimodal messages are not supported."); } return messages[0].content.slice(0, this.n); } async *_streamResponseChunks( messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): AsyncGenerator<ChatGenerationChunk> { if (!messages.length) { throw new Error("No messages provided."); } if (typeof messages[0].content !== "string") { throw new Error("Multimodal messages are not supported."); } // Pass `runManager?.getChild()` when invoking internal runnables to enable tracing // await subRunnable.invoke(params, runManager?.getChild()); for (const letter of messages[0].content.slice(0, this.n)) { yield new ChatGenerationChunk({ message: new AIMessageChunk({ content: letter, }), text: letter, }); // Trigger the appropriate callback for new chunks await runManager?.handleLLMNewToken(letter); } }} We can now use this as any other chat model: const chatModel = new CustomChatModel({ n: 4 });await chatModel.invoke([["human", "I am an LLM"]]); AIMessage { content: 'I am', additional_kwargs: {}} And support streaming: const stream = await chatModel.stream([["human", "I am an LLM"]]);for await (const chunk of stream) { console.log(chunk);} AIMessageChunk { content: 'I', additional_kwargs: {}}AIMessageChunk { content: ' ', additional_kwargs: {}}AIMessageChunk { content: 'a', additional_kwargs: {}}AIMessageChunk { content: 'm', additional_kwargs: {}} Richer outputs[​](#richer-outputs "Direct link to Richer outputs") ------------------------------------------------------------------ If you want to take advantage of LangChain's callback system for functionality like token tracking, you can extend the [`BaseChatModel`](https://v02.api.js.langchain.com/classes/langchain_core_language_models_chat_models.BaseChatModel.html) class and implement the lower level `_generate` method. It also takes a list of `BaseMessage`s as input, but requires you to construct and return a `ChatGeneration` object that permits additional metadata. Here's an example: import { AIMessage, BaseMessage } from "@langchain/core/messages";import { ChatResult } from "@langchain/core/outputs";import { BaseChatModel, BaseChatModelCallOptions, BaseChatModelParams,} from "@langchain/core/language_models/chat_models";import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";export interface AdvancedCustomChatModelOptions extends BaseChatModelCallOptions {}export interface AdvancedCustomChatModelParams extends BaseChatModelParams { n: number;}export class AdvancedCustomChatModel extends BaseChatModel<AdvancedCustomChatModelOptions> { n: number; static lc_name(): string { return "AdvancedCustomChatModel"; } constructor(fields: AdvancedCustomChatModelParams) { super(fields); this.n = fields.n; } async _generate( messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): Promise<ChatResult> { if (!messages.length) { throw new Error("No messages provided."); } if (typeof messages[0].content !== "string") { throw new Error("Multimodal messages are not supported."); } // Pass `runManager?.getChild()` when invoking internal runnables to enable tracing // await subRunnable.invoke(params, runManager?.getChild()); const content = messages[0].content.slice(0, this.n); const tokenUsage = { usedTokens: this.n, }; return { generations: [{ message: new AIMessage({ content }), text: content }], llmOutput: { tokenUsage }, }; } _llmType(): string { return "advanced_custom_chat_model"; }} This will pass the additional returned information in callback events and in the \`streamEvents method: const chatModel = new AdvancedCustomChatModel({ n: 4 });const eventStream = await chatModel.streamEvents([["human", "I am an LLM"]], { version: "v1",});for await (const event of eventStream) { if (event.event === "on_llm_end") { console.log(JSON.stringify(event, null, 2)); }} { "event": "on_llm_end", "name": "AdvancedCustomChatModel", "run_id": "b500b98d-bee5-4805-9b92-532a491f5c70", "tags": [], "metadata": {}, "data": { "output": { "generations": [ [ { "message": { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessage" ], "kwargs": { "content": "I am", "additional_kwargs": {} } }, "text": "I am" } ] ], "llmOutput": { "tokenUsage": { "usedTokens": 4 } } } }} Tracing (advanced)[​](#tracing-advanced "Direct link to Tracing (advanced)") ---------------------------------------------------------------------------- If you are implementing a custom chat model and want to use it with a tracing service like [LangSmith](https://smith.langchain.com/), you can automatically log params used for a given invocation by implementing the `invocationParams()` method on the model. This method is purely optional, but anything it returns will be logged as metadata for the trace. Here's one pattern you might use: export interface CustomChatModelOptions extends BaseChatModelCallOptions { // Some required or optional inner args tools: Record<string, any>[];}export interface CustomChatModelParams extends BaseChatModelParams { temperature: number;}export class CustomChatModel extends BaseChatModel<CustomChatModelOptions> { temperature: number; static lc_name(): string { return "CustomChatModel"; } constructor(fields: CustomChatModelParams) { super(fields); this.temperature = fields.temperature; } // Anything returned in this method will be logged as metadata in the trace. // It is common to pass it any options used to invoke the function. invocationParams(options?: this["ParsedCallOptions"]) { return { tools: options?.tools, n: this.n, }; } async _generate( messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): Promise<ChatResult> { if (!messages.length) { throw new Error("No messages provided."); } if (typeof messages[0].content !== "string") { throw new Error("Multimodal messages are not supported."); } const additionalParams = this.invocationParams(options); const content = await someAPIRequest(messages, additionalParams); return { generations: [{ message: new AIMessage({ content }), text: content }], llmOutput: {}, }; } _llmType(): string { return "advanced_custom_chat_model"; }} * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to add ad-hoc tool calling capability to LLMs and Chat Models ](/v0.2/docs/how_to/tools_prompting)[ Next How to do per-user retrieval ](/v0.2/docs/how_to/qa_per_user) * [Richer outputs](#richer-outputs) * [Tracing (advanced)](#tracing-advanced)
null
https://js.langchain.com/v0.2/docs/how_to/qa_sources
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to return sources On this page How to return sources ===================== Prerequisites This guide assumes familiarity with the following: * [Retrieval-augmented generation](/v0.2/docs/tutorials/rag/) Often in Q&A applications it’s important to show users the sources that were used to generate the answer. The simplest way to do this is for the chain to return the Documents that were retrieved in each generation. We’ll be using the [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) blog post by Lilian Weng for retrieval content this notebook. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Dependencies[​](#dependencies "Direct link to Dependencies") We’ll use an OpenAI chat model and embeddings and a Memory vector store in this walkthrough, but everything shown here works with any [ChatModel](/v0.2/docs/concepts/#chat-models) or [LLM](/v0.2/docs/concepts#llms), [Embeddings](/v0.2/docs/concepts#embedding-models), and [VectorStore](/v0.2/docs/concepts#vectorstores) or [Retriever](/v0.2/docs/concepts#retrievers). We’ll use the following packages: npm install --save langchain @langchain/openai cheerio We need to set environment variable `OPENAI_API_KEY`: export OPENAI_API_KEY=YOUR_KEY ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com/). Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=YOUR_KEY Chain without sources[​](#chain-without-sources "Direct link to Chain without sources") --------------------------------------------------------------------------------------- Here is the Q&A app we built over the [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) blog post by Lilian Weng in the [Quickstart](/v0.2/docs/tutorials/qa_chat_history/). import "cheerio";import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { pull } from "langchain/hub";import { ChatPromptTemplate } from "@langchain/core/prompts";import { formatDocumentsAsString } from "langchain/util/document";import { RunnableSequence, RunnablePassthrough,} from "@langchain/core/runnables";import { StringOutputParser } from "@langchain/core/output_parsers";const loader = new CheerioWebBaseLoader( "https://lilianweng.github.io/posts/2023-06-23-agent/");const docs = await loader.load();const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const splits = await textSplitter.splitDocuments(docs);const vectorStore = await MemoryVectorStore.fromDocuments( splits, new OpenAIEmbeddings());// Retrieve and generate using the relevant snippets of the blog.const retriever = vectorStore.asRetriever();const prompt = await pull<ChatPromptTemplate>("rlm/rag-prompt");const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const ragChain = RunnableSequence.from([ { context: retriever.pipe(formatDocumentsAsString), question: new RunnablePassthrough(), }, prompt, llm, new StringOutputParser(),]); Let’s see what this prompt actually looks like: console.log(prompt.promptMessages.map((msg) => msg.prompt.template).join("\n")); You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.Question: {question}Context: {context}Answer: await ragChain.invoke("What is task decomposition?"); "Task decomposition is a technique used to break down complex tasks into smaller and simpler steps. T"... 254 more characters Adding sources[​](#adding-sources "Direct link to Adding sources") ------------------------------------------------------------------ With LCEL, we can easily pass the retrieved documents through the chain and return them in the final response: import { RunnableMap, RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { formatDocumentsAsString } from "langchain/util/document";const ragChainWithSources = RunnableMap.from({ // Return raw documents here for now since we want to return them at // the end - we'll format in the next step of the chain context: retriever, question: new RunnablePassthrough(),}).assign({ answer: RunnableSequence.from([ (input) => { return { // Now we format the documents as strings for the prompt context: formatDocumentsAsString(input.context), question: input.question, }; }, prompt, llm, new StringOutputParser(), ]),});await ragChainWithSources.invoke("What is Task Decomposition"); { question: "What is Task Decomposition", context: [ Document { pageContent: "Fig. 1. Overview of a LLM-powered autonomous agent system.\n" + "Component One: Planning#\n" + "A complicated ta"... 898 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: 'Task decomposition can be done (1) by LLM with simple prompting like "Steps for XYZ.\\n1.", "What are'... 887 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: "Agent System Overview\n" + " \n" + " Component One: Planning\n" + " "... 850 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: "Resources:\n" + "1. Internet access for searches and information gathering.\n" + "2. Long Term memory management"... 456 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } } ], answer: "Task decomposition is a technique used to break down complex tasks into smaller and simpler steps fo"... 230 more characters} Check out the [LangSmith trace](https://smith.langchain.com/public/c3753531-563c-40d4-a6bf-21bfe8741d10/r) here to see the internals of the chain. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to return sources from your QA chains. Next, check out some of the other guides around RAG, such as [how to stream responses](/v0.2/docs/how_to/qa_streaming). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to return citations ](/v0.2/docs/how_to/qa_citations)[ Next How to stream from a question-answering chain ](/v0.2/docs/how_to/qa_streaming) * [Setup](#setup) * [Dependencies](#dependencies) * [LangSmith](#langsmith) * [Chain without sources](#chain-without-sources) * [Adding sources](#adding-sources) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/multimodal_inputs
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to pass multimodal data directly to models On this page How to pass multimodal data directly to models ============================================== Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) Here we demonstrate how to pass multimodal input directly to models. We currently expect all input to be passed in the same format as [OpenAI expects](https://platform.openai.com/docs/guides/vision). For other model providers that support multimodal input, we have added logic inside the class to convert to the expected format. In this example we will ask a model to describe an image. import * as fs from "node:fs/promises";import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229",});const imageData = await fs.readFile("../../../../examples/hotdog.jpg"); The most commonly supported way to pass in images is to pass it in as a byte string within a message with a complex content type for models that support multimodal input. Here’s an example: import { HumanMessage } from "@langchain/core/messages";const message = new HumanMessage({ content: [ { type: "text", text: "what does this image contain?", }, { type: "image_url", image_url: { url: `data:image/jpeg;base64,${imageData.toString("base64")}`, }, }, ],});const response = await model.invoke([message]);console.log(response.content); This image contains a hot dog. It shows a frankfurter or sausage encased in a soft, elongated bread bun. The sausage itself appears to be reddish in color, likely a smoked or cured variety. The bun is a golden-brown color, suggesting it has been lightly toasted or grilled. The hot dog is presented against a plain white background, allowing the details of the iconic American fast food item to be clearly visible. Some model providers support taking an HTTP URL to the image directly in a content block of type `"image_url"`: import { ChatOpenAI } from "@langchain/openai";const openAIModel = new ChatOpenAI({ model: "gpt-4o",});const imageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg";const message = new HumanMessage({ content: [ { type: "text", text: "describe the weather in this image", }, { type: "image_url", image_url: { url: imageUrl }, }, ],});const response = await openAIModel.invoke([message]);console.log(response.content); The weather in the image appears to be pleasant and clear. The sky is mostly blue with a few scattered clouds, indicating good visibility and no immediate signs of rain. The lighting suggests it’s either morning or late afternoon, with sunlight creating a warm and bright atmosphere. There is no indication of strong winds, as the grass and foliage appear calm and undisturbed. Overall, it looks like a beautiful day, possibly spring or summer, ideal for outdoor activities. We can also pass in multiple images. const message = new HumanMessage({ content: [ { type: "text", text: "are these two images the same?", }, { type: "image_url", image_url: { url: imageUrl, }, }, { type: "image_url", image_url: { url: imageUrl, }, }, ],});const response = await openAIModel.invoke([message]);console.log(response.content); Yes, the two images are the same. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to pass multimodal data to a modal. Next, you can check out our guide on [multimodal tool calls](/v0.2/docs/how_to/tool_calls_multimodal). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to generate multiple embeddings per document ](/v0.2/docs/how_to/multi_vector)[ Next How to use multimodal prompts ](/v0.2/docs/how_to/multimodal_prompts) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/multimodal_prompts
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use multimodal prompts How to use multimodal prompts ============================= Here we demonstrate how to use prompt templates to format multimodal inputs to models. In this example we will ask a model to describe an image. Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) * [LangChain Tools](/v0.2/docs/concepts/#tools) * npm * yarn * pnpm npm i axios @langchain/core @langchain/openai yarn add axios @langchain/core @langchain/openai pnpm add axios @langchain/core @langchain/openai import axios from "axios";const imageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg";const axiosRes = await axios.get(imageUrl, { responseType: "arraybuffer" });const base64 = btoa( new Uint8Array(axiosRes.data).reduce( (data, byte) => data + String.fromCharCode(byte), "" )); import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-4o" }); const prompt = ChatPromptTemplate.fromMessages([ ["system", "Describe the image provided"], [ "user", [{ type: "image_url", image_url: "data:image/jpeg;base64,{base64}" }], ],]); const chain = prompt.pipe(model); const response = await chain.invoke({ base64 });console.log(response.content); The image depicts a scenic outdoor landscape featuring a wooden boardwalk path extending forward through a large field of green grass and vegetation. On either side of the path, the grass is lush and vibrant, with a variety of bushes and low shrubs visible as well. The sky overhead is expansive and mostly clear, adorned with soft, wispy clouds, illuminated by the light giving a warm and serene ambiance. In the distant background, there are clusters of trees and additional foliage, suggesting a natural and tranquil setting, ideal for a peaceful walk or nature exploration. We can also pass in multiple images. const prompt = ChatPromptTemplate.fromMessages([ ["system", "compare the two pictures provided"], [ "user", [ { type: "image_url", image_url: "data:image/jpeg;base64,{imageData1}", }, { type: "image_url", image_url: "data:image/jpeg;base64,{imageData2}", }, ], ],]); const chain = prompt.pipe(model); const response = await chain.invoke({ imageData1: base64, imageData2: base64 });console.log(response.content); The two images provided are identical. Both show a wooden boardwalk path extending into a grassy field under a blue sky with scattered clouds. The scenery includes green shrubs and trees in the background, with a bright and clear sky above. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to pass multimodal data directly to models ](/v0.2/docs/how_to/multimodal_inputs)[ Next How to generate multiple queries to retrieve data for ](/v0.2/docs/how_to/multiple_queries)
null
https://js.langchain.com/v0.2/docs/community
Community navigator =================== Hi! Thanks for being here. We're lucky to have a community of so many passionate developers building with LangChain–we have so much to teach and learn from each other. Community members contribute code, host meetups, write blog posts, amplify each other's work, become each other's customers and collaborators, and so much more. Whether you're new to LangChain, looking to go deeper, or just want to get more exposure to the world of building with LLMs, this page can point you in the right direction. * **🦜 Contribute to LangChain** * **🌍 Meetups, Events, and Hackathons** * **📣 Help Us Amplify Your Work** * **💬 Stay in the loop** 🦜 Contribute to LangChain ========================== LangChain is the product of over 5,000+ contributions by 1,500+ contributors, and there is **still** so much to do together. Here are some ways to get involved: * **[Open a pull request](https://github.com/langchain-ai/langchainjs/issues):** we'd appreciate all forms of contributions–new features, infrastructure improvements, better documentation, bug fixes, etc. If you have an improvement or an idea, we'd love to work on it with you. * **[Read our contributor guidelines:](https://github.com/langchain-ai/langchainjs/blob/main/CONTRIBUTING.md)** We ask contributors to follow a ["fork and pull request"](https://docs.github.com/en/get-started/quickstart/contributing-to-projects) workflow, run a few local checks for formatting, linting, and testing before submitting, and follow certain documentation and testing conventions. * **Become an expert:** our experts help the community by answering product questions in Discord. If that's a role you'd like to play, we'd be so grateful! (And we have some special experts-only goodies/perks we can tell you more about). Send us an email to introduce yourself at [[email protected]](mailto:[email protected]) and we'll take it from there! * **Integrate with LangChain:** if your product integrates with LangChain–or aspires to–we want to help make sure the experience is as smooth as possible for you and end users. Send us an email at [[email protected]](mailto:[email protected]) and tell us what you're working on. * **Become an Integration Maintainer:** Partner with our team to ensure your integration stays up-to-date and talk directly with users (and answer their inquiries) in our Discord. Introduce yourself at [[email protected]](mailto:[email protected]) if you'd like to explore this role. 🌍 Meetups, Events, and Hackathons ================================== One of our favorite things about working in AI is how much enthusiasm there is for building together. We want to help make that as easy and impactful for you as possible! * **Find a meetup, hackathon, or webinar:** you can find the one for you on on our [global events calendar](https://mirror-feeling-d80.notion.site/0bc81da76a184297b86ca8fc782ee9a3?v=0d80342540df465396546976a50cfb3f). * **Submit an event to our calendar:** email us at [[email protected]](mailto:[email protected]) with a link to your event page! We can also help you spread the word with our local communities. * **Host a meetup:** If you want to bring a group of builders together, we want to help! We can publicize your event on our event calendar/Twitter, share with our local communities in Discord, send swag, or potentially hook you up with a sponsor. Email us at [[email protected]](mailto:[email protected]) to tell us about your event! * **Become a meetup sponsor:** we often hear from groups of builders that want to get together, but are blocked or limited on some dimension (space to host, budget for snacks, prizes to distribute, etc.). If you'd like to help, send us an email to [[email protected]](mailto:[email protected]) we can share more about how it works! * **Speak at an event:** meetup hosts are always looking for great speakers, presenters, and panelists. If you'd like to do that at an event, send us an email to [[email protected]](mailto:[email protected]) with more information about yourself, what you want to talk about, and what city you're based in and we'll try to match you with an upcoming event! * **Tell us about your LLM community:** If you host or participate in a community that would welcome support from LangChain and/or our team, send us an email at [[email protected]](mailto:[email protected]) and let us know how we can help. 📣 Help Us Amplify Your Work ============================ If you're working on something you're proud of, and think the LangChain community would benefit from knowing about it, we want to help you show it off. * **Post about your work and mention us:** we love hanging out on Twitter to see what people in the space are talking about and working on. If you tag [@langchainai](https://twitter.com/LangChainAI), we'll almost certainly see it and can show you some love. * **Publish something on our blog:** if you're writing about your experience building with LangChain, we'd love to post (or crosspost) it on our blog! E-mail [[email protected]](mailto:[email protected]) with a draft of your post! Or even an idea for something you want to write about. * **Get your product onto our [integrations hub](https://integrations.langchain.com/):** Many developers take advantage of our seamless integrations with other products, and come to our integrations hub to find out who those are. If you want to get your product up there, tell us about it (and how it works with LangChain) at [[email protected]](mailto:[email protected]). ☀️ Stay in the loop =================== Here's where our team hangs out, talks shop, spotlights cool work, and shares what we're up to. We'd love to see you there too. * **[Twitter](https://twitter.com/LangChainAI):** we post about what we're working on and what cool things we're seeing in the space. If you tag @langchainai in your post, we'll almost certainly see it, and can snow you some love! * **[Discord](https://discord.gg/6adMQxSpJS):** connect with with >30k developers who are building with LangChain * **[GitHub](https://github.com/langchain-ai/langchainjs):** open pull requests, contribute to a discussion, and/or contribute * **[Subscribe to our bi-weekly Release Notes](https://6w1pwbss0py.typeform.com/to/KjZB1auB):** a twice/month email roundup of the coolest things going on in our orbit * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E).
null
https://js.langchain.com/v0.2/docs/additional_resources/tutorials
On this page Tutorials ========= Below are links to tutorials and courses on LangChain.js. For written guides on common use cases for LangChain.js, check out the [tutorials](/v0.2/docs/tutorials/) and [how to](/v0.2/docs/how_to/) sections. * * * Deeplearning.ai[​](#deeplearningai "Direct link to Deeplearning.ai") -------------------------------------------------------------------- We've partnered with [Deeplearning.ai](https://deeplearning.ai) and [Andrew Ng](https://en.wikipedia.org/wiki/Andrew_Ng) on a LangChain.js short course. It covers LCEL and other building blocks you can combine to build more complex chains, as well as fundamentals around loading data for retrieval augmented generation (RAG). Try it for free below: * [Build LLM Apps with LangChain.js](https://www.deeplearning.ai/short-courses/build-llm-apps-with-langchain-js) Scrimba interactive guides[​](#scrimba-interactive-guides "Direct link to Scrimba interactive guides") ------------------------------------------------------------------------------------------------------ [Scrimba](https://scrimba.com) is a code-learning platform that allows you to interactively edit and run code while watching a video walkthrough. We've partnered with Scrimba on course materials (called "scrims") that teach the fundamentals of building with LangChain.js - check them out below, and check back for more as they become available! ### Learn LangChain.js[​](#learn-langchainjs "Direct link to Learn LangChain.js") * [Learn LangChain.js on Scrimba](https://scrimba.com/learn/langchain) An full end-to-end course that walks through how to build a chatbot that can answer questions about a provided document. A great introduction to LangChain and a great first project for learning how to use LangChain Expression Language primitives to perform retrieval! ### LangChain Expression Language (LCEL)[​](#langchain-expression-language-lcel "Direct link to LangChain Expression Language (LCEL)") * [The basics (PromptTemplate + LLM)](https://scrimba.com/scrim/c6rD6Nt9) * [Adding an output parser](https://scrimba.com/scrim/co6ae44248eacc1abd87ae3dc) * [Attaching function calls to a model](https://scrimba.com/scrim/cof5449f5bc972f8c90be6a82) * [Composing multiple chains](https://scrimba.com/scrim/co14344c29595bfb29c41f12a) * [Retrieval chains](https://scrimba.com/scrim/co0e040d09941b4000244db46) * [Conversational retrieval chains ("Chat with Docs")](https://scrimba.com/scrim/co3ed4a9eb4c6c6d0361a507c) ### Deeper dives[​](#deeper-dives "Direct link to Deeper dives") * [Setting up a new `PromptTemplate`](https://scrimba.com/scrim/cbGwRwuV) * [Setting up `ChatOpenAI` parameters](https://scrimba.com/scrim/cEgbBBUw) * [Attaching stop sequences](https://scrimba.com/scrim/co9704e389428fe2193eb955c) Neo4j GraphAcademy[​](#neo4j-graphacademy "Direct link to Neo4j GraphAcademy") ------------------------------------------------------------------------------ [Neo4j](https://neo4j.com) has put together a hands-on, practical course that shows how to build a movie-recommending chatbot in Next.js. It covers retrieval-augmented generation (RAG), tracking history, and more. Check it out below: * [Build a Neo4j-backed Chatbot with TypeScript](https://graphacademy.neo4j.com/courses/llm-chatbot-typescript/?ref=langchainjs) LangChain.js x AI SDK[​](#langchainjs-x-ai-sdk "Direct link to LangChain.js x AI SDK") -------------------------------------------------------------------------------------- How to use LangChain.js with AI SDK and React Server Components. * [Streaming agentic data to the client](https://github.com/langchain-ai/langchain-nextjs-template/blob/main/app/ai_sdk/agent/README.md) * [Streaming tool responses to the client](https://github.com/langchain-ai/langchain-nextjs-template/blob/main/app/ai_sdk/tools/README.md) * * * * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). * [Deeplearning.ai](#deeplearningai) * [Scrimba interactive guides](#scrimba-interactive-guides) * [Learn LangChain.js](#learn-langchainjs) * [LangChain Expression Language (LCEL)](#langchain-expression-language-lcel) * [Deeper dives](#deeper-dives) * [Neo4j GraphAcademy](#neo4j-graphacademy) * [LangChain.js x AI SDK](#langchainjs-x-ai-sdk)
null
https://js.langchain.com/v0.2/docs/how_to/qa_per_user
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to do per-user retrieval On this page How to do per-user retrieval ============================ Prerequisites This guide assumes familiarity with the following: * [Retrieval-augmented generation](/v0.2/docs/tutorials/rag/) When building a retrieval app, you often have to build it with multiple users in mind. This means that you may be storing data not just for one user, but for many different users, and they should not be able to see each other’s data. This means that you need to be able to configure your retrieval chain to only retrieve certain information. This generally involves two steps. **Step 1: Make sure the retriever you are using supports multiple users** At the moment, there is no unified flag or filter for this in LangChain. Rather, each vectorstore and retriever may have their own, and may be called different things (namespaces, multi-tenancy, etc). For vectorstores, this is generally exposed as a keyword argument that is passed in during `similaritySearch`. By reading the documentation or source code, figure out whether the retriever you are using supports multiple users, and, if so, how to use it. **Step 2: Add that parameter as a configurable field for the chain** The LangChain `config` object is passed through to every Runnable. Here you can add any fields you’d like to the `configurable` object. Later, inside the chain we can extract these fields. **Step 3: Call the chain with that configurable field** Now, at runtime you can call this chain with configurable field. Code Example[​](#code-example "Direct link to Code Example") ------------------------------------------------------------ Let’s see a concrete example of what this looks like in code. We will use Pinecone for this example. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/pinecone @langchain/openai @pinecone-database/pinecone @langchain/core yarn add @langchain/pinecone @langchain/openai @pinecone-database/pinecone @langchain/core pnpm add @langchain/pinecone @langchain/openai @pinecone-database/pinecone @langchain/core ### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") We’ll use OpenAI and Pinecone in this example: OPENAI_API_KEY=your-api-keyPINECONE_API_KEY=your-api-keyPINECONE_INDEX=your-index-name# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true import { OpenAIEmbeddings } from "@langchain/openai";import { PineconeStore } from "@langchain/pinecone";import { Pinecone } from "@pinecone-database/pinecone";import { Document } from "@langchain/core/documents";const embeddings = new OpenAIEmbeddings();const pinecone = new Pinecone();const pineconeIndex = pinecone.Index(Deno.env.get("PINECONE_INDEX"));const vectorStore = await PineconeStore.fromExistingIndex( new OpenAIEmbeddings(), { pineconeIndex });await vectorStore.addDocuments( [new Document({ pageContent: "i worked at kensho" })], { namespace: "harrison" });await vectorStore.addDocuments( [new Document({ pageContent: "i worked at facebook" })], { namespace: "ankush" }); [ "77b8f174-9d89-4c6c-b2ab-607fe3913b2d" ] The pinecone kwarg for `namespace` can be used to separate documents // This will only get documents for Ankushconst ankushRetriever = vectorStore.asRetriever({ filter: { namespace: "ankush", },});await ankushRetriever.invoke("where did i work?"); [ Document { pageContent: "i worked at facebook", metadata: {} } ] // This will only get documents for Harrisonconst harrisonRetriever = vectorStore.asRetriever({ filter: { namespace: "harrison", },});await harrisonRetriever.invoke("where did i work?"); [ Document { pageContent: "i worked at kensho", metadata: {} } ] We can now create the chain that we will use to perform question-answering. import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnableBinding, RunnableLambda, RunnablePassthrough,} from "@langchain/core/runnables";import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";const template = `Answer the question based only on the following context:{context}Question: {question}`;const prompt = ChatPromptTemplate.fromTemplate(template);const model = new ChatOpenAI({ model: "gpt-3.5-turbo-0125", temperature: 0,}); We can now create the chain using our configurable retriever. It is configurable because we can define any object which will be passed to the chain. From there, we extract the configurable object and pass it to the vectorstore. import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";const chain = RunnableSequence.from([ RunnablePassthrough.assign({ context: async (input, config) => { if (!config || !("configurable" in config)) { throw new Error("No config"); } const { configurable } = config; const documents = await vectorStore .asRetriever(configurable) .invoke(input.question, config); return documents.map((doc) => doc.pageContent).join("\n\n"); }, }), prompt, model, new StringOutputParser(),]); We can now invoke the chain with configurable options. `search_kwargs` is the id of the configurable field. The value is the search kwargs to use for Pinecone await chain.invoke( { question: "where did the user work?" }, { configurable: { filter: { namespace: "harrison" } } }); "The user worked at Kensho." await chain.invoke( { question: "where did the user work?" }, { configurable: { filter: { namespace: "ankush" } } }); "The user worked at Facebook." For more vector store implementations that can support multiple users, please refer to specific pages, such as [Milvus](/v0.2/docs/integrations/vectorstores/milvus). Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now seen one approach for supporting retrieval with data from multiple users. Next, check out some of the other how-to guides on RAG, such as [returning sources](/v0.2/docs/how_to/qa_sources). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to create a custom chat model class ](/v0.2/docs/how_to/custom_chat)[ Next How to track token usage ](/v0.2/docs/how_to/chat_token_usage_tracking) * [Code Example](#code-example) * [Setup](#setup) * [Install dependencies](#install-dependencies) * [Set environment variables](#set-environment-variables) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/contributing
* [](/v0.2/) * Contributing * Welcome Contributors On this page Welcome Contributors ==================== Hi there! Thank you for even being interested in contributing to LangChain. As an open-source project in a rapidly developing field, we are extremely open to contributions, whether they involve new features, improved infrastructure, better documentation, or bug fixes. 🗺️ Guidelines[​](#️-guidelines "Direct link to 🗺️ Guidelines") ---------------------------------------------------------------- ### 👩‍💻 Ways to contribute[​](#-ways-to-contribute "Direct link to 👩‍💻 Ways to contribute") There are many ways to contribute to LangChain. Here are some common ways people contribute: * [**Documentation**](/v0.2/docs/contributing/documentation/style_guide): Help improve our docs, including this one! * [**Code**](/v0.2/docs/contributing/code): Help us write code, fix bugs, or improve our infrastructure. * [**Integrations**](/v0.2/docs/contributing/integrations): Help us integrate with your favorite vendors and tools. * [**Discussions**](https://github.com/langchain-ai/langchainjs/discussions): Help answer usage questions and discuss issues with users. ### 🚩 GitHub Issues[​](#-github-issues "Direct link to 🚩 GitHub Issues") Our [issues](https://github.com/langchain-ai/langchainjs/issues) page is kept up to date with bugs, improvements, and feature requests. There is a taxonomy of labels to help with sorting and discovery of issues of interest. Please use these to help organize issues. If you start working on an issue, please assign it to yourself. If you are adding an issue, please try to keep it focused on a single, modular bug/improvement/feature. If two issues are related, or blocking, please link them rather than combining them. We will try to keep these issues as up-to-date as possible, though with the rapid rate of development in this field some may get out of date. If you notice this happening, please let us know. ### 💭 GitHub Discussions[​](#-github-discussions "Direct link to 💭 GitHub Discussions") We have a [discussions](https://github.com/langchain-ai/langchainjs/discussions) page where users can ask usage questions, discuss design decisions, and propose new features. If you are able to help answer questions, please do so! This will allow the maintainers to spend more time focused on development and bug fixing. ### 🙋 Getting Help[​](#-getting-help "Direct link to 🙋 Getting Help") Our goal is to have the simplest developer setup possible. Should you experience any difficulty getting setup, please contact a maintainer! Not only do we want to help get you unblocked, but we also want to make sure that the process is smooth for future contributors. In a similar vein, we do enforce certain linting, formatting, and documentation standards in the codebase. If you are finding these difficult (or even just annoying) to work with, feel free to contact a maintainer for help - we do not want these to get in the way of getting good code into the codebase. 🌟 Recognition ============== If your contribution has made its way into a release, we will want to give you credit on Twitter (only if you want though)! If you have a Twitter account you would like us to mention, please let us know in the PR or through another means. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Next Repository Structure ](/v0.2/docs/contributing/repo_structure) * [🗺️ Guidelines](#️-guidelines) * [👩‍💻 Ways to contribute](#-ways-to-contribute) * [🚩 GitHub Issues](#-github-issues) * [💭 GitHub Discussions](#-github-discussions) * [🙋 Getting Help](#-getting-help)
null
https://js.langchain.com/v0.2/docs/how_to/qa_streaming
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to stream from a question-answering chain On this page How to stream from a question-answering chain ============================================= Prerequisites This guide assumes familiarity with the following: * [Retrieval-augmented generation](/v0.2/docs/tutorials/rag/) Often in Q&A applications it’s important to show users the sources that were used to generate the answer. The simplest way to do this is for the chain to return the Documents that were retrieved in each generation. We’ll be using the [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) blog post by Lilian Weng for retrieval content this notebook. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Dependencies[​](#dependencies "Direct link to Dependencies") We’ll use an OpenAI chat model and embeddings and a Memory vector store in this walkthrough, but everything shown here works with any [ChatModel](/v0.2/docs/concepts/#chat-models) or [LLM](/v0.2/docs/concepts#llms), [Embeddings](/v0.2/docs/concepts#embedding-models), and [VectorStore](/v0.2/docs/concepts#vectorstores) or [Retriever](/v0.2/docs/concepts#retrievers). We’ll use the following packages: npm install --save langchain @langchain/openai cheerio We need to set environment variable `OPENAI_API_KEY`: export OPENAI_API_KEY=YOUR_KEY ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com/). Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=YOUR_KEY Chain with sources[​](#chain-with-sources "Direct link to Chain with sources") ------------------------------------------------------------------------------ Here is Q&A app with sources we built over the [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) blog post by Lilian Weng in the [Returning sources](/v0.2/docs/how_to/qa_sources/) guide: import "cheerio";import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { pull } from "langchain/hub";import { ChatPromptTemplate } from "@langchain/core/prompts";import { formatDocumentsAsString } from "langchain/util/document";import { RunnableSequence, RunnablePassthrough, RunnableMap,} from "@langchain/core/runnables";import { StringOutputParser } from "@langchain/core/output_parsers";const loader = new CheerioWebBaseLoader( "https://lilianweng.github.io/posts/2023-06-23-agent/");const docs = await loader.load();const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const splits = await textSplitter.splitDocuments(docs);const vectorStore = await MemoryVectorStore.fromDocuments( splits, new OpenAIEmbeddings());// Retrieve and generate using the relevant snippets of the blog.const retriever = vectorStore.asRetriever();const prompt = await pull<ChatPromptTemplate>("rlm/rag-prompt");const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const ragChainFromDocs = RunnableSequence.from([ RunnablePassthrough.assign({ context: (input) => formatDocumentsAsString(input.context), }), prompt, llm, new StringOutputParser(),]);let ragChainWithSource = new RunnableMap({ steps: { context: retriever, question: new RunnablePassthrough() },});ragChainWithSource = ragChainWithSource.assign({ answer: ragChainFromDocs });await ragChainWithSource.invoke("What is Task Decomposition"); { question: "What is Task Decomposition", context: [ Document { pageContent: "Fig. 1. Overview of a LLM-powered autonomous agent system.\n" + "Component One: Planning#\n" + "A complicated ta"... 898 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: 'Task decomposition can be done (1) by LLM with simple prompting like "Steps for XYZ.\\n1.", "What are'... 887 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: "Agent System Overview\n" + " \n" + " Component One: Planning\n" + " "... 850 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: "Resources:\n" + "1. Internet access for searches and information gathering.\n" + "2. Long Term memory management"... 456 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } } ], answer: "Task decomposition is a technique used to break down complex tasks into smaller and simpler steps fo"... 230 more characters} Let’s see what this prompt actually looks like. You can also view it [in the LangChain prompt hub](https://smith.langchain.com/hub/rlm/rag-prompt): console.log(prompt.promptMessages.map((msg) => msg.prompt.template).join("\n")); You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.Question: {question}Context: {context}Answer: Streaming final outputs[​](#streaming-final-outputs "Direct link to Streaming final outputs") --------------------------------------------------------------------------------------------- With [LCEL](/v0.2/docs/concepts#langchain-expression-language), we can stream outputs as they are generated: for await (const chunk of await ragChainWithSource.stream( "What is task decomposition?")) { console.log(chunk);} { question: "What is task decomposition?" }{ context: [ Document { pageContent: "Fig. 1. Overview of a LLM-powered autonomous agent system.\n" + "Component One: Planning#\n" + "A complicated ta"... 898 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: 'Task decomposition can be done (1) by LLM with simple prompting like "Steps for XYZ.\\n1.", "What are'... 887 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: "Agent System Overview\n" + " \n" + " Component One: Planning\n" + " "... 850 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } }, Document { pageContent: "(3) Task execution: Expert models execute on the specific tasks and log results.\n" + "Instruction:\n" + "\n" + "With "... 539 more characters, metadata: { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: [Object] } } } ]}{ answer: "" }{ answer: "Task" }{ answer: " decomposition" }{ answer: " is" }{ answer: " a" }{ answer: " technique" }{ answer: " used" }{ answer: " to" }{ answer: " break" }{ answer: " down" }{ answer: " complex" }{ answer: " tasks" }{ answer: " into" }{ answer: " smaller" }{ answer: " and" }{ answer: " simpler" }{ answer: " steps" }{ answer: "." }{ answer: " It" }{ answer: " can" }{ answer: " be" }{ answer: " done" }{ answer: " through" }{ answer: " various" }{ answer: " methods" }{ answer: " such" }{ answer: " as" }{ answer: " using" }{ answer: " prompting" }{ answer: " techniques" }{ answer: "," }{ answer: " task" }{ answer: "-specific" }{ answer: " instructions" }{ answer: "," }{ answer: " or" }{ answer: " human" }{ answer: " inputs" }{ answer: "." }{ answer: " Another" }{ answer: " approach" }{ answer: " involves" }{ answer: " outsourcing" }{ answer: " the" }{ answer: " planning" }{ answer: " step" }{ answer: " to" }{ answer: " an" }{ answer: " external" }{ answer: " classical" }{ answer: " planner" }{ answer: "." }{ answer: "" } We can add some logic to compile our stream as it’s being returned: const output = {};let currentKey: string | null = null;for await (const chunk of await ragChainWithSource.stream( "What is task decomposition?")) { for (const key of Object.keys(chunk)) { if (output[key] === undefined) { output[key] = chunk[key]; } else { output[key] += chunk[key]; } if (key !== currentKey) { console.log(`\n\n${key}: ${JSON.stringify(chunk[key])}`); } else { console.log(chunk[key]); } currentKey = key; }} question: "What is task decomposition?"context: [{"pageContent":"Fig. 1. Overview of a LLM-powered autonomous agent system.\nComponent One: Planning#\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.\nTask Decomposition#\nChain of thought (CoT; Wei et al. 2022) has become a standard prompting technique for enhancing model performance on complex tasks. The model is instructed to “think step by step” to utilize more test-time computation to decompose hard tasks into smaller and simpler steps. CoT transforms big tasks into multiple manageable tasks and shed lights into an interpretation of the model’s thinking process.\nTree of Thoughts (Yao et al. 2023) extends CoT by exploring multiple reasoning possibilities at each step. It first decomposes the problem into multiple thought steps and generates multiple thoughts per step, creating a tree structure. The search process can be BFS (breadth-first search) or DFS (depth-first search) with each state evaluated by a classifier (via a prompt) or majority vote.","metadata":{"source":"https://lilianweng.github.io/posts/2023-06-23-agent/","loc":{"lines":{"from":176,"to":181}}}},{"pageContent":"Task decomposition can be done (1) by LLM with simple prompting like \"Steps for XYZ.\\n1.\", \"What are the subgoals for achieving XYZ?\", (2) by using task-specific instructions; e.g. \"Write a story outline.\" for writing a novel, or (3) with human inputs.\nAnother quite distinct approach, LLM+P (Liu et al. 2023), involves relying on an external classical planner to do long-horizon planning. This approach utilizes the Planning Domain Definition Language (PDDL) as an intermediate interface to describe the planning problem. In this process, LLM (1) translates the problem into “Problem PDDL”, then (2) requests a classical planner to generate a PDDL plan based on an existing “Domain PDDL”, and finally (3) translates the PDDL plan back into natural language. Essentially, the planning step is outsourced to an external tool, assuming the availability of domain-specific PDDL and a suitable planner which is common in certain robotic setups but not in many other domains.\nSelf-Reflection#","metadata":{"source":"https://lilianweng.github.io/posts/2023-06-23-agent/","loc":{"lines":{"from":182,"to":184}}}},{"pageContent":"Agent System Overview\n \n Component One: Planning\n \n \n Task Decomposition\n \n Self-Reflection\n \n \n Component Two: Memory\n \n \n Types of Memory\n \n Maximum Inner Product Search (MIPS)\n \n \n Component Three: Tool Use\n \n Case Studies\n \n \n Scientific Discovery Agent\n \n Generative Agents Simulation\n \n Proof-of-Concept Examples\n \n \n Challenges\n \n Citation\n \n References","metadata":{"source":"https://lilianweng.github.io/posts/2023-06-23-agent/","loc":{"lines":{"from":112,"to":146}}}},{"pageContent":"(3) Task execution: Expert models execute on the specific tasks and log results.\nInstruction:\n\nWith the input and the inference results, the AI assistant needs to describe the process and results. The previous stages can be formed as - User Input: {{ User Input }}, Task Planning: {{ Tasks }}, Model Selection: {{ Model Assignment }}, Task Execution: {{ Predictions }}. You must first answer the user's request in a straightforward manner. Then describe the task process and show your analysis and model inference results to the user in the first person. If inference results contain a file path, must tell the user the complete file path.","metadata":{"source":"https://lilianweng.github.io/posts/2023-06-23-agent/","loc":{"lines":{"from":277,"to":280}}}}]answer: ""Task decomposition is a technique used to break down complex tasks into smaller and simpler steps. It can be done through various methods such as using prompting techniques, task-specific instructions, or human inputs. Another approach involves outsourcing the planning step to an external classical planner. "answer" Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to stream responses from a QA chain. Next, check out some of the other how-to guides around RAG, such as [how to add chat history](/v0.2/docs/how_to/qa_chat_history_how_to). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to return sources ](/v0.2/docs/how_to/qa_sources)[ Next How to construct filters ](/v0.2/docs/how_to/query_constructing_filters) * [Setup](#setup) * [Dependencies](#dependencies) * [LangSmith](#langsmith) * [Chain with sources](#chain-with-sources) * [Streaming final outputs](#streaming-final-outputs) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/multiple_queries
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to generate multiple queries to retrieve data for On this page How to generate multiple queries to retrieve data for ===================================================== Prerequisites This guide assumes familiarity with the following concepts: * [Vector stores](/v0.2/docs/concepts/#vectorstores) * [Retrievers](/v0.2/docs/concepts/#retrievers) * [Retrieval-augmented generation (RAG)](/v0.2/docs/tutorials/rag) Distance-based vector database retrieval embeds (represents) queries in high-dimensional space and finds similar embedded documents based on “distance”. But retrieval may produce different results with subtle changes in query wording or if the embeddings do not capture the semantics of the data well. Prompt engineering / tuning is sometimes done to manually address these problems, but can be tedious. The [`MultiQueryRetriever`](https://v02.api.js.langchain.com/classes/langchain_retrievers_multi_query.MultiQueryRetriever.html) automates the process of prompt tuning by using an LLM to generate multiple queries from different perspectives for a given user input query. For each query, it retrieves a set of relevant documents and takes the unique union across all queries to get a larger set of potentially relevant documents. By generating multiple perspectives on the same question, the `MultiQueryRetriever` can help overcome some of the limitations of the distance-based retrieval and get a richer set of results. Get started[​](#get-started "Direct link to Get started") --------------------------------------------------------- tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic @langchain/cohere yarn add @langchain/anthropic @langchain/cohere pnpm add @langchain/anthropic @langchain/cohere import { MemoryVectorStore } from "langchain/vectorstores/memory";import { CohereEmbeddings } from "@langchain/cohere";import { MultiQueryRetriever } from "langchain/retrievers/multi_query";import { ChatAnthropic } from "@langchain/anthropic";const embeddings = new CohereEmbeddings();const vectorstore = await MemoryVectorStore.fromTexts( [ "Buildings are made out of brick", "Buildings are made out of wood", "Buildings are made out of stone", "Cars are made out of metal", "Cars are made out of plastic", "mitochondria is the powerhouse of the cell", "mitochondria is made of lipids", ], [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }], embeddings);const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229",});const retriever = MultiQueryRetriever.fromLLM({ llm: model, retriever: vectorstore.asRetriever(),});const query = "What are mitochondria made of?";const retrievedDocs = await retriever.invoke(query);/* Generated queries: What are the components of mitochondria?,What substances comprise the mitochondria organelle? ,What is the molecular composition of mitochondria?*/console.log(retrievedDocs); [ Document { pageContent: "mitochondria is made of lipids", metadata: {} }, Document { pageContent: "mitochondria is the powerhouse of the cell", metadata: {} }, Document { pageContent: "Buildings are made out of brick", metadata: { id: 1 } }, Document { pageContent: "Buildings are made out of wood", metadata: { id: 2 } }] Customization[​](#customization "Direct link to Customization") --------------------------------------------------------------- You can also supply a custom prompt to tune what types of questions are generated. You can also pass a custom output parser to parse and split the results of the LLM call into a list of queries. import { LLMChain } from "langchain/chains";import { pull } from "langchain/hub";import { BaseOutputParser } from "@langchain/core/output_parsers";import { PromptTemplate } from "@langchain/core/prompts";type LineList = { lines: string[];};class LineListOutputParser extends BaseOutputParser<LineList> { static lc_name() { return "LineListOutputParser"; } lc_namespace = ["langchain", "retrievers", "multiquery"]; async parse(text: string): Promise<LineList> { const startKeyIndex = text.indexOf("<questions>"); const endKeyIndex = text.indexOf("</questions>"); const questionsStartIndex = startKeyIndex === -1 ? 0 : startKeyIndex + "<questions>".length; const questionsEndIndex = endKeyIndex === -1 ? text.length : endKeyIndex; const lines = text .slice(questionsStartIndex, questionsEndIndex) .trim() .split("\n") .filter((line) => line.trim() !== ""); return { lines }; } getFormatInstructions(): string { throw new Error("Not implemented."); }}// Default prompt is available at: https://smith.langchain.com/hub/jacob/multi-vector-retriever-germanconst prompt: PromptTemplate = await pull( "jacob/multi-vector-retriever-german");const vectorstore = await MemoryVectorStore.fromTexts( [ "Gebäude werden aus Ziegelsteinen hergestellt", "Gebäude werden aus Holz hergestellt", "Gebäude werden aus Stein hergestellt", "Autos werden aus Metall hergestellt", "Autos werden aus Kunststoff hergestellt", "Mitochondrien sind die Energiekraftwerke der Zelle", "Mitochondrien bestehen aus Lipiden", ], [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }], embeddings);const model = new ChatAnthropic({});const llmChain = new LLMChain({ llm: model, prompt, outputParser: new LineListOutputParser(),});const retriever = new MultiQueryRetriever({ retriever: vectorstore.asRetriever(), llmChain,});const query = "What are mitochondria made of?";const retrievedDocs = await retriever.invoke(query);/* Generated queries: Was besteht ein Mitochondrium?,Aus welchen Komponenten setzt sich ein Mitochondrium zusammen? ,Welche Moleküle finden sich in einem Mitochondrium?*/console.log(retrievedDocs); [ Document { pageContent: "Mitochondrien bestehen aus Lipiden", metadata: {} }, Document { pageContent: "Mitochondrien sind die Energiekraftwerke der Zelle", metadata: {} }, Document { pageContent: "Gebäude werden aus Stein hergestellt", metadata: { id: 3 } }, Document { pageContent: "Autos werden aus Metall hergestellt", metadata: { id: 4 } }, Document { pageContent: "Gebäude werden aus Holz hergestellt", metadata: { id: 2 } }, Document { pageContent: "Gebäude werden aus Ziegelsteinen hergestellt", metadata: { id: 1 } }] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to use the `MultiQueryRetriever` to query a vector store with automatically generated queries. See the individual sections for deeper dives on specific retrievers, the [broader tutorial on RAG](/v0.2/docs/tutorials/rag), or this section to learn how to [create your own custom retriever over any data source](/v0.2/docs/how_to/custom_retriever/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use multimodal prompts ](/v0.2/docs/how_to/multimodal_prompts)[ Next How to try to fix errors in output parsing ](/v0.2/docs/how_to/output_parser_fixing) * [Get started](#get-started) * [Customization](#customization) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/
* [](/v0.2/) * Tutorials On this page Tutorials ========= New to LangChain or to LLM app development in general? Read this material to quickly get up and running. Basics[​](#basics "Direct link to Basics") ------------------------------------------ * [Build a Simple LLM Application with LCEL](/v0.2/docs/tutorials/llm_chain) * [Build a Chatbot](/v0.2/docs/tutorials/chatbot) * [Build an Agent](/v0.2/docs/tutorials/agents) Working with external knowledge[​](#working-with-external-knowledge "Direct link to Working with external knowledge") --------------------------------------------------------------------------------------------------------------------- * [Build a Retrieval Augmented Generation (RAG) Application](/v0.2/docs/tutorials/rag) * [Build a Conversational RAG Application](/v0.2/docs/tutorials/qa_chat_history) * [Build a Question/Answering system over SQL data](/v0.2/docs/tutorials/sql_qa) * [Build a Query Analysis System](/v0.2/docs/tutorials/query_analysis) * [Build a local RAG application](/v0.2/docs/tutorials/local_rag) * [Build a Question Answering application over a Graph Database](/v0.2/docs/tutorials/graph) * [Build a PDF ingestion and Question/Answering system](/v0.2/docs/tutorials/pdf_qa/) Specialized tasks[​](#specialized-tasks "Direct link to Specialized tasks") --------------------------------------------------------------------------- * [Build an Extraction Chain](/v0.2/docs/tutorials/extraction) * [Classify text into labels](/v0.2/docs/tutorials/classification) * [Summarize text](/v0.2/docs/tutorials/summarization) LangGraph.js[​](#langgraphjs "Direct link to LangGraph.js") ----------------------------------------------------------- LangGraph.js is an extension of LangChain aimed at building robust and stateful multi-actor applications with LLMs by modeling steps as edges and nodes in a graph. LangGraph.js documentation is currently hosted on a separate site. You can peruse [LangGraph.js tutorials here](https://langchain-ai.github.io/langgraphjs/tutorials/). LangSmith[​](#langsmith "Direct link to LangSmith") --------------------------------------------------- LangSmith allows you to closely trace, monitor and evaluate your LLM application. It seamlessly integrates with LangChain, and you can use it to inspect and debug individual steps of your chains as you build. LangSmith documentation is hosted on a separate site. You can peruse [LangSmith tutorials here](https://docs.smith.langchain.com/tutorials/). ### Evaluation[​](#evaluation "Direct link to Evaluation") LangSmith helps you evaluate the performance of your LLM applications. The below tutorial is a great way to get started: * [Evaluate your LLM application](https://docs.smith.langchain.com/tutorials/Developers/evaluation) * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Introduction ](/v0.2/docs/introduction)[ Next Build a Question Answering application over a Graph Database ](/v0.2/docs/tutorials/graph) * [Basics](#basics) * [Working with external knowledge](#working-with-external-knowledge) * [Specialized tasks](#specialized-tasks) * [LangGraph.js](#langgraphjs) * [LangSmith](#langsmith) * [Evaluation](#evaluation)
null
https://js.langchain.com/v0.2/docs/how_to/chat_token_usage_tracking
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to track token usage On this page How to track token usage ======================== Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) This notebook goes over how to track your token usage for specific calls. Using `AIMessage.usage_metadata`[​](#using-aimessageusage_metadata "Direct link to using-aimessageusage_metadata") ------------------------------------------------------------------------------------------------------------------ A number of model providers return token usage information as part of the chat generation response. When available, this information will be included on the `AIMessage` objects produced by the corresponding model. LangChain `AIMessage` objects include a [`usage_metadata`](https://api.js.langchain.com/classes/langchain_core_messages.AIMessage.html#usage_metadata) attribute for supported providers. When populated, this attribute will be an object with standard keys (e.g., "input\_tokens" and "output\_tokens"). #### OpenAI[​](#openai "Direct link to OpenAI") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { ChatOpenAI } from "@langchain/openai";const chatModel = new ChatOpenAI({ model: "gpt-3.5-turbo-0125",});const res = await chatModel.invoke("Tell me a joke.");console.log(res.usage_metadata);/* { input_tokens: 12, output_tokens: 17, total_tokens: 29 }*/ #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` #### Anthropic[​](#anthropic "Direct link to Anthropic") * npm * Yarn * pnpm npm install @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic import { ChatAnthropic } from "@langchain/anthropic";const chatModel = new ChatAnthropic({ model: "claude-3-haiku-20240307",});const res = await chatModel.invoke("Tell me a joke.");console.log(res.usage_metadata);/* { input_tokens: 12, output_tokens: 98, total_tokens: 110 }*/ #### API Reference: * [ChatAnthropic](https://v02.api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic` Using `AIMessage.response_metadata`[​](#using-aimessageresponse_metadata "Direct link to using-aimessageresponse_metadata") --------------------------------------------------------------------------------------------------------------------------- A number of model providers return token usage information as part of the chat generation response. When available, this is included in the `AIMessage.response_metadata` field. #### OpenAI[​](#openai-1 "Direct link to OpenAI") import { ChatOpenAI } from "@langchain/openai";const chatModel = new ChatOpenAI({ model: "gpt-4-turbo",});const res = await chatModel.invoke("Tell me a joke.");console.log(res.response_metadata);/* { tokenUsage: { completionTokens: 15, promptTokens: 12, totalTokens: 27 }, finish_reason: 'stop' }*/ #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` #### Anthropic[​](#anthropic-1 "Direct link to Anthropic") import { ChatAnthropic } from "@langchain/anthropic";const chatModel = new ChatAnthropic({ model: "claude-3-sonnet-20240229",});const res = await chatModel.invoke("Tell me a joke.");console.log(res.response_metadata);/* { id: 'msg_017Mgz6HdgNbi3cwL1LNB9Dw', model: 'claude-3-sonnet-20240229', stop_sequence: null, usage: { input_tokens: 12, output_tokens: 30 }, stop_reason: 'end_turn' }*/ #### API Reference: * [ChatAnthropic](https://v02.api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic` Streaming[​](#streaming "Direct link to Streaming") --------------------------------------------------- Some providers support token count metadata in a streaming context. #### OpenAI[​](#openai-2 "Direct link to OpenAI") For example, OpenAI will return a message chunk at the end of a stream with token usage information. This behavior is supported by `@langchain/openai` >= 0.1.0 and can be enabled by passing a `stream_options` parameter when making your call. info By default, the last message chunk in a stream will include a `finish_reason` in the message's `response_metadata` attribute. If we include token usage in streaming mode, an additional chunk containing usage metadata will be added to the end of the stream, such that `finish_reason` appears on the second to last message chunk. import type { AIMessageChunk } from "@langchain/core/messages";import { ChatOpenAI } from "@langchain/openai";import { concat } from "@langchain/core/utils/stream";// Instantiate the modelconst model = new ChatOpenAI();const response = await model.stream("Hello, how are you?", { // Pass the stream options stream_options: { include_usage: true, },});// Iterate over the response, only saving the last chunklet finalResult: AIMessageChunk | undefined;for await (const chunk of response) { if (finalResult) { finalResult = concat(finalResult, chunk); } else { finalResult = chunk; }}console.log(finalResult?.usage_metadata);/* { input_tokens: 13, output_tokens: 30, total_tokens: 43 }*/ #### API Reference: * [AIMessageChunk](https://v02.api.js.langchain.com/classes/langchain_core_messages.AIMessageChunk.html) from `@langchain/core/messages` * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [concat](https://v02.api.js.langchain.com/functions/langchain_core_utils_stream.concat.html) from `@langchain/core/utils/stream` Using callbacks[​](#using-callbacks "Direct link to Using callbacks") --------------------------------------------------------------------- You can also use the `handleLLMEnd` callback to get the full output from the LLM, including token usage for supported models. Here's an example of how you could do that: import { ChatOpenAI } from "@langchain/openai";const chatModel = new ChatOpenAI({ model: "gpt-4-turbo", callbacks: [ { handleLLMEnd(output) { console.log(JSON.stringify(output, null, 2)); }, }, ],});await chatModel.invoke("Tell me a joke.");/* { "generations": [ [ { "text": "Why did the scarecrow win an award?\n\nBecause he was outstanding in his field!", "message": { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessage" ], "kwargs": { "content": "Why did the scarecrow win an award?\n\nBecause he was outstanding in his field!", "tool_calls": [], "invalid_tool_calls": [], "additional_kwargs": {}, "response_metadata": { "tokenUsage": { "completionTokens": 17, "promptTokens": 12, "totalTokens": 29 }, "finish_reason": "stop" } } }, "generationInfo": { "finish_reason": "stop" } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 17, "promptTokens": 12, "totalTokens": 29 } } }*/ #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now seen a few examples of how to track chat model token usage for supported providers. Next, check out the other how-to guides on chat models in this section, like [how to get a model to return structured output](/v0.2/docs/how_to/structured_output) or [how to add caching to your chat models](/v0.2/docs/how_to/chat_model_caching). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to do per-user retrieval ](/v0.2/docs/how_to/qa_per_user)[ Next How to track token usage ](/v0.2/docs/how_to/llm_token_usage_tracking) * [Using `AIMessage.usage_metadata`](#using-aimessageusage_metadata) * [Using `AIMessage.response_metadata`](#using-aimessageresponse_metadata) * [Streaming](#streaming) * [Using callbacks](#using-callbacks) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/llm_token_usage_tracking
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to track token usage On this page How to track token usage ======================== Prerequisites This guide assumes familiarity with the following concepts: * [LLMs](/v0.2/docs/concepts/#llms) This notebook goes over how to track your token usage for specific LLM calls. This is only implemented by some providers, including OpenAI. Here's an example of tracking token usage for a single LLM call via a callback: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { OpenAI } from "@langchain/openai";const llm = new OpenAI({ model: "gpt-3.5-turbo-instruct", callbacks: [ { handleLLMEnd(output) { console.log(JSON.stringify(output, null, 2)); }, }, ],});await llm.invoke("Tell me a joke.");/* { "generations": [ [ { "text": "\n\nWhy don't scientists trust atoms?\n\nBecause they make up everything.", "generationInfo": { "finishReason": "stop", "logprobs": null } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 14, "promptTokens": 5, "totalTokens": 19 } } }*/ #### API Reference: * [OpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai` If this model is passed to a chain or agent that calls it multiple times, it will log an output each time. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now seen how to get token usage for supported LLM providers. Next, check out the other how-to guides in this section, like [how to implement your own custom LLM](/v0.2/docs/how_to/custom_llm). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to track token usage ](/v0.2/docs/how_to/chat_token_usage_tracking)[ Next How to pass through arguments from one step to the next ](/v0.2/docs/how_to/passthrough) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/query_constructing_filters
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to construct filters On this page How to construct filters ======================== Prerequisites This guide assumes familiarity with the following: * [Query analysis](/v0.2/docs/tutorials/query_analysis) We may want to do query analysis to extract filters to pass into retrievers. One way we ask the LLM to represent these filters is as a Zod schema. There is then the issue of converting that Zod schema into a filter that can be passed into a retriever. This can be done manually, but LangChain also provides some “Translators” that are able to translate from a common syntax into filters specific to each retriever. Here, we will cover how to use those translators. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") * npm * yarn * pnpm npm i zod yarn add zod pnpm add zod In this example, `year` and `author` are both attributes to filter on. import { z } from "zod";const searchSchema = z.object({ query: z.string(), startYear: z.number().optional(), author: z.string().optional(),});const searchQuery: z.infer<typeof searchSchema> = { query: "RAG", startYear: 2022, author: "LangChain",}; import { Comparison, Comparator } from "langchain/chains/query_constructor/ir";function constructComparisons( query: z.infer<typeof searchSchema>): Comparison[] { const comparisons: Comparison[] = []; if (query.startYear !== undefined) { comparisons.push( new Comparison("gt" as Comparator, "start_year", query.startYear) ); } if (query.author !== undefined) { comparisons.push( new Comparison("eq" as Comparator, "author", query.author) ); } return comparisons;}const comparisons = constructComparisons(searchQuery); import { Operation, Operator } from "langchain/chains/query_constructor/ir";const _filter = new Operation("and" as Operator, comparisons); import { ChromaTranslator } from "langchain/retrievers/self_query/chroma";new ChromaTranslator().visitOperation(_filter); { "$and": [ { start_year: { "$gt": 2022 } }, { author: { "$eq": "LangChain" } } ]} Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to create a specific filter from an arbitrary query. Next, check out some of the other query analysis guides in this section, like [how to use few-shotting to improve performance](/v0.2/docs/how_to/query_no_queries). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to stream from a question-answering chain ](/v0.2/docs/how_to/qa_streaming)[ Next How to add examples to the prompt ](/v0.2/docs/how_to/query_few_shot) * [Setup](#setup) * [Install dependencies](#install-dependencies) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/output_parser_fixing
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to try to fix errors in output parsing How to try to fix errors in output parsing ========================================== Prerequisites This guide assumes familiarity with the following concepts: - [Chat models](/v0.2/docs/concepts/#chat-models) - [Output parsers](/v0.2/docs/concepts/#output-parsers) - [Prompt templates](/v0.2/docs/concepts/#prompt-templates) - [Chaining runnables together](/v0.2/docs/how_to/sequence/) LLMs aren’t perfect, and sometimes fail to produce output that perfectly matches a the desired format. To help handle errors, we can use the [`OutputFixingParser`](https://api.js.langchain.com/classes/langchain_output_parsers.OutputFixingParser.html) This output parser wraps another output parser, and in the event that the first one fails, it calls out to another LLM in an attempt to fix any errors. Specifically, we can pass the misformatted output, along with the formatted instructions, to the model and ask it to fix it. For this example, we’ll use the [`StructuredOutputParser`](https://api.js.langchain.com/classes/langchain_core_output_parsers.StructuredOutputParser.html), which can validate output according to a Zod schema. Here’s what happens if we pass it a result that does not comply with the schema: import { z } from "zod";import { RunnableSequence } from "@langchain/core/runnables";import { StructuredOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";const zodSchema = z.object({ name: z.string().describe("name of an actor"), film_names: z .array(z.string()) .describe("list of names of films they starred in"),});const parser = StructuredOutputParser.fromZodSchema(zodSchema);const misformatted = "{'name': 'Tom Hanks', 'film_names': ['Forrest Gump']}";await parser.parse(misformatted); Error: Failed to parse. Text: "{'name': 'Tom Hanks', 'film_names': ['Forrest Gump']}". Error: SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2) Now we can construct and use a `OutputFixingParser`. This output parser takes as an argument another output parser but also an LLM with which to try to correct any formatting mistakes. import { ChatAnthropic } from "@langchain/anthropic";import { OutputFixingParser } from "langchain/output_parsers";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", maxTokens: 512, temperature: 0.1,});const parserWithFix = OutputFixingParser.fromLLM(model, parser);await parserWithFix.parse(misformatted); { name: "Tom Hanks", film_names: [ "Forrest Gump", "Saving Private Ryan", "Cast Away", "Catch Me If You Can" ]} For more about different parameters and options, check out our [API reference docs](https://api.js.langchain.com/classes/langchain_output_parsers.OutputFixingParser.html). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to generate multiple queries to retrieve data for ](/v0.2/docs/how_to/multiple_queries)[ Next How to parse JSON output ](/v0.2/docs/how_to/output_parser_json)
null
https://js.langchain.com/v0.2/docs/how_to/query_few_shot
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to add examples to the prompt On this page How to add examples to the prompt ================================= Prerequisites This guide assumes familiarity with the following: * [Query analysis](/v0.2/docs/tutorials/query_analysis) As our query analysis becomes more complex, the LLM may struggle to understand how exactly it should respond in certain scenarios. In order to improve performance here, we can add examples to the prompt to guide the LLM. Let’s take a look at how we can add examples for the LangChain YouTube video query analyzer we built in the [query analysis tutorial](/v0.2/docs/tutorials/query_analysis). Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i zod uuid yarn add zod uuid pnpm add zod uuid ### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") # Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true Query schema[​](#query-schema "Direct link to Query schema") ------------------------------------------------------------ We’ll define a query schema that we want our model to output. To make our query analysis a bit more interesting, we’ll add a `subQueries` field that contains more narrow questions derived from the top level question. import { z } from "zod";const subQueriesDescription = `If the original question contains multiple distinct sub-questions,or if there are more generic questions that would be helpful to answer inorder to answer the original question, write a list of all relevant sub-questions.Make sure this list is comprehensive and covers all parts of the original question.It's ok if there's redundancy in the sub-questions, it's better to cover all the bases than to miss some.Make sure the sub-questions are as narrowly focused as possible in order to get the most relevant results.`;const searchSchema = z.object({ query: z .string() .describe("Primary similarity search query applied to video transcripts."), subQueries: z.array(z.string()).optional().describe(subQueriesDescription), publishYear: z.number().optional().describe("Year video was published"),}); Query generation[​](#query-generation "Direct link to Query generation") ------------------------------------------------------------------------ ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";const system = `You are an expert at converting user questions into database queries.You have access to a database of tutorial videos about a software library for building LLM-powered applications.Given a question, return a list of database queries optimized to retrieve the most relevant results.If there are acronyms or words you are not familiar with, do not try to rephrase them.`;const prompt = ChatPromptTemplate.fromMessages([ ["system", system], ["placeholder", "{examples}"], ["human", "{question}"],]);const llmWithTools = llm.withStructuredOutput(searchSchema, { name: "Search",});const queryAnalyzer = RunnableSequence.from([ { question: new RunnablePassthrough(), }, prompt, llmWithTools,]); Let’s try out our query analyzer without any examples in the prompt: await queryAnalyzer.invoke( "what's the difference between web voyager and reflection agents? do both use langgraph?"); { query: "difference between Web Voyager and Reflection Agents", subQueries: [ "Do Web Voyager and Reflection Agents use LangGraph?" ]} Adding examples and tuning the prompt[​](#adding-examples-and-tuning-the-prompt "Direct link to Adding examples and tuning the prompt") --------------------------------------------------------------------------------------------------------------------------------------- This works pretty well, but we probably want it to decompose the question even further to separate the queries about Web Voyager and Reflection Agents. To tune our query generation results, we can add some examples of inputs questions and gold standard output queries to our prompt. const examples = []; const question = "What's chat langchain, is it a langchain template?";const query = { query: "What is chat langchain and is it a langchain template?", subQueries: ["What is chat langchain", "What is a langchain template"],};examples.push({ input: question, toolCalls: [query] }); 1 const question = "How to build multi-agent system and stream intermediate steps from it";const query = { query: "How to build multi-agent system and stream intermediate steps from it", subQueries: [ "How to build multi-agent system", "How to stream intermediate steps from multi-agent system", "How to stream intermediate steps", ],};examples.push({ input: question, toolCalls: [query] }); 2 const question = "LangChain agents vs LangGraph?";const query = { query: "What's the difference between LangChain agents and LangGraph? How do you deploy them?", subQueries: [ "What are LangChain agents", "What is LangGraph", "How do you deploy LangChain agents", "How do you deploy LangGraph", ],};examples.push({ input: question, toolCalls: [query] }); 3 Now we need to update our prompt template and chain so that the examples are included in each prompt. Since we’re working with LLM model function-calling, we’ll need to do a bit of extra structuring to send example inputs and outputs to the model. We’ll create a `toolExampleToMessages` helper function to handle this for us: import { AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage,} from "@langchain/core/messages";import { v4 as uuidV4 } from "uuid";const toolExampleToMessages = ( example: Example | Record<string, any>): Array<BaseMessage> => { const messages: Array<BaseMessage> = [ new HumanMessage({ content: example.input }), ]; const openaiToolCalls = example.toolCalls.map((toolCall) => { return { id: uuidV4(), type: "function" as const, function: { name: "search", arguments: JSON.stringify(toolCall), }, }; }); messages.push( new AIMessage({ content: "", additional_kwargs: { tool_calls: openaiToolCalls }, }) ); const toolOutputs = "toolOutputs" in example ? example.toolOutputs : Array(openaiToolCalls.length).fill( "You have correctly called this tool." ); toolOutputs.forEach((output, index) => { messages.push( new ToolMessage({ content: output, tool_call_id: openaiToolCalls[index].id, }) ); }); return messages;};const exampleMessages = examples.map((ex) => toolExampleToMessages(ex)).flat(); import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";import { RunnableSequence } from "@langchain/core/runnables";const queryAnalyzerWithExamples = RunnableSequence.from([ { question: new RunnablePassthrough(), examples: () => exampleMessages, }, prompt, llmWithTools,]); await queryAnalyzerWithExamples.invoke( "what's the difference between web voyager and reflection agents? do both use langgraph?"); { query: "Difference between Web Voyager and Reflection agents, do they both use LangGraph?", subQueries: [ "Difference between Web Voyager and Reflection agents", "Do Web Voyager and Reflection agents use LangGraph" ]} Thanks to our examples we get a slightly more decomposed search query. With some more prompt engineering and tuning of our examples we could improve query generation even more. You can see that the examples are passed to the model as messages in the [LangSmith trace](https://smith.langchain.com/public/102829c3-69fc-4cb7-b28b-399ae2c9c008/r). Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned some techniques for combining few-shotting with query analysis. Next, check out some of the other query analysis guides in this section, like [how to deal with high cardinality data](/v0.2/docs/how_to/query_high_cardinality). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to construct filters ](/v0.2/docs/how_to/query_constructing_filters)[ Next How to deal with high cardinality categorical variables ](/v0.2/docs/how_to/query_high_cardinality) * [Setup](#setup) * [Install dependencies](#install-dependencies) * [Set environment variables](#set-environment-variables) * [Query schema](#query-schema) * [Query generation](#query-generation) * [Adding examples and tuning the prompt](#adding-examples-and-tuning-the-prompt) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/query_high_cardinality
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to deal with high cardinality categorical variables On this page How to deal with high cardinality categorical variables ======================================================= Prerequisites This guide assumes familiarity with the following: * [Query analysis](/v0.2/docs/tutorials/query_analysis) High cardinality data refers to columns in a dataset that contain a large number of unique values. This guide demonstrates some techniques for dealing with these inputs. For example, you may want to do query analysis to create a filter on a categorical column. One of the difficulties here is that you usually need to specify the EXACT categorical value. The issue is you need to make sure the LLM generates that categorical value exactly. This can be done relatively easy with prompting when there are only a few values that are valid. When there are a high number of valid values then it becomes more difficult, as those values may not fit in the LLM context, or (if they do) there may be too many for the LLM to properly attend to. In this notebook we take a look at how to approach this. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community zod @faker-js/faker yarn add @langchain/community zod @faker-js/faker pnpm add @langchain/community zod @faker-js/faker ### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") # Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true #### Set up data[​](#set-up-data "Direct link to Set up data") We will generate a bunch of fake names import { faker } from "@faker-js/faker";const names = Array.from({ length: 10000 }, () => faker.person.fullName()); Let’s look at some of the names names[0]; "Rolando Wilkinson" names[567]; "Homer Harber" Query Analysis[​](#query-analysis "Direct link to Query Analysis") ------------------------------------------------------------------ We can now set up a baseline query analysis import { z } from "zod";const searchSchema = z.object({ query: z.string(), author: z.string(),}); ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";const system = `Generate a relevant search query for a library system`;const prompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{question}"],]);const llmWithTools = llm.withStructuredOutput(searchSchema, { name: "Search",});const queryAnalyzer = RunnableSequence.from([ { question: new RunnablePassthrough(), }, prompt, llmWithTools,]); We can see that if we spell the name exactly correctly, it knows how to handle it await queryAnalyzer.invoke("what are books about aliens by Jesse Knight"); { query: "aliens", author: "Jesse Knight" } The issue is that the values you want to filter on may NOT be spelled exactly correctly await queryAnalyzer.invoke("what are books about aliens by jess knight"); { query: "books about aliens", author: "jess knight" } ### Add in all values[​](#add-in-all-values "Direct link to Add in all values") One way around this is to add ALL possible values to the prompt. That will generally guide the query in the right direction const system = `Generate a relevant search query for a library system using the 'search' tool.The 'author' you return to the user MUST be one of the following authors:{authors}Do NOT hallucinate author name!`;const basePrompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{question}"],]);const prompt = await basePrompt.partial({ authors: names.join(", ") });const queryAnalyzerAll = RunnableSequence.from([ { question: new RunnablePassthrough(), }, prompt, llmWithTools,]); However… if the list of categoricals is long enough, it may error! try { const res = await queryAnalyzerAll.invoke( "what are books about aliens by jess knight" );} catch (e) { console.error(e);} Error: 400 This model's maximum context length is 16385 tokens. However, your messages resulted in 50197 tokens (50167 in the messages, 30 in the functions). Please reduce the length of the messages or functions. at Function.generate (file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/openai/4.47.1/error.mjs:41:20) at OpenAI.makeStatusError (file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/openai/4.47.1/core.mjs:256:25) at OpenAI.makeRequest (file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/openai/4.47.1/core.mjs:299:30) at eventLoopTick (ext:core/01_core.js:63:7) at async file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/@langchain/openai/0.0.31/dist/chat_models.js:756:29 at async RetryOperation._fn (file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/p-retry/4.6.2/index.js:50:12) { status: 400, headers: { "alt-svc": 'h3=":443"; ma=86400', "cf-cache-status": "DYNAMIC", "cf-ray": "885f794b3df4fa52-SJC", "content-length": "340", "content-type": "application/json", date: "Sat, 18 May 2024 23:02:16 GMT", "openai-organization": "langchain", "openai-processing-ms": "230", "openai-version": "2020-10-01", server: "cloudflare", "set-cookie": "_cfuvid=F_c9lnRuQDUhKiUE2eR2PlsxHPldf1OAVMonLlHTjzM-1716073336256-0.0.1.1-604800000; path=/; domain="... 48 more characters, "strict-transport-security": "max-age=15724800; includeSubDomains", "x-ratelimit-limit-requests": "10000", "x-ratelimit-limit-tokens": "2000000", "x-ratelimit-remaining-requests": "9999", "x-ratelimit-remaining-tokens": "1958402", "x-ratelimit-reset-requests": "6ms", "x-ratelimit-reset-tokens": "1.247s", "x-request-id": "req_7b88677d6883fac1520e44543f68c839" }, request_id: "req_7b88677d6883fac1520e44543f68c839", error: { message: "This model's maximum context length is 16385 tokens. However, your messages resulted in 50197 tokens"... 101 more characters, type: "invalid_request_error", param: "messages", code: "context_length_exceeded" }, code: "context_length_exceeded", param: "messages", type: "invalid_request_error", attemptNumber: 1, retriesLeft: 6} We can try to use a longer context window… but with so much information in there, it is not guaranteed to pick it up reliably ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llmLong = new ChatOpenAI({ model: "gpt-4-turbo-preview" }); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llmLong = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llmLong = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llmLong = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llmLong = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llmLong = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); const structuredLlmLong = llmLong.withStructuredOutput(searchSchema, { name: "Search",});const queryAnalyzerAll = RunnableSequence.from([ { question: new RunnablePassthrough(), }, prompt, structuredLlmLong,]); await queryAnalyzerAll.invoke("what are books about aliens by jess knight"); { query: "aliens", author: "jess knight" } ### Find and all relevant values[​](#find-and-all-relevant-values "Direct link to Find and all relevant values") Instead, what we can do is create a [vector store index](/v0.2/docs/concepts#vectorstores) over the relevant values and then query that for the N most relevant values, import { OpenAIEmbeddings } from "@langchain/openai";import { MemoryVectorStore } from "langchain/vectorstores/memory";const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small",});const vectorstore = await MemoryVectorStore.fromTexts(names, {}, embeddings);const selectNames = async (question: string) => { const _docs = await vectorstore.similaritySearch(question, 10); const _names = _docs.map((d) => d.pageContent); return _names.join(", ");};const createPrompt = RunnableSequence.from([ { question: new RunnablePassthrough(), authors: selectNames, }, basePrompt,]);await createPrompt.invoke("what are books by jess knight"); ChatPromptValue { lc_serializable: true, lc_kwargs: { messages: [ SystemMessage { lc_serializable: true, lc_kwargs: { content: "Generate a relevant search query for a library system using the 'search' tool.\n" + "\n" + "The 'author' you ret"... 243 more characters, additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Generate a relevant search query for a library system using the 'search' tool.\n" + "\n" + "The 'author' you ret"... 243 more characters, name: undefined, additional_kwargs: {}, response_metadata: {} }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "what are books by jess knight", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "what are books by jess knight", name: undefined, additional_kwargs: {}, response_metadata: {} } ] }, lc_namespace: [ "langchain_core", "prompt_values" ], messages: [ SystemMessage { lc_serializable: true, lc_kwargs: { content: "Generate a relevant search query for a library system using the 'search' tool.\n" + "\n" + "The 'author' you ret"... 243 more characters, additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Generate a relevant search query for a library system using the 'search' tool.\n" + "\n" + "The 'author' you ret"... 243 more characters, name: undefined, additional_kwargs: {}, response_metadata: {} }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "what are books by jess knight", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "what are books by jess knight", name: undefined, additional_kwargs: {}, response_metadata: {} } ]} const queryAnalyzerSelect = createPrompt.pipe(llmWithTools);await queryAnalyzerSelect.invoke("what are books about aliens by jess knight"); { query: "aliens", author: "Jess Knight" } Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to deal with high cardinality data when constructing queries. Next, check out some of the other query analysis guides in this section, like [how to use few-shotting to improve performance](/v0.2/docs/how_to/query_no_queries). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to add examples to the prompt ](/v0.2/docs/how_to/query_few_shot)[ Next How to handle multiple queries ](/v0.2/docs/how_to/query_multiple_queries) * [Setup](#setup) * [Install dependencies](#install-dependencies) * [Set environment variables](#set-environment-variables) * [Query Analysis](#query-analysis) * [Add in all values](#add-in-all-values) * [Find and all relevant values](#find-and-all-relevant-values) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/passthrough
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to pass through arguments from one step to the next On this page How to pass through arguments from one step to the next ======================================================= Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) * [Chaining runnables](/v0.2/docs/how_to/sequence/) * [Calling runnables in parallel](/v0.2/docs/how_to/parallel/) * [Custom functions](/v0.2/docs/how_to/functions/) When composing chains with several steps, sometimes you will want to pass data from previous steps unchanged for use as input to a later step. The [`RunnablePassthrough`](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html) class allows you to do just this, and is typically is used in conjuction with a [RunnableParallel](/v0.2/docs/how_to/parallel/) to pass data through to a later step in your constructed chains. Let’s look at an example: import { RunnableParallel, RunnablePassthrough,} from "@langchain/core/runnables";const runnable = RunnableParallel.from({ passed: new RunnablePassthrough(), modified: (input) => input.num + 1,});await runnable.invoke({ num: 1 }); { passed: { num: 1 }, modified: 2 } As seen above, `passed` key was called with `RunnablePassthrough()` and so it simply passed on `{'num': 1}`. We also set a second key in the map with `modified`. This uses a lambda to set a single value adding 1 to the num, which resulted in `modified` key with the value of `2`. Retrieval Example[​](#retrieval-example "Direct link to Retrieval Example") --------------------------------------------------------------------------- In the example below, we see a more real-world use case where we use `RunnablePassthrough` along with `RunnableParallel` in a chain to properly format inputs to a prompt: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";import { MemoryVectorStore } from "langchain/vectorstores/memory";const vectorstore = await MemoryVectorStore.fromDocuments( [{ pageContent: "harrison worked at kensho", metadata: {} }], new OpenAIEmbeddings());const retriever = vectorstore.asRetriever();const template = `Answer the question based only on the following context:{context}Question: {question}`;const prompt = ChatPromptTemplate.fromTemplate(template);const model = new ChatOpenAI({ model: "gpt-4o" });const retrievalChain = RunnableSequence.from([ { context: retriever.pipe((docs) => docs[0].pageContent), question: new RunnablePassthrough(), }, prompt, model, new StringOutputParser(),]);await retrievalChain.invoke("where did harrison work?"); "Harrison worked at Kensho." Here the input to prompt is expected to be a map with keys `"context"` and `"question"`. The user input is just the question. So we need to get the context using our retriever and passthrough the user input under the `"question"` key. The `RunnablePassthrough` allows us to pass on the user’s question to the prompt and model. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ Now you’ve learned how to pass data through your chains to help to help format the data flowing through your chains. To learn more, see the other how-to guides on runnables in this section. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to track token usage ](/v0.2/docs/how_to/llm_token_usage_tracking)[ Next How to compose prompts together ](/v0.2/docs/how_to/prompts_composition) * [Retrieval Example](#retrieval-example) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/output_parser_json
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to parse JSON output On this page How to parse JSON output ======================== While some model providers support [built-in ways to return structured output](/v0.2/docs/how_to/structured_output), not all do. We can use an output parser to help users to specify an arbitrary JSON schema via the prompt, query a model for outputs that conform to that schema, and finally parse that schema as JSON. note Keep in mind that large language models are leaky abstractions! You’ll have to use an LLM with sufficient capacity to generate well-formed JSON. Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) * [Output parsers](/v0.2/docs/concepts/#output-parsers) * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) * [Structured output](/v0.2/docs/how_to/structured_output) * [Chaining runnables together](/v0.2/docs/how_to/sequence/) The [`JsonOutputParser`](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.JsonOutputParser.html) is one built-in option for prompting for and then parsing JSON output. ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-4o", temperature: 0,});import { JsonOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";// Define your desired data structure. Only used for typing the parser output.interface Joke { setup: string; punchline: string;}// A query and format instructions used to prompt a language model.const jokeQuery = "Tell me a joke.";const formatInstructions = "Respond with a valid JSON object, containing two fields: 'setup' and 'punchline'.";// Set up a parser + inject instructions into the prompt template.const parser = new JsonOutputParser<Joke>();const prompt = ChatPromptTemplate.fromTemplate( "Answer the user query.\n{format_instructions}\n{query}\n");const partialedPrompt = await prompt.partial({ format_instructions: formatInstructions,});const chain = partialedPrompt.pipe(model).pipe(parser);await chain.invoke({ query: jokeQuery }); { setup: "Why don't scientists trust atoms?", punchline: "Because they make up everything!"} Streaming[​](#streaming "Direct link to Streaming") --------------------------------------------------- The `JsonOutputParser` also supports streaming partial chunks. This is useful when the model returns partial JSON output in multiple chunks. The parser will keep track of the partial chunks and return the final JSON output when the model finishes generating the output. for await (const s of await chain.stream({ query: jokeQuery })) { console.log(s);} {}{ setup: "" }{ setup: "Why" }{ setup: "Why don't" }{ setup: "Why don't scientists" }{ setup: "Why don't scientists trust" }{ setup: "Why don't scientists trust atoms" }{ setup: "Why don't scientists trust atoms?", punchline: "" }{ setup: "Why don't scientists trust atoms?", punchline: "Because" }{ setup: "Why don't scientists trust atoms?", punchline: "Because they"}{ setup: "Why don't scientists trust atoms?", punchline: "Because they make"}{ setup: "Why don't scientists trust atoms?", punchline: "Because they make up"}{ setup: "Why don't scientists trust atoms?", punchline: "Because they make up everything"}{ setup: "Why don't scientists trust atoms?", punchline: "Because they make up everything!"} Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned one way to prompt a model to return structured JSON. Next, check out the [broader guide on obtaining structured output](/v0.2/docs/how_to/structured_output) for other techniques. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to try to fix errors in output parsing ](/v0.2/docs/how_to/output_parser_fixing)[ Next How to parse XML output ](/v0.2/docs/how_to/output_parser_xml) * [Streaming](#streaming) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/graph
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build a Question Answering application over a Graph Database On this page Build a Question Answering application over a Graph Database ============================================================ In this guide we’ll go over the basic ways to create a Q&A chain over a graph database. These systems will allow us to ask a question about the data in a graph database and get back a natural language answer. ⚠️ Security note ⚠️[​](#security-note "Direct link to ⚠️ Security note ⚠️") --------------------------------------------------------------------------- Building Q&A systems of graph databases requires executing model-generated graph queries. There are inherent risks in doing this. Make sure that your database connection permissions are always scoped as narrowly as possible for your chain/agent’s needs. This will mitigate though not eliminate the risks of building a model-driven system. For more on general security best practices, [see here](/v0.2/docs/security). Architecture[​](#architecture "Direct link to Architecture") ------------------------------------------------------------ At a high-level, the steps of most graph chains are: 1. **Convert question to a graph database query**: Model converts user input to a graph database query (e.g. Cypher). 2. **Execute graph database query**: Execute the graph database query. 3. **Answer the question**: Model responds to user input using the query results. ![sql_usecase.png](/v0.2/assets/images/graph_usecase-34d891523e6284bb6230b38c5f8392e5.png) Setup[​](#setup "Direct link to Setup") --------------------------------------- #### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i langchain @langchain/community @langchain/openai neo4j-driver yarn add langchain @langchain/community @langchain/openai neo4j-driver pnpm add langchain @langchain/community @langchain/openai neo4j-driver #### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") We’ll use OpenAI in this example: OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true Next, we need to define Neo4j credentials. Follow [these installation steps](https://neo4j.com/docs/operations-manual/current/installation/) to set up a Neo4j database. NEO4J_URI="bolt://localhost:7687"NEO4J_USERNAME="neo4j"NEO4J_PASSWORD="password" The below example will create a connection with a Neo4j database and will populate it with example data about movies and their actors. import "neo4j-driver";import { Neo4jGraph } from "@langchain/community/graphs/neo4j_graph";const url = Deno.env.get("NEO4J_URI");const username = Deno.env.get("NEO4J_USER");const password = Deno.env.get("NEO4J_PASSWORD");const graph = await Neo4jGraph.initialize({ url, username, password });// Import movie informationconst moviesQuery = `LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'AS rowMERGE (m:Movie {id:row.movieId})SET m.released = date(row.released), m.title = row.title, m.imdbRating = toFloat(row.imdbRating)FOREACH (director in split(row.director, '|') | MERGE (p:Person {name:trim(director)}) MERGE (p)-[:DIRECTED]->(m))FOREACH (actor in split(row.actors, '|') | MERGE (p:Person {name:trim(actor)}) MERGE (p)-[:ACTED_IN]->(m))FOREACH (genre in split(row.genres, '|') | MERGE (g:Genre {name:trim(genre)}) MERGE (m)-[:IN_GENRE]->(g))`;await graph.query(moviesQuery); Schema refreshed successfully. [] Graph schema[​](#graph-schema "Direct link to Graph schema") ------------------------------------------------------------ In order for an LLM to be able to generate a Cypher statement, it needs information about the graph schema. When you instantiate a graph object, it retrieves the information about the graph schema. If you later make any changes to the graph, you can run the `refreshSchema` method to refresh the schema information. await graph.refreshSchema();console.log(graph.getSchema()); Node properties are the following:Movie {imdbRating: FLOAT, id: STRING, released: DATE, title: STRING}, Person {name: STRING}, Genre {name: STRING}Relationship properties are the following:The relationships are the following:(:Movie)-[:IN_GENRE]->(:Genre), (:Person)-[:DIRECTED]->(:Movie), (:Person)-[:ACTED_IN]->(:Movie) Great! We’ve got a graph database that we can query. Now let’s try hooking it up to an LLM. Chain[​](#chain "Direct link to Chain") --------------------------------------- Let’s use a simple chain that takes a question, turns it into a Cypher query, executes the query, and uses the result to answer the original question. ![graph_chain.webp](/v0.2/assets/images/graph_chain-6379941793e0fa985e51e4bda0329403.webp) LangChain comes with a built-in chain for this workflow that is designed to work with Neo4j: [GraphCypherQAChain](https://python.langchain.com/docs/use_cases/graph/graph_cypher_qa) import { GraphCypherQAChain } from "langchain/chains/graph_qa/cypher";import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const chain = GraphCypherQAChain.fromLLM({ llm, graph,});const response = await chain.invoke({ query: "What was the cast of the Casino?",});console.log(response); { result: "James Woods, Joe Pesci, Robert De Niro, Sharon Stone" } ### Next steps[​](#next-steps "Direct link to Next steps") For more complex query-generation, we may want to create few-shot prompts or add query-checking steps. For advanced techniques like this and more check out: * [Prompting strategies](/v0.2/docs/how_to/graph_prompting): Advanced prompt engineering techniques. * [Mapping values](/v0.2/docs/how_to/graph_mapping/): Techniques for mapping values from questions to database. * [Semantic layer](/v0.2/docs/how_to/graph_semantic): Techniques for working implementing semantic layers. * [Constructing graphs](/v0.2/docs/how_to/graph_constructing): Techniques for constructing knowledge graphs. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Tutorials ](/v0.2/docs/tutorials/)[ Next Tutorials ](/v0.2/docs/tutorials/) * [⚠️ Security note ⚠️](#security-note) * [Architecture](#architecture) * [Setup](#setup) * [Graph schema](#graph-schema) * [Chain](#chain) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/query_multiple_queries
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to handle multiple queries On this page How to handle multiple queries ============================== Prerequisites This guide assumes familiarity with the following: * [Query analysis](/v0.2/docs/tutorials/query_analysis) Sometimes, a query analysis technique may allow for multiple queries to be generated. In these cases, we need to remember to run all queries and then to combine the results. We will show a simple example (using mock data) of how to do that. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community @langchain/openai zod chromadb yarn add @langchain/community @langchain/openai zod chromadb pnpm add @langchain/community @langchain/openai zod chromadb ### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true ### Create Index[​](#create-index "Direct link to Create Index") We will create a vectorstore over fake information. import { Chroma } from "@langchain/community/vectorstores/chroma";import { OpenAIEmbeddings } from "@langchain/openai";import "chromadb";const texts = ["Harrison worked at Kensho", "Ankush worked at Facebook"];const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small" });const vectorstore = await Chroma.fromTexts(texts, {}, embeddings, { collectionName: "multi_query",});const retriever = vectorstore.asRetriever(1); Query analysis[​](#query-analysis "Direct link to Query analysis") ------------------------------------------------------------------ We will use function calling to structure the output. We will let it return multiple queries. import { z } from "zod";const searchSchema = z .object({ queries: z.array(z.string()).describe("Distinct queries to search for"), }) .describe("Search over a database of job records."); ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnableSequence, RunnablePassthrough,} from "@langchain/core/runnables";const system = `You have the ability to issue search queries to get information to help answer user information.If you need to look up two distinct pieces of information, you are allowed to do that!`;const prompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{question}"],]);const llmWithTools = llm.withStructuredOutput(searchSchema, { name: "Search",});const queryAnalyzer = RunnableSequence.from([ { question: new RunnablePassthrough(), }, prompt, llmWithTools,]); We can see that this allows for creating multiple queries await queryAnalyzer.invoke("where did Harrison Work"); { queries: [ "Harrison" ] } await queryAnalyzer.invoke("where did Harrison and ankush Work"); { queries: [ "Harrison work", "Ankush work" ] } Retrieval with query analysis[​](#retrieval-with-query-analysis "Direct link to Retrieval with query analysis") --------------------------------------------------------------------------------------------------------------- So how would we include this in a chain? One thing that will make this a lot easier is if we call our retriever asyncronously - this will let us loop over the queries and not get blocked on the response time. import { RunnableConfig, RunnableLambda } from "@langchain/core/runnables";const chain = async (question: string, config?: RunnableConfig) => { const response = await queryAnalyzer.invoke(question, config); const docs = []; for (const query of response.queries) { const newDocs = await retriever.invoke(query, config); docs.push(...newDocs); } // You probably want to think about reranking or deduplicating documents here // But that is a separate topic return docs;};const customChain = new RunnableLambda({ func: chain }); await customChain.invoke("where did Harrison Work"); [ Document { pageContent: "Harrison worked at Kensho", metadata: {} } ] await customChain.invoke("where did Harrison and ankush Work"); [ Document { pageContent: "Harrison worked at Kensho", metadata: {} }, Document { pageContent: "Ankush worked at Facebook", metadata: {} }] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned some techniques for handling multiple queries in a query analysis system. Next, check out some of the other query analysis guides in this section, like [how to deal with cases where no query is generated](/v0.2/docs/how_to/query_no_queries). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to deal with high cardinality categorical variables ](/v0.2/docs/how_to/query_high_cardinality)[ Next How to handle multiple retrievers ](/v0.2/docs/how_to/query_multiple_retrievers) * [Setup](#setup) * [Install dependencies](#install-dependencies) * [Set environment variables](#set-environment-variables) * [Create Index](#create-index) * [Query analysis](#query-analysis) * [Retrieval with query analysis](#retrieval-with-query-analysis) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/prompts_composition
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to compose prompts together On this page How to compose prompts together =============================== Prerequisites This guide assumes familiarity with the following concepts: * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) LangChain provides a user friendly interface for composing different parts of prompts together. You can do this with either string prompts or chat prompts. Constructing prompts this way allows for easy reuse of components. String prompt composition[​](#string-prompt-composition "Direct link to String prompt composition") --------------------------------------------------------------------------------------------------- When working with string prompts, each template is joined together. You can work with either prompts directly or strings (the first element in the list needs to be a prompt). import { PromptTemplate } from "@langchain/core/prompts";const prompt = PromptTemplate.fromTemplate( `Tell me a joke about {topic}, make it funny and in {language}`);prompt; PromptTemplate { lc_serializable: true, lc_kwargs: { inputVariables: [ "topic", "language" ], templateFormat: "f-string", template: "Tell me a joke about {topic}, make it funny and in {language}" }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "prompt" ], inputVariables: [ "topic", "language" ], outputParser: undefined, partialVariables: undefined, templateFormat: "f-string", template: "Tell me a joke about {topic}, make it funny and in {language}", validateTemplate: true} await prompt.format({ topic: "sports", language: "spanish" }); "Tell me a joke about sports, make it funny and in spanish" Chat prompt composition[​](#chat-prompt-composition "Direct link to Chat prompt composition") --------------------------------------------------------------------------------------------- A chat prompt is made up a of a list of messages. Similarly to the above example, we can concatenate chat prompt templates. Each new element is a new message in the final prompt. First, let’s initialize the a [`ChatPromptTemplate`](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.chat.ChatPromptTemplate.html) with a [`SystemMessage`](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.system.SystemMessage.html). import { AIMessage, HumanMessage, SystemMessage,} from "@langchain/core/messages";const prompt = new SystemMessage("You are a nice pirate"); You can then easily create a pipeline combining it with other messages _or_ message templates. Use a `BaseMessage` when there are no variables to be formatted, use a `MessageTemplate` when there are variables to be formatted. You can also use just a string (note: this will automatically get inferred as a [`HumanMessagePromptTemplate`](https://v02.api.js.langchain.com/classes/langchain_core_prompts.HumanMessagePromptTemplate.html).) import { HumanMessagePromptTemplate } from "@langchain/core/prompts";const newPrompt = HumanMessagePromptTemplate.fromTemplate([ prompt, new HumanMessage("Hi"), new AIMessage("what?"), "{input}",]); Under the hood, this creates an instance of the ChatPromptTemplate class, so you can use it just as you did before! await newPrompt.formatMessages({ input: "i said hi" }); [ HumanMessage { lc_serializable: true, lc_kwargs: { content: [ { type: "text", text: "You are a nice pirate" }, { type: "text", text: "Hi" }, { type: "text", text: "what?" }, { type: "text", text: "i said hi" } ], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: [ { type: "text", text: "You are a nice pirate" }, { type: "text", text: "Hi" }, { type: "text", text: "what?" }, { type: "text", text: "i said hi" } ], name: undefined, additional_kwargs: {}, response_metadata: {} }] Using PipelinePrompt[​](#using-pipelineprompt "Direct link to Using PipelinePrompt") ------------------------------------------------------------------------------------ LangChain includes a class called [`PipelinePromptTemplate`](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.pipeline.PipelinePromptTemplate.html), which can be useful when you want to reuse parts of prompts. A PipelinePrompt consists of two main parts: * Final prompt: The final prompt that is returned * Pipeline prompts: A list of tuples, consisting of a string name and a prompt template. Each prompt template will be formatted and then passed to future prompt templates as a variable with the same name. import { PromptTemplate, PipelinePromptTemplate,} from "@langchain/core/prompts";const fullPrompt = PromptTemplate.fromTemplate(`{introduction}{example}{start}`);const introductionPrompt = PromptTemplate.fromTemplate( `You are impersonating {person}.`);const examplePrompt = PromptTemplate.fromTemplate(`Here's an example of an interaction:Q: {example_q}A: {example_a}`);const startPrompt = PromptTemplate.fromTemplate(`Now, do this for real!Q: {input}A:`);const composedPrompt = new PipelinePromptTemplate({ pipelinePrompts: [ { name: "introduction", prompt: introductionPrompt, }, { name: "example", prompt: examplePrompt, }, { name: "start", prompt: startPrompt, }, ], finalPrompt: fullPrompt,}); const formattedPrompt = await composedPrompt.format({ person: "Elon Musk", example_q: `What's your favorite car?`, example_a: "Telsa", input: `What's your favorite social media site?`,});console.log(formattedPrompt); You are impersonating Elon Musk.Here's an example of an interaction:Q: What's your favorite car?A: TelsaNow, do this for real!Q: What's your favorite social media site?A: Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to compose prompts together. Next, check out the other how-to guides on prompt templates in this section, like [adding few-shot examples to your prompt templates](/v0.2/docs/how_to/few_shot_examples_chat). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to pass through arguments from one step to the next ](/v0.2/docs/how_to/passthrough)[ Next How to use legacy LangChain Agents (AgentExecutor) ](/v0.2/docs/how_to/agent_executor) * [String prompt composition](#string-prompt-composition) * [Chat prompt composition](#chat-prompt-composition) * [Using PipelinePrompt](#using-pipelineprompt) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/llm_chain
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build a Simple LLM Application with LCEL On this page Build a Simple LLM Application with LCEL ======================================== In this quickstart we’ll show you how to build a simple LLM application with LangChain. This application will translate text from English into another language. This is a relatively simple LLM application - it’s just a single LLM call plus some prompting. Still, this is a great way to get started with LangChain - a lot of features can be built with just some prompting and an LLM call! After reading this tutorial, you’ll have a high level overview of: * Using [language models](/v0.2/docs/concepts/#chat-models) * Using [PromptTemplates](/v0.2/docs/concepts/#prompt-templates) and [OutputParsers](/v0.2/docs/concepts/#output-parsers) * Using [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) to chain components together * Debugging and tracing your application using [LangSmith](/v0.2/docs/concepts/#langsmith) Let’s dive in! Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Installation[​](#installation "Direct link to Installation") To install LangChain run: * npm * yarn * pnpm npm i langchain yarn add langchain pnpm add langchain For more details, see our [Installation guide](/v0.2/docs/how_to/installation/). ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com). After you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2="true"export LANGCHAIN_API_KEY="..." Using Language Models[​](#using-language-models "Direct link to Using Language Models") --------------------------------------------------------------------------------------- First up, let’s learn how to use a language model by itself. LangChain supports many different language models that you can use interchangably - select the one you want to use below! ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI(model: "gpt-4"); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); Let’s first use the model directly. `ChatModel`s are instances of LangChain “Runnables”, which means they expose a standard interface for interacting with them. To just simply call the model, we can pass in a list of messages to the `.invoke` method. import { HumanMessage, SystemMessage } from "@langchain/core/messages";const messages = [ new SystemMessage("Translate the following from English into Italian"), new HumanMessage("hi!"),];await model.invoke(messages); AIMessage { lc_serializable: true, lc_kwargs: { content: "ciao!", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "ciao!", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 3, promptTokens: 20, totalTokens: 23 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} If we’ve enable LangSmith, we can see that this run is logged to LangSmith, and can see the [LangSmith trace](https://smith.langchain.com/public/45f1a650-38fb-41e1-9b61-becc0684f2ce/r) OutputParsers[​](#outputparsers "Direct link to OutputParsers") --------------------------------------------------------------- Notice that the response from the model is an `AIMessage`. This contains a string response along with other metadata about the response. Oftentimes we may just want to work with the string response. We can parse out just this response by using a simple output parser. We first import the simple output parser. import { StringOutputParser } from "@langchain/core/output_parsers";const parser = new StringOutputParser(); One way to use it is to use it by itself. For example, we could save the result of the language model call and then pass it to the parser. const result = await model.invoke(messages); await parser.invoke(result); "ciao!" Chaining together components with LCEL[​](#chaining-together-components-with-lcel "Direct link to Chaining together components with LCEL") ------------------------------------------------------------------------------------------------------------------------------------------ We can also “chain” the model to the output parser. This means this output parser will get called with the output from the model. This chain takes on the input type of the language model (string or list of message) and returns the output type of the output parser (string). We can create the chain using the `.pipe()` method. The `.pipe()` method is used in LangChain to combine two elements together. const chain = model.pipe(parser); await chain.invoke(messages); "Ciao!" This is a simple example of using [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) to chain together LangChain modules. There are several benefits to this approach, including optimized streaming and tracing support. If we now look at LangSmith, we can see that the chain has two steps: first the language model is called, then the result of that is passed to the output parser. We can see the [LangSmith trace](https://smith.langchain.com/public/05bec1c1-fc51-4b2c-ab3b-4b63709e4462/r) Prompt Templates[​](#prompt-templates "Direct link to Prompt Templates") ------------------------------------------------------------------------ Right now we are passing a list of messages directly into the language model. Where does this list of messages come from? Usually it constructed from a combination of user input and application logic. This application logic usually takes the raw user input and transforms it into a list of messages ready to pass to the language model. Common transformations include adding a system message or formatting a template with the user input. PromptTemplates are a concept in LangChain designed to assist with this transformation. They take in raw user input and return data (a prompt) that is ready to pass into a language model. Let’s create a PromptTemplate here. It will take in two user variables: * `language`: The language to translate text into * `text`: The text to translate import { ChatPromptTemplate } from "@langchain/core/prompts"; First, let’s create a string that we will format to be the system message: const systemTemplate = "Translate the following into {language}:"; Next, we can create the PromptTemplate. This will be a combination of the `systemTemplate` as well as a simpler template for where to put the text const promptTemplate = ChatPromptTemplate.fromMessages([ ["system", systemTemplate], ["user", "{text}"],]); The input to this prompt template is a dictionary. We can play around with this prompt template by itself to see what it does by itself const result = await promptTemplate.invoke({ language: "italian", text: "hi" });result; ChatPromptValue { lc_serializable: true, lc_kwargs: { messages: [ SystemMessage { lc_serializable: true, lc_kwargs: { content: "Translate the following into italian:", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Translate the following into italian:", name: undefined, additional_kwargs: {}, response_metadata: {} }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "hi", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "hi", name: undefined, additional_kwargs: {}, response_metadata: {} } ] }, lc_namespace: [ "langchain_core", "prompt_values" ], messages: [ SystemMessage { lc_serializable: true, lc_kwargs: { content: "Translate the following into italian:", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Translate the following into italian:", name: undefined, additional_kwargs: {}, response_metadata: {} }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "hi", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "hi", name: undefined, additional_kwargs: {}, response_metadata: {} } ]} We can see that it returns a `ChatPromptValue` that consists of two messages. If we want to access the messages directly we do: result.toChatMessages(); [ SystemMessage { lc_serializable: true, lc_kwargs: { content: "Translate the following into italian:", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Translate the following into italian:", name: undefined, additional_kwargs: {}, response_metadata: {} }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "hi", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "hi", name: undefined, additional_kwargs: {}, response_metadata: {} }] We can now combine this with the model and the output parser from above. This will chain all three components together. const chain = promptTemplate.pipe(model).pipe(parser); await chain.invoke({ language: "italian", text: "hi" }); "ciao" If we take a look at the LangSmith trace, we can see all three components show up in the [LangSmith trace](https://smith.langchain.com/public/cef6edcd-39ed-4c1e-86f7-491a1b611aeb/r) Conclusion[​](#conclusion "Direct link to Conclusion") ------------------------------------------------------ That’s it! In this tutorial you’ve learned how to create your first simple LLM application. You’ve learned how to work with language models, how to parse their outputs, how to create a prompt template, chaining them together with LCEL, and how to get great observability into chains you create with LangSmith. This just scratches the surface of what you will want to learn to become a proficient AI Engineer. Luckily - we’ve got a lot of other resources! For further reading on the core concepts of LangChain, we’ve got detailed [Conceptual Guides](/v0.2/docs/concepts). If you have more specific questions on these concepts, check out the following sections of the how-to guides: * [LangChain Expression Language (LCEL)](/v0.2/docs/how_to/#langchain-expression-language) * [Prompt templates](/v0.2/docs/how_to/#prompt-templates) * [Chat models](/v0.2/docs/how_to/#chat-models) * [Output parsers](/v0.2/docs/how_to/#output-parsers) And the LangSmith docs: * [LangSmith](https://docs.smith.langchain.com) * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Tutorials ](/v0.2/docs/tutorials/)[ Next Build a Chatbot ](/v0.2/docs/tutorials/chatbot) * [Setup](#setup) * [Installation](#installation) * [LangSmith](#langsmith) * [Using Language Models](#using-language-models) * [OutputParsers](#outputparsers) * [Chaining together components with LCEL](#chaining-together-components-with-lcel) * [Prompt Templates](#prompt-templates) * [Conclusion](#conclusion)
null
https://js.langchain.com/v0.2/docs/how_to/query_multiple_retrievers
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to handle multiple retrievers On this page How to handle multiple retrievers ================================= Prerequisites This guide assumes familiarity with the following: * [Query analysis](/v0.2/docs/tutorials/query_analysis) Sometimes, a query analysis technique may allow for selection of which retriever to use. To use this, you will need to add some logic to select the retriever to do. We will show a simple example (using mock data) of how to do that. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community @langchain/openai zod chromadb yarn add @langchain/community @langchain/openai zod chromadb pnpm add @langchain/community @langchain/openai zod chromadb ### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true ### Create Index[​](#create-index "Direct link to Create Index") We will create a vectorstore over fake information. import { Chroma } from "@langchain/community/vectorstores/chroma";import { OpenAIEmbeddings } from "@langchain/openai";import "chromadb";const texts = ["Harrison worked at Kensho"];const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small" });const vectorstore = await Chroma.fromTexts(texts, {}, embeddings, { collectionName: "harrison",});const retrieverHarrison = vectorstore.asRetriever(1);const texts = ["Ankush worked at Facebook"];const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small" });const vectorstore = await Chroma.fromTexts(texts, {}, embeddings, { collectionName: "ankush",});const retrieverAnkush = vectorstore.asRetriever(1); Query analysis[​](#query-analysis "Direct link to Query analysis") ------------------------------------------------------------------ We will use function calling to structure the output. We will let it return multiple queries. import { z } from "zod";const searchSchema = z.object({ query: z.string().describe("Query to look up"), person: z .string() .describe( "Person to look things up for. Should be `HARRISON` or `ANKUSH`." ),}); ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnableSequence, RunnablePassthrough,} from "@langchain/core/runnables";const system = `You have the ability to issue search queries to get information to help answer user information.`;const prompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{question}"],]);const llmWithTools = llm.withStructuredOutput(searchSchema, { name: "Search",});const queryAnalyzer = RunnableSequence.from([ { question: new RunnablePassthrough(), }, prompt, llmWithTools,]); We can see that this allows for routing between retrievers await queryAnalyzer.invoke("where did Harrison Work"); { query: "workplace of Harrison", person: "HARRISON" } await queryAnalyzer.invoke("where did ankush Work"); { query: "Workplace of Ankush", person: "ANKUSH" } Retrieval with query analysis[​](#retrieval-with-query-analysis "Direct link to Retrieval with query analysis") --------------------------------------------------------------------------------------------------------------- So how would we include this in a chain? We just need some simple logic to select the retriever and pass in the search query const retrievers = { HARRISON: retrieverHarrison, ANKUSH: retrieverAnkush,}; import { RunnableConfig, RunnableLambda } from "@langchain/core/runnables";const chain = async (question: string, config?: RunnableConfig) => { const response = await queryAnalyzer.invoke(question, config); const retriever = retrievers[response.person]; return retriever.invoke(response.query, config);};const customChain = new RunnableLambda({ func: chain }); await customChain.invoke("where did Harrison Work"); [ Document { pageContent: "Harrison worked at Kensho", metadata: {} } ] await customChain.invoke("where did ankush Work"); [ Document { pageContent: "Ankush worked at Facebook", metadata: {} } ] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned some techniques for handling multiple retrievers in a query analysis system. Next, check out some of the other query analysis guides in this section, like [how to deal with cases where no query is generated](/v0.2/docs/how_to/query_no_queries). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to handle multiple queries ](/v0.2/docs/how_to/query_multiple_queries)[ Next How to handle cases where no queries are generated ](/v0.2/docs/how_to/query_no_queries) * [Setup](#setup) * [Install dependencies](#install-dependencies) * [Set environment variables](#set-environment-variables) * [Create Index](#create-index) * [Query analysis](#query-analysis) * [Retrieval with query analysis](#retrieval-with-query-analysis) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/chatbot
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build a Chatbot On this page Build a Chatbot =============== Overview[​](#overview "Direct link to Overview") ------------------------------------------------ Prerequisites This guide assumes familiarity with the following concepts: * [Chat Models](/v0.2/docs/concepts/#chat-models) * [Prompt Templates](/v0.2/docs/concepts/#prompt-templates) * [Chat History](/v0.2/docs/concepts/#chat-history) We’ll go over an example of how to design and implement an LLM-powered chatbot. This chatbot will be able to have a conversation and remember previous interactions. Note that this chatbot that we build will only use the language model to have a conversation. There are several other related concepts that you may be looking for: * [Conversational RAG](/v0.2/docs/tutorials/qa_chat_history): Enable a chatbot experience over an external source of data * [Agents](/v0.2/docs/tutorials/agents): Build a chatbot that can take actions This tutorial will cover the basics which will be helpful for those two more advanced topics, but feel free to skip directly to there should you choose. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Installation[​](#installation "Direct link to Installation") To install LangChain run: * npm * yarn * pnpm npm i langchain yarn add langchain pnpm add langchain For more details, see our [Installation guide](/v0.2/docs/how_to/installation). ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com). After you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2="true"export LANGCHAIN_API_KEY="..." Quickstart[​](#quickstart "Direct link to Quickstart") ------------------------------------------------------ First up, let’s learn how to use a language model by itself. LangChain supports many different language models that you can use interchangably - select the one you want to use below! ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI(model="gpt-3.5-turbo"); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); Let’s first use the model directly. `ChatModel`s are instances of LangChain “Runnables”, which means they expose a standard interface for interacting with them. To just simply call the model, we can pass in a list of messages to the `.invoke` method. import { HumanMessage } from "@langchain/core/messages";await model.invoke([new HumanMessage({ content: "Hi! I'm Bob" })]); AIMessage { lc_serializable: true, lc_kwargs: { content: "Hello Bob, it's nice to meet you! I'm an AI assistant created by Anthropic. How are you doing today?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_015Qvu91azZviks5VzGvYT7z", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 12, output_tokens: 30 }, stop_reason: "end_turn" }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello Bob, it's nice to meet you! I'm an AI assistant created by Anthropic. How are you doing today?", name: undefined, additional_kwargs: { id: "msg_015Qvu91azZviks5VzGvYT7z", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 12, output_tokens: 30 }, stop_reason: "end_turn" }, response_metadata: { id: "msg_015Qvu91azZviks5VzGvYT7z", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 12, output_tokens: 30 }, stop_reason: "end_turn" }, tool_calls: [], invalid_tool_calls: []} The model on its own does not have any concept of state. For example, if you ask a followup question: await model.invoke([new HumanMessage({ content: "What's my name?" })]); AIMessage { lc_serializable: true, lc_kwargs: { content: "I'm afraid I don't actually know your name. I'm Claude, an AI assistant created by Anthropic.", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_01TNDCwsU7ruVoqJwjKqNrzJ", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 12, output_tokens: 27 }, stop_reason: "end_turn" }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "I'm afraid I don't actually know your name. I'm Claude, an AI assistant created by Anthropic.", name: undefined, additional_kwargs: { id: "msg_01TNDCwsU7ruVoqJwjKqNrzJ", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 12, output_tokens: 27 }, stop_reason: "end_turn" }, response_metadata: { id: "msg_01TNDCwsU7ruVoqJwjKqNrzJ", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 12, output_tokens: 27 }, stop_reason: "end_turn" }, tool_calls: [], invalid_tool_calls: []} Let’s take a look at the example [LangSmith trace](https://smith.langchain.com/public/e5a0ae1b-32b9-4beb-836d-38f40bfa6762/r) We can see that it doesn’t take the previous conversation turn into context, and cannot answer the question. This makes for a terrible chatbot experience! To get around this, we need to pass the entire conversation history into the model. Let’s see what happens when we do that: import { AIMessage } from "@langchain/core/messages";await model.invoke([ new HumanMessage({ content: "Hi! I'm Bob" }), new AIMessage({ content: "Hello Bob! How can I assist you today?" }), new HumanMessage({ content: "What's my name?" }),]); AIMessage { lc_serializable: true, lc_kwargs: { content: "You said your name is Bob.", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_01AEQMme3Z1MFKHW8PeDBJ7g", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 33, output_tokens: 10 }, stop_reason: "end_turn" }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "You said your name is Bob.", name: undefined, additional_kwargs: { id: "msg_01AEQMme3Z1MFKHW8PeDBJ7g", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 33, output_tokens: 10 }, stop_reason: "end_turn" }, response_metadata: { id: "msg_01AEQMme3Z1MFKHW8PeDBJ7g", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 33, output_tokens: 10 }, stop_reason: "end_turn" }, tool_calls: [], invalid_tool_calls: []} And now we can see that we get a good response! This is the basic idea underpinning a chatbot’s ability to interact conversationally. So how do we best implement this? Message History[​](#message-history "Direct link to Message History") --------------------------------------------------------------------- We can use a Message History class to wrap our model and make it stateful. This will keep track of inputs and outputs of the model, and store them in some datastore. Future interactions will then load those messages and pass them into the chain as part of the input. Let’s see how to use this! We import the relevant classes and set up our chain which wraps the model and adds in this message history. A key part here is the function we pass into as the `getSessionHistory()`. This function is expected to take in a `sessionId` and return a Message History object. This `sessionId` is used to distinguish between separate conversations, and should be passed in as part of the config when calling the new chain. Let’s also create a simple chain by adding a prompt to help with formatting: // We use an ephemeral, in-memory chat history for this demo.import { InMemoryChatMessageHistory } from "@langchain/core/chat_history";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnableWithMessageHistory } from "@langchain/core/runnables";const messageHistories: Record<string, InMemoryChatMessageHistory> = {};const prompt = ChatPromptTemplate.fromMessages([ [ "system", `You are a helpful assistant who remembers all details the user shares with you.`, ], ["placeholder", "{chat_history}"], ["human", "{input}"],]);const chain = prompt.pipe(model);const withMessageHistory = new RunnableWithMessageHistory({ runnable: chain, getMessageHistory: async (sessionId) => { if (messageHistories[sessionId] === undefined) { messageHistories[sessionId] = new InMemoryChatMessageHistory(); } return messageHistories[sessionId]; }, inputMessagesKey: "input", historyMessagesKey: "chat_history",}); We now need to create a `config` that we pass into the runnable every time. This config contains information that is not part of the input directly, but is still useful. In this case, we want to include a `session_id`. This should look like: const config = { configurable: { sessionId: "abc2", },};const response = await withMessageHistory.invoke( { input: "Hi! I'm Bob", }, config);response.content; "Hi Bob, nice to meet you! I'm an AI assistant. I'll remember that your name is Bob as we continue ou"... 110 more characters const followupResponse = await withMessageHistory.invoke( { input: "What's my name?", }, config);followupResponse.content; "Your name is Bob. You introduced yourself as Bob at the start of our conversation." Great! Our chatbot now remembers things about us. If we change the config to reference a different `session_id`, we can see that it starts the conversation fresh. const config = { configurable: { sessionId: "abc3", },};const response = await withMessageHistory.invoke( { input: "What's my name?", }, config);response.content; "I'm afraid I don't actually know your name. As an AI assistant without any prior context about you, "... 61 more characters However, we can always go back to the original conversation (since we are persisting it in a database) const config = { configurable: { sessionId: "abc2", },};const response = await withMessageHistory.invoke( { input: "What's my name?", }, config);response.content; `Your name is Bob. I clearly remember you telling me "Hi! I'm Bob" when we started talking.` This is how we can support a chatbot having conversations with many users! Managing Conversation History[​](#managing-conversation-history "Direct link to Managing Conversation History") --------------------------------------------------------------------------------------------------------------- One important concept to understand when building chatbots is how to manage conversation history. If left unmanaged, the list of messages will grow unbounded and potentially overflow the context window of the LLM. Therefore, it is important to add a step that limits the size of the messages you are passing in. **Importantly, you will want to do this BEFORE the prompt template but AFTER you load previous messages from Message History.** We can do this by adding a simple step in front of the prompt that modifies the `chat_history` key appropriately, and then wrap that new chain in the Message History class. First, let’s define a function that will modify the messages passed in. Let’s make it so that it selects the 10 most recent messages. We can then create a new chain by adding that at the start. import type { BaseMessage } from "@langchain/core/messages";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";const filterMessages = ({ chat_history }: { chat_history: BaseMessage[] }) => { return chat_history.slice(-10);};const chain = RunnableSequence.from([ RunnablePassthrough.assign({ chat_history: filterMessages, }), prompt, model,]); Let’s now try it out! If we create a list of messages more than 10 messages long, we can see what it no longer remembers information in the early messages. const messages = [ new HumanMessage({ content: "hi! I'm bob" }), new AIMessage({ content: "hi!" }), new HumanMessage({ content: "I like vanilla ice cream" }), new AIMessage({ content: "nice" }), new HumanMessage({ content: "whats 2 + 2" }), new AIMessage({ content: "4" }), new HumanMessage({ content: "thanks" }), new AIMessage({ content: "No problem!" }), new HumanMessage({ content: "having fun?" }), new AIMessage({ content: "yes!" }), new HumanMessage({ content: "That's great!" }), new AIMessage({ content: "yes it is!" }),]; const response = await chain.invoke({ chat_history: messages, input: "what's my name?",});response.content; "I'm afraid I don't actually know your name. You haven't provided that detail to me yet." But if we ask about information that is within the last ten messages, it still remembers it const response = await chain.invoke({ chat_history: messages, input: "what's my fav ice cream",});response.content; "You said earlier that you like vanilla ice cream." Let’s now wrap this chain in a `RunnableWithMessageHistory` constructor. For demo purposes, we will also slightly modify our `getMessageHistory()` method to always start new sessions with the previously declared list of 10 messages to simulate several conversation turns: const messageHistories: Record<string, InMemoryChatMessageHistory> = {};const withMessageHistory = new RunnableWithMessageHistory({ runnable: chain, getMessageHistory: async (sessionId) => { if (messageHistories[sessionId] === undefined) { const messageHistory = new InMemoryChatMessageHistory(); await messageHistory.addMessages(messages); messageHistories[sessionId] = messageHistory; } return messageHistories[sessionId]; }, inputMessagesKey: "input", historyMessagesKey: "chat_history",});const config = { configurable: { sessionId: "abc4", },};const response = await withMessageHistory.invoke( { input: "whats my name?", }, config);response.content; "I'm afraid I don't actually know your name since you haven't provided it to me yet. I don't have pe"... 66 more characters There’s now two new messages in the chat history. This means that even more information that used to be accessible in our conversation history is no longer available! const response = await withMessageHistory.invoke( { input: "whats my favorite ice cream?", }, config);response.content; "I'm sorry, I don't have any information about your favorite ice cream flavor since you haven't share"... 167 more characters If you take a look at LangSmith, you can see exactly what is happening under the hood in the [LangSmith trace](https://smith.langchain.com/public/ebc2e1e7-0703-43f7-a476-8cb8cbd7f61a/r). Navigate to the chat model call to see exactly which messages are getting filtered out. Streaming[​](#streaming "Direct link to Streaming") --------------------------------------------------- Now we’ve got a functional chatbot. However, one _really_ important UX consideration for chatbot application is streaming. LLMs can sometimes take a while to respond, and so in order to improve the user experience one thing that most application do is stream back each token as it is generated. This allows the user to see progress. It’s actually super easy to do this! All chains expose a `.stream()` method, and ones that use message history are no different. We can simply use that method to get back a streaming response. const config = { configurable: { sessionId: "abc6", },};const stream = await withMessageHistory.stream( { input: "hi! I'm todd. tell me a joke", }, config);for await (const chunk of stream) { console.log("|", chunk.content);} || Hi| Tod| d!| Here| 's| a| silly| joke| for| you| :|Why| di| d the| tom| ato| turn| re| d?| Because| it| saw| the| sal| a| d| dressing| !|| Next Steps[​](#next-steps "Direct link to Next Steps") ------------------------------------------------------ Now that you understand the basics of how to create a chatbot in LangChain, some more advanced tutorials you may be interested in are: * [Conversational RAG](/v0.2/docs/tutorials/qa_chat_history): Enable a chatbot experience over an external source of data * [Agents](/v0.2/docs/tutorials/agents): Build a chatbot that can take actions If you want to dive deeper on specifics, some things worth checking out are: * [Streaming](/v0.2/docs/how_to/streaming): streaming is _crucial_ for chat applications * [How to add message history](/v0.2/docs/how_to/message_history): for a deeper dive into all things related to message history * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build a Simple LLM Application with LCEL ](/v0.2/docs/tutorials/llm_chain)[ Next Build an Agent ](/v0.2/docs/tutorials/agents) * [Overview](#overview) * [Setup](#setup) * [Installation](#installation) * [LangSmith](#langsmith) * [Quickstart](#quickstart) * [Message History](#message-history) * [Managing Conversation History](#managing-conversation-history) * [Streaming](#streaming) * [Next Steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/agent_executor
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use legacy LangChain Agents (AgentExecutor) On this page How to use legacy LangChain Agents (AgentExecutor) ================================================== Prerequisites This guide assumes familiarity with the following concepts: * [Tools](/v0.2/docs/concepts#tools) By themselves, language models can’t take actions - they just output text. Agents are systems that use an LLM as a reasoning engine to determine which actions to take and what the inputs to those actions should be. The results of those actions can then be fed back into the agent and it determine whether more actions are needed, or whether it is okay to finish. In this tutorial we will build an agent that can interact with multiple different tools: one being a local database, the other being a search engine. You will be able to ask this agent questions, watch it call tools, and have conversations with it. info This section will cover building with LangChain Agents. LangChain Agents are fine for getting started, but past a certain point you will likely want flexibility and control that they do not offer. For working with more advanced agents, we’d recommend checking out [LangGraph](/v0.2/docs/concepts/#langgraph). Concepts[​](#concepts "Direct link to Concepts") ------------------------------------------------ Concepts we will cover are: - Using [language models](/v0.2/docs/concepts/#chat-models), in particular their tool calling ability - Creating a [Retriever](/v0.2/docs/concepts/#retrievers) to expose specific information to our agent - Using a Search [Tool](/v0.2/docs/concepts/#tools) to look up things online - [`Chat History`](/v0.2/docs/concepts/#chat-history), which allows a chatbot to “remember” past interactions and take them into account when responding to followup questions. - Debugging and tracing your application using [LangSmith](/v0.2/docs/concepts/#langsmith) Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Jupyter Notebook[​](#jupyter-notebook "Direct link to Jupyter Notebook") This guide (and most of the other guides in the documentation) uses [Jupyter notebooks](https://jupyter.org/) and assumes the reader is as well. Jupyter notebooks are perfect for learning how to work with LLM systems because oftentimes things can go wrong (unexpected output, API down, etc) and going through guides in an interactive environment is a great way to better understand them. This and other tutorials are perhaps most conveniently run in a Jupyter notebook. See [here](https://jupyter.org/install) for instructions on how to install. ### Installation[​](#installation "Direct link to Installation") To install LangChain (and `cheerio` for the web loader) run: * npm * yarn * pnpm npm i langchain cheerio yarn add langchain cheerio pnpm add langchain cheerio For more details, see our [Installation guide](/v0.2/docs/how_to/installation/). ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com). After you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2="true"export LANGCHAIN_API_KEY="..." Define tools[​](#define-tools "Direct link to Define tools") ------------------------------------------------------------ We first need to create the tools we want to use. We will use two tools: [Tavily](/v0.2/docs/integrations/tools/tavily_search) (to search online) and then a retriever over a local index we will create ### [Tavily](/v0.2/docs/integrations/tools/tavily_search)[​](#tavily "Direct link to tavily") We have a built-in tool in LangChain to easily use Tavily search engine as tool. Note that this requires an API key - they have a free tier, but if you don’t have one or don’t want to create one, you can always ignore this step. Once you create your API key, you will need to export that as: export TAVILY_API_KEY="..." import "cheerio"; // This is required in notebooks to use the `CheerioWebBaseLoader`import { TavilySearchResults } from "@langchain/community/tools/tavily_search";const search = new TavilySearchResults({ maxResults: 2,});await search.invoke("what is the weather in SF"); `[{"title":"Weather in San Francisco","url":"https://www.weatherapi.com/","content":"{'location': {'n`... 1347 more characters ### Retriever[​](#retriever "Direct link to Retriever") We will also create a retriever over some data of our own. For a deeper explanation of each step here, see [this tutorial](/v0.2/docs/tutorials/rag). import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings } from "@langchain/openai";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";const loader = new CheerioWebBaseLoader( "https://docs.smith.langchain.com/overview");const docs = await loader.load();const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const documents = await splitter.splitDocuments(docs);const vectorStore = await MemoryVectorStore.fromDocuments( documents, new OpenAIEmbeddings());const retriever = vectorStore.asRetriever();(await retriever.invoke("how to upload a dataset"))[0]; Document { pageContent: 'description="A sample dataset in LangSmith.")client.create_examples( inputs=[ {"postfix": '... 891 more characters, metadata: { source: "https://docs.smith.langchain.com/overview", loc: { lines: { from: 4, to: 4 } } }} Now that we have populated our index that we will do doing retrieval over, we can easily turn it into a tool (the format needed for an agent to properly use it) import { createRetrieverTool } from "langchain/tools/retriever";const retrieverTool = await createRetrieverTool(retriever, { name: "langsmith_search", description: "Search for information about LangSmith. For any questions about LangSmith, you must use this tool!",}); ### Tools[​](#tools "Direct link to Tools") Now that we have created both, we can create a list of tools that we will use downstream. const tools = [search, retrieverTool]; Using Language Models[​](#using-language-models "Direct link to Using Language Models") --------------------------------------------------------------------------------------- Next, let’s learn how to use a language model by to call tools. LangChain supports many different language models that you can use interchangably - select the one you want to use below! ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI(model: "gpt-4"); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); You can call the language model by passing in a list of messages. By default, the response is a `content` string. import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-4", temperature: 0 });import { HumanMessage } from "@langchain/core/messages";const response = await model.invoke([new HumanMessage("hi!")]);response.content; "Hello! How can I assist you today?" We can now see what it is like to enable this model to do tool calling. In order to enable that we use `.bind` to give the language model knowledge of these tools const modelWithTools = model.bindTools(tools); We can now call the model. Let’s first call it with a normal message, and see how it responds. We can look at both the `content` field as well as the `tool_calls` field. const response = await modelWithTools.invoke([new HumanMessage("Hi!")]);console.log(`Content: ${response.content}`);console.log(`Tool calls: ${response.tool_calls}`); Content: Hello! How can I assist you today?Tool calls: Now, let’s try calling it with some input that would expect a tool to be called. const response = await modelWithTools.invoke([ new HumanMessage("What's the weather in SF?"),]);console.log(`Content: ${response.content}`);console.log(`Tool calls: ${JSON.stringify(response.tool_calls, null, 2)}`); Content:Tool calls: [ { "name": "tavily_search_results_json", "args": { "input": "current weather in San Francisco" }, "id": "call_VcSjZAZkEOx9lcHNZNXAjXkm" }] We can see that there’s now no content, but there is a tool call! It wants us to call the Tavily Search tool. This isn’t calling that tool yet - it’s just telling us to. In order to actually calll it, we’ll want to create our agent. Create the agent[​](#create-the-agent "Direct link to Create the agent") ------------------------------------------------------------------------ Now that we have defined the tools and the LLM, we can create the agent. We will be using a tool calling agent - for more information on this type of agent, as well as other options, see [this guide](/v0.2/docs/concepts/#agent_types/). We can first choose the prompt we want to use to guide the agent: import { ChatPromptTemplate } from "@langchain/core/prompts";const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant"], ["placeholder", "{chat_history}"], ["human", "{input}"], ["placeholder", "{agent_scratchpad}"],]);console.log(prompt.promptMessages); [ SystemMessagePromptTemplate { lc_serializable: true, lc_kwargs: { prompt: PromptTemplate { lc_serializable: true, lc_kwargs: { inputVariables: [], templateFormat: "f-string", template: "You are a helpful assistant" }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "prompt" ], inputVariables: [], outputParser: undefined, partialVariables: undefined, templateFormat: "f-string", template: "You are a helpful assistant", validateTemplate: true } }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "chat" ], inputVariables: [], additionalOptions: {}, prompt: PromptTemplate { lc_serializable: true, lc_kwargs: { inputVariables: [], templateFormat: "f-string", template: "You are a helpful assistant" }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "prompt" ], inputVariables: [], outputParser: undefined, partialVariables: undefined, templateFormat: "f-string", template: "You are a helpful assistant", validateTemplate: true }, messageClass: undefined, chatMessageClass: undefined }, MessagesPlaceholder { lc_serializable: true, lc_kwargs: { variableName: "chat_history", optional: true }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "chat" ], variableName: "chat_history", optional: true }, HumanMessagePromptTemplate { lc_serializable: true, lc_kwargs: { prompt: PromptTemplate { lc_serializable: true, lc_kwargs: { inputVariables: [Array], templateFormat: "f-string", template: "{input}" }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "prompt" ], inputVariables: [ "input" ], outputParser: undefined, partialVariables: undefined, templateFormat: "f-string", template: "{input}", validateTemplate: true } }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "chat" ], inputVariables: [ "input" ], additionalOptions: {}, prompt: PromptTemplate { lc_serializable: true, lc_kwargs: { inputVariables: [ "input" ], templateFormat: "f-string", template: "{input}" }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "prompt" ], inputVariables: [ "input" ], outputParser: undefined, partialVariables: undefined, templateFormat: "f-string", template: "{input}", validateTemplate: true }, messageClass: undefined, chatMessageClass: undefined }, MessagesPlaceholder { lc_serializable: true, lc_kwargs: { variableName: "agent_scratchpad", optional: true }, lc_runnable: true, name: undefined, lc_namespace: [ "langchain_core", "prompts", "chat" ], variableName: "agent_scratchpad", optional: true }] Now, we can initalize the agent with the LLM, the prompt, and the tools. The agent is responsible for taking in input and deciding what actions to take. Crucially, the Agent does not execute those actions - that is done by the AgentExecutor (next step). For more information about how to think about these components, see our [conceptual guide](/v0.2/docs/concepts/#agents). Note that we are passing in the `model`, not `modelWithTools`. That is because `createToolCallingAgent` will call `.bind` for us under the hood. import { createToolCallingAgent } from "langchain/agents";const agent = await createToolCallingAgent({ llm: model, tools, prompt }); Finally, we combine the agent (the brains) with the tools inside the AgentExecutor (which will repeatedly call the agent and execute tools). import { AgentExecutor } from "langchain/agents";const agentExecutor = new AgentExecutor({ agent, tools,}); Run the agent[​](#run-the-agent "Direct link to Run the agent") --------------------------------------------------------------- We can now run the agent on a few queries! Note that for now, these are all **stateless** queries (it won’t remember previous interactions). First up, let’s how it responds when there’s no need to call a tool: await agentExecutor.invoke({ input: "hi!" }); { input: "hi!", output: "Hello! How can I assist you today?" } In order to see exactly what is happening under the hood (and to make sure it’s not calling a tool) we can take a look at the [LangSmith trace](https://smith.langchain.com/public/b8051e80-14fd-4931-be0f-6416280bc500/r) Let’s now try it out on an example where it should be invoking the retriever await agentExecutor.invoke({ input: "how can langsmith help with testing?" }); { input: "how can langsmith help with testing?", output: "LangSmith can be a valuable tool for testing in several ways:\n" + "\n" + "1. **Logging Traces**: LangSmith prov"... 960 more characters} Let’s take a look at the [LangSmith trace](https://smith.langchain.com/public/35bd4f0f-aa2f-4ac2-b9a9-89ce0ca306ca/r) to make sure it’s actually calling that. Now let’s try one where it needs to call the search tool: await agentExecutor.invoke({ input: "whats the weather in sf?" }); { input: "whats the weather in sf?", output: "The current weather in San Francisco, California is partly cloudy with a temperature of 12.2°C (54.0"... 176 more characters} We can check out the [LangSmith trace](https://smith.langchain.com/public/dfde6f46-0e7b-4dfe-813c-87d7bfb2ade5/r) to make sure it’s calling the search tool effectively. Adding in memory[​](#adding-in-memory "Direct link to Adding in memory") ------------------------------------------------------------------------ As mentioned earlier, this agent is stateless. This means it does not remember previous interactions. To give it memory we need to pass in previous `chat_history`. **Note**: The input variable needs to be called `chat_history` because of the prompt we are using. If we use a different prompt, we could change the variable name. // Here we pass in an empty list of messages for chat_history because it is the first message in the chatawait agentExecutor.invoke({ input: "hi! my name is bob", chat_history: [] }); { input: "hi! my name is bob", chat_history: [], output: "Hello Bob! How can I assist you today?"} import { AIMessage, HumanMessage } from "@langchain/core/messages";await agentExecutor.invoke({ chat_history: [ new HumanMessage("hi! my name is bob"), new AIMessage("Hello Bob! How can I assist you today?"), ], input: "what's my name?",}); { chat_history: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "hi! my name is bob", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "hi! my name is bob", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Hello Bob! How can I assist you today?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello Bob! How can I assist you today?", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] } ], input: "what's my name?", output: "Your name is Bob. How can I assist you further?"} If we want to keep track of these messages automatically, we can wrap this in a RunnableWithMessageHistory. Because we have multiple inputs, we need to specify two things: * `inputMessagesKey`: The input key to use to add to the conversation history. * `historyMessagesKey`: The key to add the loaded messages into. For more information on how to use this, see [this guide](/v0.2/docs/how_to/message_history). import { ChatMessageHistory } from "@langchain/community/stores/message/in_memory";import { BaseChatMessageHistory } from "@langchain/core/chat_history";import { RunnableWithMessageHistory } from "@langchain/core/runnables";const store = {};function getMessageHistory(sessionId: string): BaseChatMessageHistory { if (!(sessionId in store)) { store[sessionId] = new ChatMessageHistory(); } return store[sessionId];}const agentWithChatHistory = new RunnableWithMessageHistory({ runnable: agentExecutor, getMessageHistory, inputMessagesKey: "input", historyMessagesKey: "chat_history",});await agentWithChatHistory.invoke( { input: "hi! I'm bob" }, { configurable: { sessionId: "<foo>" } }); { input: "hi! I'm bob", chat_history: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "hi! I'm bob", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "hi! I'm bob", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Hello, Bob! How can I assist you today?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello, Bob! How can I assist you today?", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] } ], output: "Hello, Bob! How can I assist you today?"} await agentWithChatHistory.invoke( { input: "what's my name?" }, { configurable: { sessionId: "<foo>" } }); { input: "what's my name?", chat_history: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "hi! I'm bob", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "hi! I'm bob", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Hello, Bob! How can I assist you today?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello, Bob! How can I assist you today?", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "what's my name?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "what's my name?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Your name is Bob. How can I assist you further?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Your name is Bob. How can I assist you further?", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] } ], output: "Your name is Bob. How can I assist you further?"} Example LangSmith trace: [https://smith.langchain.com/public/98c8d162-60ae-4493-aa9f-992d87bd0429/r](https://smith.langchain.com/public/98c8d162-60ae-4493-aa9f-992d87bd0429/r) Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ That’s a wrap! In this quick start we covered how to create a simple agent. Agents are a complex topic, and there’s lot to learn! info This section covered building with LangChain Agents. LangChain Agents are fine for getting started, but past a certain point you will likely want flexibility and control that they do not offer. For working with more advanced agents, we’d recommend checking out [LangGraph](/v0.2/docs/concepts/#langgraph). You can also see [this guide to help migrate to LangGraph](/v0.2/docs/how_to/migrate_agent). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to compose prompts together ](/v0.2/docs/how_to/prompts_composition)[ Next How to add values to a chain's state ](/v0.2/docs/how_to/assign) * [Concepts](#concepts) * [Setup](#setup) * [Jupyter Notebook](#jupyter-notebook) * [Installation](#installation) * [LangSmith](#langsmith) * [Define tools](#define-tools) * [Tavily](#tavily) * [Retriever](#retriever) * [Tools](#tools) * [Using Language Models](#using-language-models) * [Create the agent](#create-the-agent) * [Run the agent](#run-the-agent) * [Adding in memory](#adding-in-memory) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/query_no_queries
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to handle cases where no queries are generated On this page How to handle cases where no queries are generated ================================================== Prerequisites This guide assumes familiarity with the following: * [Query analysis](/v0.2/docs/tutorials/query_analysis) Sometimes, a query analysis technique may allow for any number of queries to be generated - including no queries! In this case, our overall chain will need to inspect the result of the query analysis before deciding whether to call the retriever or not. We will use mock data for this example. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community @langchain/openai zod chromadb yarn add @langchain/community @langchain/openai zod chromadb pnpm add @langchain/community @langchain/openai zod chromadb ### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true ### Create Index[​](#create-index "Direct link to Create Index") We will create a vectorstore over fake information. import { Chroma } from "@langchain/community/vectorstores/chroma";import { OpenAIEmbeddings } from "@langchain/openai";import "chromadb";const texts = ["Harrison worked at Kensho"];const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small" });const vectorstore = await Chroma.fromTexts(texts, {}, embeddings, { collectionName: "harrison",});const retriever = vectorstore.asRetriever(1); Query analysis[​](#query-analysis "Direct link to Query analysis") ------------------------------------------------------------------ We will use function calling to structure the output. However, we will configure the LLM such that is doesn’t NEED to call the function representing a search query (should it decide not to). We will also then use a prompt to do query analysis that explicitly lays when it should and shouldn’t make a search. import { z } from "zod";const searchSchema = z.object({ query: z.string().describe("Similarity search query applied to job record."),}); ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { zodToJsonSchema } from "zod-to-json-schema";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnableSequence, RunnablePassthrough,} from "@langchain/core/runnables";const system = `You have the ability to issue search queries to get information to help answer user information.You do not NEED to look things up. If you don't need to, then just respond normally.`;const prompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{question}"],]);const llmWithTools = llm.bind({ tools: [ { type: "function" as const, function: { name: "search", description: "Search over a database of job records.", parameters: zodToJsonSchema(searchSchema), }, }, ],});const queryAnalyzer = RunnableSequence.from([ { question: new RunnablePassthrough(), }, prompt, llmWithTools,]); We can see that by invoking this we get an message that sometimes - but not always - returns a tool call. await queryAnalyzer.invoke("where did Harrison work"); AIMessage { lc_serializable: true, lc_kwargs: { content: "", additional_kwargs: { function_call: undefined, tool_calls: [ { id: "call_uqHm5OMbXBkmqDr7Xzj8EMmd", type: "function", function: [Object] } ] } }, lc_namespace: [ "langchain_core", "messages" ], content: "", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: [ { id: "call_uqHm5OMbXBkmqDr7Xzj8EMmd", type: "function", function: { name: "search", arguments: '{"query":"Harrison"}' } } ] }} await queryAnalyzer.invoke("hi!"); AIMessage { lc_serializable: true, lc_kwargs: { content: "Hello! How can I assist you today?", additional_kwargs: { function_call: undefined, tool_calls: undefined } }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello! How can I assist you today?", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }} Retrieval with query analysis[​](#retrieval-with-query-analysis "Direct link to Retrieval with query analysis") --------------------------------------------------------------------------------------------------------------- So how would we include this in a chain? Let’s look at an example below. import { JsonOutputKeyToolsParser } from "@langchain/core/output_parsers/openai_tools";const outputParser = new JsonOutputKeyToolsParser({ keyName: "search",}); import { RunnableConfig, RunnableLambda } from "@langchain/core/runnables";const chain = async (question: string, config?: RunnableConfig) => { const response = await queryAnalyzer.invoke(question, config); if ( "tool_calls" in response.additional_kwargs && response.additional_kwargs.tool_calls !== undefined ) { const query = await outputParser.invoke(response, config); return retriever.invoke(query[0].query, config); } else { return response; }};const customChain = new RunnableLambda({ func: chain }); await customChain.invoke("where did Harrison Work"); [ Document { pageContent: "Harrison worked at Kensho", metadata: {} } ] await customChain.invoke("hi!"); AIMessage { lc_serializable: true, lc_kwargs: { content: "Hello! How can I assist you today?", additional_kwargs: { function_call: undefined, tool_calls: undefined } }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello! How can I assist you today?", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }} Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned some techniques for handling irrelevant questions in query analysis systems. Next, check out some of the other query analysis guides in this section, like [how to use few-shot examples](/v0.2/docs/how_to/query_few_shot). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to handle multiple retrievers ](/v0.2/docs/how_to/query_multiple_retrievers)[ Next How to recursively split text by characters ](/v0.2/docs/how_to/recursive_text_splitter) * [Setup](#setup) * [Install dependencies](#install-dependencies) * [Set environment variables](#set-environment-variables) * [Create Index](#create-index) * [Query analysis](#query-analysis) * [Retrieval with query analysis](#retrieval-with-query-analysis) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/parallel
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to invoke runnables in parallel On this page How to invoke runnables in parallel =================================== Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) * [Chaining runnables](/v0.2/docs/how_to/sequence/) The [`RunnableParallel`](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableParallel.html) (also known as a `RunnableMap`) primitive is an object whose values are runnables (or things that can be coerced to runnables, like functions). It runs all of its values in parallel, and each value is called with the initial input to the `RunnableParallel`. The final return value is an object with the results of each value under its appropriate key. Formatting with `RunnableParallels`[​](#formatting-with-runnableparallels "Direct link to formatting-with-runnableparallels") ----------------------------------------------------------------------------------------------------------------------------- `RunnableParallels` are useful for parallelizing operations, but can also be useful for manipulating the output of one Runnable to match the input format of the next Runnable in a sequence. You can use them to split or fork the chain so that multiple components can process the input in parallel. Later, other components can join or merge the results to synthesize a final response. This type of chain creates a computation graph that looks like the following: Input / \ / \ Branch1 Branch2 \ / \ / Combine Below, the input to each chain in the `RunnableParallel` is expected to be an object with a key for `"topic"`. We can satisfy that requirement by invoking our chain with an object matching that structure. tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/anthropic @langchain/cohere yarn add @langchain/anthropic @langchain/cohere pnpm add @langchain/anthropic @langchain/cohere import { PromptTemplate } from "@langchain/core/prompts";import { RunnableMap } from "@langchain/core/runnables";import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({});const jokeChain = PromptTemplate.fromTemplate( "Tell me a joke about {topic}").pipe(model);const poemChain = PromptTemplate.fromTemplate( "write a 2-line poem about {topic}").pipe(model);const mapChain = RunnableMap.from({ joke: jokeChain, poem: poemChain,});const result = await mapChain.invoke({ topic: "bear" });console.log(result);/* { joke: AIMessage { content: " Here's a silly joke about a bear:\n" + '\n' + 'What do you call a bear with no teeth?\n' + 'A gummy bear!', additional_kwargs: {} }, poem: AIMessage { content: ' Here is a 2-line poem about a bear:\n' + '\n' + 'Furry and wild, the bear roams free \n' + 'Foraging the forest, strong as can be', additional_kwargs: {} } }*/ #### API Reference: * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` * [RunnableMap](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableMap.html) from `@langchain/core/runnables` * [ChatAnthropic](https://v02.api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic` Manipulating outputs/inputs[​](#manipulating-outputsinputs "Direct link to Manipulating outputs/inputs") -------------------------------------------------------------------------------------------------------- Maps can be useful for manipulating the output of one Runnable to match the input format of the next Runnable in a sequence. Note below that the object within the `RunnableSequence.from()` call is automatically coerced into a runnable map. All keys of the object must have values that are runnables or can be themselves coerced to runnables (functions to `RunnableLambda`s or objects to `RunnableMap`s). This coercion will also occur when composing chains via the `.pipe()` method. import { CohereEmbeddings } from "@langchain/cohere";import { PromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { Document } from "@langchain/core/documents";import { ChatAnthropic } from "@langchain/anthropic";import { MemoryVectorStore } from "langchain/vectorstores/memory";const model = new ChatAnthropic();const vectorstore = await MemoryVectorStore.fromDocuments( [{ pageContent: "mitochondria is the powerhouse of the cell", metadata: {} }], new CohereEmbeddings());const retriever = vectorstore.asRetriever();const template = `Answer the question based only on the following context:{context}Question: {question}`;const prompt = PromptTemplate.fromTemplate(template);const formatDocs = (docs: Document[]) => docs.map((doc) => doc.pageContent);const retrievalChain = RunnableSequence.from([ { context: retriever.pipe(formatDocs), question: new RunnablePassthrough() }, prompt, model, new StringOutputParser(),]);const result = await retrievalChain.invoke( "what is the powerhouse of the cell?");console.log(result);/* Based on the given context, the powerhouse of the cell is mitochondria.*/ #### API Reference: * [CohereEmbeddings](https://v02.api.js.langchain.com/classes/langchain_cohere.CohereEmbeddings.html) from `@langchain/cohere` * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` * [StringOutputParser](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers` * [RunnablePassthrough](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html) from `@langchain/core/runnables` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [Document](https://v02.api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents` * [ChatAnthropic](https://v02.api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic` * [MemoryVectorStore](https://v02.api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory` Here the input to prompt is expected to be a map with keys "context" and "question". The user input is just the question. So we need to get the context using our retriever and passthrough the user input under the "question" key. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You now know some ways to format and parallelize chain steps with `RunnableParallel`. Next, you might be interested in [using custom logic](/v0.2/docs/how_to/functions/) in your chains. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to parse XML output ](/v0.2/docs/how_to/output_parser_xml)[ Next How to retrieve the whole document for a chunk ](/v0.2/docs/how_to/parent_document_retriever) * [Formatting with `RunnableParallels`](#formatting-with-runnableparallels) * [Manipulating outputs/inputs](#manipulating-outputsinputs) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/agents
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build an Agent On this page Build an Agent ============== Prerequisites This guide assumes familiarity with the following concepts: * [Chat Models](/v0.2/docs/concepts/#chat-models) * [Tools](/v0.2/docs/concepts/#tools) * [Agents](/v0.2/docs/concepts/#agents) By themselves, language models can't take actions - they just output text. A big use case for LangChain is creating **agents**. Agents are systems that use an LLM as a reasoning enginer to determine which actions to take and what the inputs to those actions should be. The results of those actions can then be fed back into the agent and it determine whether more actions are needed, or whether it is okay to finish. In this tutorial we will build an agent that can interact with multiple different tools: one being a local database, the other being a search engine. You will be able to ask this agent questions, watch it call tools, and have conversations with it. Setup: LangSmith[​](#setup-langsmith "Direct link to Setup: LangSmith") ----------------------------------------------------------------------- By definition, agents take a self-determined, input-dependent sequence of steps before returning a user-facing output. This makes debugging these systems particularly tricky, and observability particularly important. [LangSmith](https://smith.langchain.com) is especially useful for such cases. When building with LangChain, all steps will automatically be traced in LangSmith. To set up LangSmith we just need set the following environment variables: export LANGCHAIN_TRACING_V2="true"export LANGCHAIN_API_KEY="<your-api-key>" Define tools[​](#define-tools "Direct link to Define tools") ------------------------------------------------------------ We first need to create the tools we want to use. We will use two tools: [Tavily](https://app.tavily.com) (to search online) and then a retriever over a local index we will create. ### [Tavily](https://app.tavily.com)[​](#tavily "Direct link to tavily") We have a built-in tool in LangChain to easily use Tavily search engine as tool. Note that this requires a Tavily API key set as an environment variable named `TAVILY_API_KEY` - they have a free tier, but if you don’t have one or don’t want to create one, you can always ignore this step. import { TavilySearchResults } from "@langchain/community/tools/tavily_search";const searchTool = new TavilySearchResults();const toolResult = await searchTool.invoke("what is the weather in SF?");console.log(toolResult);/* [{"title":"Weather in December 2023 in San Francisco, California, USA","url":"https://www.timeanddate.com/weather/@5391959/historic?month=12&year=2023","content":"Currently: 52 °F. Broken clouds. (Weather station: San Francisco International Airport, USA). See more current weather Select month: December 2023 Weather in San Francisco — Graph °F Sun, Dec 17 Lo:55 6 pm Hi:57 4 Mon, Dec 18 Lo:54 12 am Hi:55 7 Lo:54 6 am Hi:55 10 Lo:57 12 pm Hi:64 9 Lo:63 6 pm Hi:64 14 Tue, Dec 19 Lo:61","score":0.96006},...]*/ ### Retriever[​](#retriever "Direct link to Retriever") We will also create a retriever over some data of our own. For a deeper explanation of each step here, see our [how to guides](/v0.2/docs/how_to/). import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings } from "@langchain/openai";const loader = new CheerioWebBaseLoader( "https://docs.smith.langchain.com/user_guide");const rawDocs = await loader.load();const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const docs = await splitter.splitDocuments(rawDocs);const vectorstore = await MemoryVectorStore.fromDocuments( docs, new OpenAIEmbeddings());const retriever = vectorstore.asRetriever();const retrieverResult = await retriever.invoke("how to upload a dataset");console.log(retrieverResult[0]);/* Document { pageContent: "your application progresses through the beta testing phase, it's essential to continue collecting data to refine and improve its performance. LangSmith enables you to add runs as examples to datasets (from both the project page and within an annotation queue), expanding your test coverage on real-world scenarios. This is a key benefit in having your logging system and your evaluation/testing system in the same platform.Production​Closely inspecting key data points, growing benchmarking datasets, annotating traces, and drilling down into important data in trace view are workflows you’ll also want to do once your app hits production. However, especially at the production stage, it’s crucial to get a high-level overview of application performance with respect to latency, cost, and feedback scores. This ensures that it's delivering desirable results at scale.Monitoring and A/B Testing​LangSmith provides monitoring charts that allow you to track key metrics over time. You can expand to", metadata: { source: 'https://docs.smith.langchain.com/user_guide', loc: { lines: [Object] } } }*/ Now that we have populated our index that we will do doing retrieval over, we can easily turn it into a tool (the format needed for an agent to properly use it): import { createRetrieverTool } from "langchain/tools/retriever";const retrieverTool = createRetrieverTool(retriever, { name: "langsmith_search", description: "Search for information about LangSmith. For any questions about LangSmith, you must use this tool!",}); ### Tools[​](#tools "Direct link to Tools") Now that we have created both, we can create a list of tools that we will use downstream: const tools = [searchTool, retrieverTool]; Create the agent[​](#create-the-agent "Direct link to Create the agent") ------------------------------------------------------------------------ Now that we have defined the tools, we can create the agent. We will be using an OpenAI Functions agent - for more information on this type of agent, as well as other options, see [this guide](https://js.langchain.com/v0.1/docs/modules/agents/agent_types/). First, we choose the LLM we want to be guiding the agent. import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0,}); Next, we choose the prompt we want to use to guide the agent: import type { ChatPromptTemplate } from "@langchain/core/prompts";import { pull } from "langchain/hub";// Get the prompt to use - you can modify this!// If you want to see the prompt in full, you can at:// https://smith.langchain.com/hub/hwchase17/openai-functions-agentconst prompt = await pull<ChatPromptTemplate>( "hwchase17/openai-functions-agent"); Now, we can initalize the agent with the LLM, the prompt, and the tools. The agent is responsible for taking in input and deciding what actions to take. Crucially, the Agent does not execute those actions - that is done by the AgentExecutor (next step). For more information about how to thing about these components, see our [conceptual guide](/v0.2/docs/concepts#agents). import { createOpenAIFunctionsAgent } from "langchain/agents";const agent = await createOpenAIFunctionsAgent({ llm, tools, prompt,}); Finally, we combine the agent (the brains) with the tools inside the AgentExecutor (which will repeatedly call the agent and execute tools). For more information about how to thing about these components, see our [conceptual guide](/v0.2/docs/concepts#agents). import { AgentExecutor } from "langchain/agents";const agentExecutor = new AgentExecutor({ agent, tools,}); Run the agent[​](#run-the-agent "Direct link to Run the agent") --------------------------------------------------------------- We can now run the agent on a few queries! Note that for now, these are all stateless queries (it won’t remember previous interactions). const result1 = await agentExecutor.invoke({ input: "hi!",});console.log(result1);/* [chain/start] [1:chain:AgentExecutor] Entering Chain run with input: { "input": "hi!" } [chain/end] [1:chain:AgentExecutor] [1.36s] Exiting Chain run with output: { "output": "Hello! How can I assist you today?" } { input: 'hi!', output: 'Hello! How can I assist you today?' }*/ const result2 = await agentExecutor.invoke({ input: "how can langsmith help with testing?",});console.log(result2);/* [chain/start] [1:chain:AgentExecutor] Entering Chain run with input: { "input": "how can langsmith help with testing?" } [chain/end] [1:chain:AgentExecutor > 2:chain:RunnableAgent > 7:parser:OpenAIFunctionsAgentOutputParser] [66ms] Exiting Chain run with output: { "tool": "langsmith_search", "toolInput": { "query": "how can LangSmith help with testing?" }, "log": "Invoking \"langsmith_search\" with {\"query\":\"how can LangSmith help with testing?\"}\n", "messageLog": [ { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "langsmith_search", "arguments": "{\"query\":\"how can LangSmith help with testing?\"}" } } } } ] } [tool/start] [1:chain:AgentExecutor > 8:tool:langsmith_search] Entering Tool run with input: "{"query":"how can LangSmith help with testing?"}" [retriever/start] [1:chain:AgentExecutor > 8:tool:langsmith_search > 9:retriever:VectorStoreRetriever] Entering Retriever run with input: { "query": "how can LangSmith help with testing?" } [retriever/end] [1:chain:AgentExecutor > 8:tool:langsmith_search > 9:retriever:VectorStoreRetriever] [294ms] Exiting Retriever run with output: { "documents": [ { "pageContent": "You can also quickly edit examples and add them to datasets to expand the surface area of your evaluation sets or to fine-tune a model for improved quality or reduced costs.Monitoring​After all this, your app might finally ready to go in production. LangSmith can also be used to monitor your application in much the same way that you used for debugging. You can log all traces, visualize latency and token usage statistics, and troubleshoot specific issues as they arise. Each run can also be assigned string tags or key-value metadata, allowing you to attach correlation ids or AB test variants, and filter runs accordingly.We’ve also made it possible to associate feedback programmatically with runs. This means that if your application has a thumbs up/down button on it, you can use that to log feedback back to LangSmith. This can be used to track performance over time and pinpoint under performing data points, which you can subsequently add to a dataset for future testing — mirroring the", "metadata": { "source": "https://docs.smith.langchain.com/user_guide", "loc": { "lines": { "from": 11, "to": 11 } } } }, { "pageContent": "the time that we do… it’s so helpful. We can use LangSmith to debug:An unexpected end resultWhy an agent is loopingWhy a chain was slower than expectedHow many tokens an agent usedDebugging​Debugging LLMs, chains, and agents can be tough. LangSmith helps solve the following pain points:What was the exact input to the LLM?​LLM calls are often tricky and non-deterministic. The inputs/outputs may seem straightforward, given they are technically string → string (or chat messages → chat message), but this can be misleading as the input string is usually constructed from a combination of user input and auxiliary functions.Most inputs to an LLM call are a combination of some type of fixed template along with input variables. These input variables could come directly from user input or from an auxiliary function (like retrieval). By the time these input variables go into the LLM they will have been converted to a string format, but often times they are not naturally represented as a string", "metadata": { "source": "https://docs.smith.langchain.com/user_guide", "loc": { "lines": { "from": 3, "to": 3 } } } }, { "pageContent": "inputs, and see what happens. At some point though, our application is performing\nwell and we want to be more rigorous about testing changes. We can use a dataset\nthat we’ve constructed along the way (see above). Alternatively, we could spend some\ntime constructing a small dataset by hand. For these situations, LangSmith simplifies", "metadata": { "source": "https://docs.smith.langchain.com/user_guide", "loc": { "lines": { "from": 4, "to": 7 } } } }, { "pageContent": "feedback back to LangSmith. This can be used to track performance over time and pinpoint under performing data points, which you can subsequently add to a dataset for future testing — mirroring the debug mode approach.We’ve provided several examples in the LangSmith documentation for extracting insights from logged runs. In addition to guiding you on performing this task yourself, we also provide examples of integrating with third parties for this purpose. We're eager to expand this area in the coming months! If you have ideas for either -- an open-source way to evaluate, or are building a company that wants to do analytics over these runs, please reach out.Exporting datasets​LangSmith makes it easy to curate datasets. However, these aren’t just useful inside LangSmith; they can be exported for use in other contexts. Notable applications include exporting for use in OpenAI Evals or fine-tuning, such as with FireworksAI.To set up tracing in Deno, web browsers, or other runtime", "metadata": { "source": "https://docs.smith.langchain.com/user_guide", "loc": { "lines": { "from": 11, "to": 11 } } } } ] } [chain/start] [1:chain:AgentExecutor > 10:chain:RunnableAgent] Entering Chain run with input: { "input": "how can langsmith help with testing?", "steps": [ { "action": { "tool": "langsmith_search", "toolInput": { "query": "how can LangSmith help with testing?" }, "log": "Invoking \"langsmith_search\" with {\"query\":\"how can LangSmith help with testing?\"}\n", "messageLog": [ { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "langsmith_search", "arguments": "{\"query\":\"how can LangSmith help with testing?\"}" } } } } ] }, "observation": "You can also quickly edit examples and add them to datasets to expand the surface area of your evaluation sets or to fine-tune a model for improved quality or reduced costs.Monitoring​After all this, your app might finally ready to go in production. LangSmith can also be used to monitor your application in much the same way that you used for debugging. You can log all traces, visualize latency and token usage statistics, and troubleshoot specific issues as they arise. Each run can also be assigned string tags or key-value metadata, allowing you to attach correlation ids or AB test variants, and filter runs accordingly.We’ve also made it possible to associate feedback programmatically with runs. This means that if your application has a thumbs up/down button on it, you can use that to log feedback back to LangSmith. This can be used to track performance over time and pinpoint under performing data points, which you can subsequently add to a dataset for future testing — mirroring the\n\nthe time that we do… it’s so helpful. We can use LangSmith to debug:An unexpected end resultWhy an agent is loopingWhy a chain was slower than expectedHow many tokens an agent usedDebugging​Debugging LLMs, chains, and agents can be tough. LangSmith helps solve the following pain points:What was the exact input to the LLM?​LLM calls are often tricky and non-deterministic. The inputs/outputs may seem straightforward, given they are technically string → string (or chat messages → chat message), but this can be misleading as the input string is usually constructed from a combination of user input and auxiliary functions.Most inputs to an LLM call are a combination of some type of fixed template along with input variables. These input variables could come directly from user input or from an auxiliary function (like retrieval). By the time these input variables go into the LLM they will have been converted to a string format, but often times they are not naturally represented as a string\n\ninputs, and see what happens. At some point though, our application is performing\nwell and we want to be more rigorous about testing changes. We can use a dataset\nthat we’ve constructed along the way (see above). Alternatively, we could spend some\ntime constructing a small dataset by hand. For these situations, LangSmith simplifies\n\nfeedback back to LangSmith. This can be used to track performance over time and pinpoint under performing data points, which you can subsequently add to a dataset for future testing — mirroring the debug mode approach.We’ve provided several examples in the LangSmith documentation for extracting insights from logged runs. In addition to guiding you on performing this task yourself, we also provide examples of integrating with third parties for this purpose. We're eager to expand this area in the coming months! If you have ideas for either -- an open-source way to evaluate, or are building a company that wants to do analytics over these runs, please reach out.Exporting datasets​LangSmith makes it easy to curate datasets. However, these aren’t just useful inside LangSmith; they can be exported for use in other contexts. Notable applications include exporting for use in OpenAI Evals or fine-tuning, such as with FireworksAI.To set up tracing in Deno, web browsers, or other runtime" } ] } [chain/end] [1:chain:AgentExecutor] [5.83s] Exiting Chain run with output: { "input": "how can langsmith help with testing?", "output": "LangSmith can help with testing in several ways:\n\n1. Debugging: LangSmith can be used to debug unexpected end results, agent loops, slow chains, and token usage. It helps in pinpointing underperforming data points and tracking performance over time.\n\n2. Monitoring: LangSmith can monitor applications by logging all traces, visualizing latency and token usage statistics, and troubleshooting specific issues as they arise. It also allows for associating feedback programmatically with runs, which can be used to track performance over time.\n\n3. Exporting Datasets: LangSmith makes it easy to curate datasets, which can be exported for use in other contexts such as OpenAI Evals or fine-tuning with FireworksAI.\n\nOverall, LangSmith simplifies the process of testing changes, constructing datasets, and extracting insights from logged runs, making it a valuable tool for testing and evaluation." } { input: 'how can langsmith help with testing?', output: 'LangSmith can help with testing in several ways:\n' + '\n' + '1. Initial Test Set: LangSmith allows developers to create datasets of inputs and reference outputs to run tests on their LLM applications. These test cases can be uploaded in bulk, created on the fly, or exported from application traces.\n' + '\n' + "2. Comparison View: When making changes to your applications, LangSmith provides a comparison view to see whether you've regressed with respect to your initial test cases. This is helpful for evaluating changes in prompts, retrieval strategies, or model choices.\n" + '\n' + '3. Monitoring and A/B Testing: LangSmith provides monitoring charts to track key metrics over time and allows for A/B testing changes in prompt, model, or retrieval strategy.\n' + '\n' + '4. Debugging: LangSmith offers tracing and debugging information at each step of an LLM sequence, making it easier to identify and root-cause issues when things go wrong.\n' + '\n' + '5. Beta Testing and Production: LangSmith enables the addition of runs as examples to datasets, expanding test coverage on real-world scenarios. It also provides monitoring for application performance with respect to latency, cost, and feedback scores at the production stage.\n' + '\n' + 'Overall, LangSmith provides comprehensive testing and monitoring capabilities for LLM applications.' }*/ Adding in memory[​](#adding-in-memory "Direct link to Adding in memory") ------------------------------------------------------------------------ As mentioned earlier, this agent is stateless. This means it does not remember previous interactions. To give it memory we need to pass in previous `chat_history`. **Note:** the input variable below needs to be called `chat_history` because of the prompt we are using. If we use a different prompt, we could change the variable name. const result3 = await agentExecutor.invoke({ input: "hi! my name is cob.", chat_history: [],});console.log(result3);/* { input: 'hi! my name is cob.', chat_history: [], output: "Hello Cob! It's nice to meet you. How can I assist you today?" }*/ import { HumanMessage, AIMessage } from "@langchain/core/messages";const result4 = await agentExecutor.invoke({ input: "what's my name?", chat_history: [ new HumanMessage("hi! my name is cob."), new AIMessage("Hello Cob! How can I assist you today?"), ],});console.log(result4);/* { input: "what's my name?", chat_history: [ HumanMessage { content: 'hi! my name is cob.', additional_kwargs: {} }, AIMessage { content: 'Hello Cob! How can I assist you today?', additional_kwargs: {} } ], output: 'Your name is Cob. How can I assist you today, Cob?' }*/ If we want to keep track of these messages automatically, we can wrap this in a RunnableWithMessageHistory. For more information on how to use this, see [this guide](/v0.2/docs/how_to/message_history/). import { ChatMessageHistory } from "langchain/stores/message/in_memory";import { RunnableWithMessageHistory } from "@langchain/core/runnables";const messageHistory = new ChatMessageHistory();const agentWithChatHistory = new RunnableWithMessageHistory({ runnable: agentExecutor, // This is needed because in most real world scenarios, a session id is needed per user. // It isn't really used here because we are using a simple in memory ChatMessageHistory. getMessageHistory: (_sessionId) => messageHistory, inputMessagesKey: "input", historyMessagesKey: "chat_history",});const result5 = await agentWithChatHistory.invoke( { input: "hi! i'm cob", }, { // This is needed because in most real world scenarios, a session id is needed per user. // It isn't really used here because we are using a simple in memory ChatMessageHistory. configurable: { sessionId: "foo", }, });console.log(result5);/* { input: "hi! i'm cob", chat_history: [ HumanMessage { content: "hi! i'm cob", additional_kwargs: {} }, AIMessage { content: 'Hello Cob! How can I assist you today?', additional_kwargs: {} } ], output: 'Hello Cob! How can I assist you today?' }*/ const result6 = await agentWithChatHistory.invoke( { input: "what's my name?", }, { // This is needed because in most real world scenarios, a session id is needed per user. // It isn't really used here because we are using a simple in memory ChatMessageHistory. configurable: { sessionId: "foo", }, });console.log(result6);/* { input: "what's my name?", chat_history: [ HumanMessage { content: "hi! i'm cob", additional_kwargs: {} }, AIMessage { content: 'Hello Cob! How can I assist you today?', additional_kwargs: {} }, HumanMessage { content: "what's my name?", additional_kwargs: {} }, AIMessage { content: 'Your name is Cob. How can I assist you today, Cob?', additional_kwargs: {} } ], output: 'Your name is Cob. How can I assist you today, Cob?' }*/ Conclusion[​](#conclusion "Direct link to Conclusion") ------------------------------------------------------ That’s a wrap! In this quick start we covered how to create a simple agent. Agents are a complex topic, and there’s lot to learn! Head back to the [main agent page](/v0.2/docs/how_to/agent_executor/) to find more resources on conceptual guides, different types of agents, how to create custom tools, and more! * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build a Chatbot ](/v0.2/docs/tutorials/chatbot)[ Next Build an Extraction Chain ](/v0.2/docs/tutorials/extraction) * [Setup: LangSmith](#setup-langsmith) * [Define tools](#define-tools) * [Tavily](#tavily) * [Retriever](#retriever) * [Tools](#tools) * [Create the agent](#create-the-agent) * [Run the agent](#run-the-agent) * [Adding in memory](#adding-in-memory) * [Conclusion](#conclusion)
null
https://js.langchain.com/v0.2/docs/how_to/assign
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to add values to a chain's state On this page How to add values to a chain's state ==================================== Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) * [Chaining runnables](/v0.2/docs/how_to/sequence/) * [Calling runnables in parallel](/v0.2/docs/how_to/parallel/) * [Custom functions](/v0.2/docs/how_to/functions/) * [Passing data through](/v0.2/docs/how_to/passthrough) An alternate way of [passing data through](/v0.2/docs/how_to/passthrough) steps of a chain is to leave the current values of the chain state unchanged while assigning a new value under a given key. The [`RunnablePassthrough.assign()`](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html#assign-2) static method takes an input value and adds the extra arguments passed to the assign function. This is useful in the common [LangChain Expression Language](/v0.2/docs/concepts/#langchain-expression-language) pattern of additively creating a dictionary to use as input to a later step. Here’s an example: import { RunnableParallel, RunnablePassthrough,} from "@langchain/core/runnables";const runnable = RunnableParallel.from({ extra: RunnablePassthrough.assign({ mult: (input: { num: number }) => input.num * 3, modified: (input: { num: number }) => input.num + 1, }),});await runnable.invoke({ num: 1 }); { extra: { num: 1, mult: 3, modified: 2 } } Let’s break down what’s happening here. * The input to the chain is `{"num": 1}`. This is passed into a `RunnableParallel`, which invokes the runnables it is passed in parallel with that input. * The value under the `extra` key is invoked. `RunnablePassthrough.assign()` keeps the original keys in the input dict (`{"num": 1}`), and assigns a new key called `mult`. The value is `lambda x: x["num"] * 3)`, which is `3`. Thus, the result is `{"num": 1, "mult": 3}`. * `{"num": 1, "mult": 3}` is returned to the `RunnableParallel` call, and is set as the value to the key `extra`. * At the same time, the `modified` key is called. The result is `2`, since the lambda extracts a key called `"num"` from its input and adds one. Thus, the result is `{'extra': {'num': 1, 'mult': 3}, 'modified': 2}`. Streaming[​](#streaming "Direct link to Streaming") --------------------------------------------------- One convenient feature of this method is that it allows values to pass through as soon as they are available. To show this off, we’ll use `RunnablePassthrough.assign()` to immediately return source docs in a retrieval chain: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";import { MemoryVectorStore } from "langchain/vectorstores/memory";const vectorstore = await MemoryVectorStore.fromDocuments( [{ pageContent: "harrison worked at kensho", metadata: {} }], new OpenAIEmbeddings());const retriever = vectorstore.asRetriever();const template = `Answer the question based only on the following context:{context}Question: {question}`;const prompt = ChatPromptTemplate.fromTemplate(template);const model = new ChatOpenAI({ model: "gpt-4o" });const generationChain = prompt.pipe(model).pipe(new StringOutputParser());const retrievalChain = RunnableSequence.from([ { context: retriever.pipe((docs) => docs[0].pageContent), question: new RunnablePassthrough(), }, RunnablePassthrough.assign({ output: generationChain }),]);const stream = await retrievalChain.stream("where did harrison work?");for await (const chunk of stream) { console.log(chunk);} { question: "where did harrison work?" }{ context: "harrison worked at kensho" }{ output: "" }{ output: "H" }{ output: "arrison" }{ output: " worked" }{ output: " at" }{ output: " Kens" }{ output: "ho" }{ output: "." }{ output: "" } We can see that the first chunk contains the original `"question"` since that is immediately available. The second chunk contains `"context"` since the retriever finishes second. Finally, the output from the `generation_chain` streams in chunks as soon as it is available. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ Now you’ve learned how to pass data through your chains to help to help format the data flowing through your chains. To learn more, see the other how-to guides on runnables in this section. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use legacy LangChain Agents (AgentExecutor) ](/v0.2/docs/how_to/agent_executor)[ Next How to attach runtime arguments to a Runnable ](/v0.2/docs/how_to/binding) * [Streaming](#streaming) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/prompts_partial
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to partially format prompt templates On this page How to partially format prompt templates ======================================== Prerequisites This guide assumes familiarity with the following concepts: * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) Like partially binding arguments to a function, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values. LangChain supports this in two ways: 1. Partial formatting with string values. 2. Partial formatting with functions that return string values. In the examples below, we go over the motivations for both use cases as well as how to do it in LangChain. Partial with strings[​](#partial-with-strings "Direct link to Partial with strings") ------------------------------------------------------------------------------------ One common use case for wanting to partial a prompt template is if you get access to some of the variables in a prompt before others. For example, suppose you have a prompt template that requires two variables, `foo` and `baz`. If you get the `foo` value early on in your chain, but the `baz` value later, it can be inconvenient to pass both variables all the way through the chain. Instead, you can partial the prompt template with the `foo` value, and then pass the partialed prompt template along and just use that. Below is an example of doing this: import { PromptTemplate } from "langchain/prompts";const prompt = new PromptTemplate({ template: "{foo}{bar}", inputVariables: ["foo", "bar"],});const partialPrompt = await prompt.partial({ foo: "foo",});const formattedPrompt = await partialPrompt.format({ bar: "baz",});console.log(formattedPrompt);// foobaz You can also just initialize the prompt with the partialed variables. const prompt = new PromptTemplate({ template: "{foo}{bar}", inputVariables: ["bar"], partialVariables: { foo: "foo", },});const formattedPrompt = await prompt.format({ bar: "baz",});console.log(formattedPrompt);// foobaz Partial With Functions[​](#partial-with-functions "Direct link to Partial With Functions") ------------------------------------------------------------------------------------------ You can also partial with a function. The use case for this is when you have a variable you know that you always want to fetch in a common way. A prime example of this is with date or time. Imagine you have a prompt which you always want to have the current date. You can't hard code it in the prompt, and passing it along with the other input variables can be tedious. In this case, it's very handy to be able to partial the prompt with a function that always returns the current date. const getCurrentDate = () => { return new Date().toISOString();};const prompt = new PromptTemplate({ template: "Tell me a {adjective} joke about the day {date}", inputVariables: ["adjective", "date"],});const partialPrompt = await prompt.partial({ date: getCurrentDate,});const formattedPrompt = await partialPrompt.format({ adjective: "funny",});console.log(formattedPrompt);// Tell me a funny joke about the day 2023-07-13T00:54:59.287Z You can also just initialize the prompt with the partialed variables: const prompt = new PromptTemplate({ template: "Tell me a {adjective} joke about the day {date}", inputVariables: ["adjective"], partialVariables: { date: getCurrentDate, },});const formattedPrompt = await prompt.format({ adjective: "funny",});console.log(formattedPrompt);// Tell me a funny joke about the day 2023-07-13T00:54:59.287Z Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned how to partially apply variables to your prompt templates. Next, check out the other how-to guides on prompt templates in this section, like [adding few-shot examples to your prompt templates](/v0.2/docs/how_to/few_shot_examples_chat). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to retrieve the whole document for a chunk ](/v0.2/docs/how_to/parent_document_retriever)[ Next How to add chat history to a question-answering chain ](/v0.2/docs/how_to/qa_chat_history_how_to) * [Partial with strings](#partial-with-strings) * [Partial With Functions](#partial-with-functions) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/binding
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to attach runtime arguments to a Runnable On this page How to attach runtime arguments to a Runnable ============================================= Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) * [Chaining runnables](/v0.2/docs/how_to/sequence/) * [Tool calling](/v0.2/docs/how_to/tool_calling/) Sometimes we want to invoke a [`Runnable`](https://v02.api.js.langchain.com/classes/langchain_core_runnables.Runnable.html) within a [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) with constant arguments that are not part of the output of the preceding Runnable in the sequence, and which are not part of the user input. We can use the [`Runnable.bind()`](https://v02.api.js.langchain.com/classes/langchain_core_runnables.Runnable.html#bind) method to set these arguments ahead of time. Binding stop sequences[​](#binding-stop-sequences "Direct link to Binding stop sequences") ------------------------------------------------------------------------------------------ Suppose we have a simple prompt + model chain: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatOpenAI } from "@langchain/openai";const prompt = ChatPromptTemplate.fromMessages([ [ "system", "Write out the following equation using algebraic symbols then solve it. Use the format\n\nEQUATION:...\nSOLUTION:...\n\n", ], ["human", "{equation_statement}"],]);const model = new ChatOpenAI({ temperature: 0 });const runnable = prompt.pipe(model).pipe(new StringOutputParser());const res = await runnable.invoke({ equation_statement: "x raised to the third plus seven equals 12",});console.log(res); EQUATION: x^3 + 7 = 12SOLUTION:Subtract 7 from both sides:x^3 = 5Take the cube root of both sides:x = ∛5 and want to call the model with certain `stop` words so that we shorten the output, which is useful in certain types of prompting techniques. While we can pass some arguments into the constructor, other runtime args use the `.bind()` method as follows: const runnable = prompt .pipe(model.bind({ stop: "SOLUTION" })) .pipe(new StringOutputParser());const res = await runnable.invoke({ equation_statement: "x raised to the third plus seven equals 12",});console.log(res); EQUATION: x^3 + 7 = 12 What you can bind to a Runnable will depend on the extra parameters you can pass when invoking it. Attaching OpenAI tools[​](#attaching-openai-tools "Direct link to Attaching OpenAI tools") ------------------------------------------------------------------------------------------ Another common use-case is tool calling. While you should generally use the [`.bind_tools()`](/v0.2/docs/how_to/tool_calling/) method for tool-calling models, you can also bind provider-specific args directly if you want lower level control: const tools = [ { type: "function", function: { name: "get_current_weather", description: "Get the current weather in a given location", parameters: { type: "object", properties: { location: { type: "string", description: "The city and state, e.g. San Francisco, CA", }, unit: { type: "string", enum: ["celsius", "fahrenheit"] }, }, required: ["location"], }, }, },];const model = new ChatOpenAI({ model: "gpt-4o" }).bind({ tools });await model.invoke("What's the weather in SF, NYC and LA?"); AIMessage { lc_serializable: true, lc_kwargs: { content: "", tool_calls: [ { name: "get_current_weather", args: { location: "San Francisco, CA" }, id: "call_iDKz4zU8PKBaaIT052fJkMMF" }, { name: "get_current_weather", args: { location: "New York, NY" }, id: "call_niQwZDOqO6OJTBiDBFG8FODc" }, { name: "get_current_weather", args: { location: "Los Angeles, CA" }, id: "call_zLXH2cDVQy0nAVC0ViWuEP4m" } ], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: [ { id: "call_iDKz4zU8PKBaaIT052fJkMMF", type: "function", function: [Object] }, { id: "call_niQwZDOqO6OJTBiDBFG8FODc", type: "function", function: [Object] }, { id: "call_zLXH2cDVQy0nAVC0ViWuEP4m", type: "function", function: [Object] } ] }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: [ { id: "call_iDKz4zU8PKBaaIT052fJkMMF", type: "function", function: { name: "get_current_weather", arguments: '{"location": "San Francisco, CA"}' } }, { id: "call_niQwZDOqO6OJTBiDBFG8FODc", type: "function", function: { name: "get_current_weather", arguments: '{"location": "New York, NY"}' } }, { id: "call_zLXH2cDVQy0nAVC0ViWuEP4m", type: "function", function: { name: "get_current_weather", arguments: '{"location": "Los Angeles, CA"}' } } ] }, response_metadata: { tokenUsage: { completionTokens: 70, promptTokens: 82, totalTokens: 152 }, finish_reason: "tool_calls" }, tool_calls: [ { name: "get_current_weather", args: { location: "San Francisco, CA" }, id: "call_iDKz4zU8PKBaaIT052fJkMMF" }, { name: "get_current_weather", args: { location: "New York, NY" }, id: "call_niQwZDOqO6OJTBiDBFG8FODc" }, { name: "get_current_weather", args: { location: "Los Angeles, CA" }, id: "call_zLXH2cDVQy0nAVC0ViWuEP4m" } ], invalid_tool_calls: []} Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You now know how to bind runtime arguments to a Runnable. Next, you might be interested in our how-to guides on [passing data through a chain](/v0.2/docs/how_to/passthrough/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to add values to a chain's state ](/v0.2/docs/how_to/assign)[ Next How to cache embedding results ](/v0.2/docs/how_to/caching_embeddings) * [Binding stop sequences](#binding-stop-sequences) * [Attaching OpenAI tools](#attaching-openai-tools) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/extraction
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build an Extraction Chain On this page Build an Extraction Chain ========================= Prerequisites This guide assumes familiarity with the following concepts: * [Chat Models](/v0.2/docs/concepts/#chat-models) * [Tools](/v0.2/docs/concepts/#tools) * [Tool calling](/v0.2/docs/concepts/#function-tool-calling) In this tutorial, we will build a chain to extract structured information from unstructured text. info This tutorial will only work with models that support **function/tool calling** Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Installation[​](#installation "Direct link to Installation") To install LangChain run: * npm * yarn * pnpm npm i langchain yarn add langchain pnpm add langchain For more details, see our [Installation guide](/v0.2/docs/how_to/installation/). ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com). After you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2="true"export LANGCHAIN_API_KEY="..." The Schema[​](#the-schema "Direct link to The Schema") ------------------------------------------------------ First, we need to describe what information we want to extract from the text. We’ll use [Zod](https://zod.dev) to define an example schema that extracts personal information. * npm * yarn * pnpm npm i zod @langchain/core yarn add zod @langchain/core pnpm add zod @langchain/core import { z } from "zod";const personSchema = z.object({ name: z.string().nullish().describe("The name of the person"), hair_color: z .string() .nullish() .describe("The color of the person's hair if known"), height_in_meters: z.string().nullish().describe("Height measured in meters"),}); There are two best practices when defining schema: 1. Document the **attributes** and the **schema** itself: This information is sent to the LLM and is used to improve the quality of information extraction. 2. Do not force the LLM to make up information! Above we used `.nullish()` for the attributes allowing the LLM to output `null` or `undefined` if it doesn’t know the answer. info For best performance, document the schema well and make sure the model isn’t force to return results if there’s no information to be extracted in the text. The Extractor[​](#the-extractor "Direct link to The Extractor") --------------------------------------------------------------- Let’s create an information extractor using the schema we defined above. import { ChatPromptTemplate } from "@langchain/core/prompts";// Define a custom prompt to provide instructions and any additional context.// 1) You can add examples into the prompt template to improve extraction quality// 2) Introduce additional parameters to take context into account (e.g., include metadata// about the document from which the text was extracted.)const prompt = ChatPromptTemplate.fromMessages([ [ "system", `You are an expert extraction algorithm.Only extract relevant information from the text.If you do not know the value of an attribute asked to extract,return null for the attribute's value.`, ], // Please see the how-to about improving performance with // reference examples. // ["placeholder", "{examples}"], ["human", "{text}"],]); We need to use a model that supports function/tool calling. Please review [the documentation](/v0.2/docs/concepts#function-tool-calling) for list of some models that can be used with this API. import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0,});const runnable = prompt.pipe(llm.withStructuredOutput(personSchema));const text = "Alan Smith is 6 feet tall and has blond hair.";await runnable.invoke({ text }); { name: "Alan Smith", hair_color: "blond", height_in_meters: "1.83" } info Extraction is Generative 🤯 LLMs are generative models, so they can do some pretty cool things like correctly extract the height of the person in meters even though it was provided in feet! We can see the LangSmith trace [here](https://smith.langchain.com/public/3d44b7e8-e7ca-4e02-951d-3290ccc89d64/r). Even though we defined our schema with the variable name `personSchema`, Zod is unable to infer this name and therefore does not pass it along to the model. To help give the LLM more clues as to what your provided schema represents, you can also give the schema you pass to `withStructuredOutput()` a name: const runnable = prompt.pipe( llm.withStructuredOutput(personSchema, { name: "person" }));const text = "Alan Smith is 6 feet tall and has blond hair.";await runnable.invoke({ text }); { name: "Alan Smith", hair_color: "blond", height_in_meters: "1.83" } This can improve performance in many cases. Multiple Entities[​](#multiple-entities "Direct link to Multiple Entities") --------------------------------------------------------------------------- In **most cases**, you should be extracting a list of entities rather than a single entity. This can be easily achieved using Zod by nesting models inside one another. import { z } from "zod";const personSchema = z.object({ name: z.string().nullish().describe("The name of the person"), hair_color: z .string() .nullish() .describe("The color of the person's hair if known"), height_in_meters: z.number().nullish().describe("Height measured in meters"),});const dataSchema = z.object({ people: z.array(personSchema).describe("Extracted data about people"),}); info Extraction might not be perfect here. Please continue to see how to use **Reference Examples** to improve the quality of extraction, and see the **guidelines** section! const runnable = prompt.pipe(llm.withStructuredOutput(dataSchema));const text = "My name is Jeff, my hair is black and i am 6 feet tall. Anna has the same color hair as me.";await runnable.invoke({ text }); { people: [ { name: "Jeff", hair_color: "black", height_in_meters: 1.83 }, { name: "Anna", hair_color: "black", height_in_meters: null } ]} tip When the schema accommodates the extraction of **multiple entities**, it also allows the model to extract **no entities** if no relevant information is in the text by providing an empty list. This is usually a **good** thing! It allows specifying **required** attributes on an entity without necessarily forcing the model to detect this entity. We can see the LangSmith trace [here](https://smith.langchain.com/public/272096ab-9ac5-43f9-aa00-3b8443477d17/r) Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ Now that you understand the basics of extraction with LangChain, you’re ready to proceed to the rest of the how-to guides: * [Add Examples](/v0.2/docs/how_to/extraction_examples): Learn how to use **reference examples** to improve performance. * [Handle Long Text](/v0.2/docs/how_to/extraction_long_text): What should you do if the text does not fit into the context window of the LLM? * [Use a Parsing Approach](/v0.2/docs/how_to/extraction_parse): Use a prompt based approach to extract with models that do not support **tool/function calling**. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build an Agent ](/v0.2/docs/tutorials/agents)[ Next Summarize Text ](/v0.2/docs/tutorials/summarization) * [Setup](#setup) * [Installation](#installation) * [LangSmith](#langsmith) * [The Schema](#the-schema) * [The Extractor](#the-extractor) * [Multiple Entities](#multiple-entities) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/parent_document_retriever
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to retrieve the whole document for a chunk On this page How to retrieve the whole document for a chunk ============================================== Prerequisites This guide assumes familiarity with the following concepts: * [Retrievers](/v0.2/docs/concepts/#retrievers) * [Text splitters](/v0.2/docs/concepts/#text-splitters) * [Retrieval-augmented generation (RAG)](/v0.2/docs/tutorials/rag) When splitting documents for retrieval, there are often conflicting desires: 1. You may want to have small documents, so that their embeddings can most accurately reflect their meaning. If documents are too long, then the embeddings can lose meaning. 2. You want to have long enough documents that the context of each chunk is retained. The [`ParentDocumentRetriever`](https://v02.api.js.langchain.com/classes/langchain_retrievers_parent_document.ParentDocumentRetriever.html) strikes that balance by splitting and storing small chunks of data. During retrieval, it first fetches the small chunks but then looks up the parent ids for those chunks and returns those larger documents. Note that "parent document" refers to the document that a small chunk originated from. This can either be the whole raw document OR a larger chunk. This is a more specific form of [generating multiple embeddings per document](/v0.2/docs/how_to/multi_vector). Usage[​](#usage "Direct link to Usage") --------------------------------------- tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { OpenAIEmbeddings } from "@langchain/openai";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { InMemoryStore } from "@langchain/core/stores";import { ParentDocumentRetriever } from "langchain/retrievers/parent_document";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { TextLoader } from "langchain/document_loaders/fs/text";const vectorstore = new MemoryVectorStore(new OpenAIEmbeddings());const docstore = new InMemoryStore();const retriever = new ParentDocumentRetriever({ vectorstore, docstore, // Optional, not required if you're already passing in split documents parentSplitter: new RecursiveCharacterTextSplitter({ chunkOverlap: 0, chunkSize: 500, }), childSplitter: new RecursiveCharacterTextSplitter({ chunkOverlap: 0, chunkSize: 50, }), // Optional `k` parameter to search for more child documents in VectorStore. // Note that this does not exactly correspond to the number of final (parent) documents // retrieved, as multiple child documents can point to the same parent. childK: 20, // Optional `k` parameter to limit number of final, parent documents returned from this // retriever and sent to LLM. This is an upper-bound, and the final count may be lower than this. parentK: 5,});const textLoader = new TextLoader("../examples/state_of_the_union.txt");const parentDocuments = await textLoader.load();// We must add the parent documents via the retriever's addDocuments methodawait retriever.addDocuments(parentDocuments);const retrievedDocs = await retriever.invoke("justice breyer");// Retrieved chunks are the larger parent chunksconsole.log(retrievedDocs);/* [ Document { pageContent: 'Tonight, I call on the Senate to pass — pass the Freedom to Vote Act. Pass the John Lewis Act — Voting Rights Act. And while you’re at it, pass the DISCLOSE Act so Americans know who is funding our elections.\n' + '\n' + 'Look, tonight, I’d — I’d like to honor someone who has dedicated his life to serve this country: Justice Breyer — an Army veteran, Constitutional scholar, retiring Justice of the United States Supreme Court.', metadata: { source: '../examples/state_of_the_union.txt', loc: [Object] } }, Document { pageContent: 'As I did four days ago, I’ve nominated a Circuit Court of Appeals — Ketanji Brown Jackson. One of our nation’s top legal minds who will continue in just Brey- — Justice Breyer’s legacy of excellence. A former top litigator in private practice, a former federal public defender from a family of public-school educators and police officers — she’s a consensus builder.', metadata: { source: '../examples/state_of_the_union.txt', loc: [Object] } }, Document { pageContent: 'Justice Breyer, thank you for your service. Thank you, thank you, thank you. I mean it. Get up. Stand — let me see you. Thank you.\n' + '\n' + 'And we all know — no matter what your ideology, we all know one of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.', metadata: { source: '../examples/state_of_the_union.txt', loc: [Object] } } ]*/ #### API Reference: * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [MemoryVectorStore](https://v02.api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory` * [InMemoryStore](https://v02.api.js.langchain.com/classes/langchain_core_stores.InMemoryStore.html) from `@langchain/core/stores` * [ParentDocumentRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_parent_document.ParentDocumentRetriever.html) from `langchain/retrievers/parent_document` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [TextLoader](https://v02.api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text` With Score Threshold[​](#with-score-threshold "Direct link to With Score Threshold") ------------------------------------------------------------------------------------ By setting the options in `scoreThresholdOptions` we can force the `ParentDocumentRetriever` to use the `ScoreThresholdRetriever` under the hood. This sets the vector store inside `ScoreThresholdRetriever` as the one we passed when initializing `ParentDocumentRetriever`, while also allowing us to also set a score threshold for the retriever. This can be helpful when you're not sure how many documents you want (or if you are sure, just set the `maxK` option), but you want to make sure that the documents you do get are within a certain relevancy threshold. Note: if a retriever is passed, `ParentDocumentRetriever` will default to use it for retrieving small chunks, as well as adding documents via the `addDocuments` method. import { OpenAIEmbeddings } from "@langchain/openai";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { InMemoryStore } from "@langchain/core/stores";import { ParentDocumentRetriever } from "langchain/retrievers/parent_document";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { TextLoader } from "langchain/document_loaders/fs/text";import { ScoreThresholdRetriever } from "langchain/retrievers/score_threshold";const vectorstore = new MemoryVectorStore(new OpenAIEmbeddings());const docstore = new InMemoryStore();const childDocumentRetriever = ScoreThresholdRetriever.fromVectorStore( vectorstore, { minSimilarityScore: 0.01, // Essentially no threshold maxK: 1, // Only return the top result });const retriever = new ParentDocumentRetriever({ vectorstore, docstore, childDocumentRetriever, // Optional, not required if you're already passing in split documents parentSplitter: new RecursiveCharacterTextSplitter({ chunkOverlap: 0, chunkSize: 500, }), childSplitter: new RecursiveCharacterTextSplitter({ chunkOverlap: 0, chunkSize: 50, }),});const textLoader = new TextLoader("../examples/state_of_the_union.txt");const parentDocuments = await textLoader.load();// We must add the parent documents via the retriever's addDocuments methodawait retriever.addDocuments(parentDocuments);const retrievedDocs = await retriever.invoke("justice breyer");// Retrieved chunk is the larger parent chunkconsole.log(retrievedDocs);/* [ Document { pageContent: 'Tonight, I call on the Senate to pass — pass the Freedom to Vote Act. Pass the John Lewis Act — Voting Rights Act. And while you’re at it, pass the DISCLOSE Act so Americans know who is funding our elections.\n' + '\n' + 'Look, tonight, I’d — I’d like to honor someone who has dedicated his life to serve this country: Justice Breyer — an Army veteran, Constitutional scholar, retiring Justice of the United States Supreme Court.', metadata: { source: '../examples/state_of_the_union.txt', loc: [Object] } }, ]*/ #### API Reference: * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [MemoryVectorStore](https://v02.api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory` * [InMemoryStore](https://v02.api.js.langchain.com/classes/langchain_core_stores.InMemoryStore.html) from `@langchain/core/stores` * [ParentDocumentRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_parent_document.ParentDocumentRetriever.html) from `langchain/retrievers/parent_document` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [TextLoader](https://v02.api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text` * [ScoreThresholdRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_score_threshold.ScoreThresholdRetriever.html) from `langchain/retrievers/score_threshold` With Contextual chunk headers[​](#with-contextual-chunk-headers "Direct link to With Contextual chunk headers") --------------------------------------------------------------------------------------------------------------- Consider a scenario where you want to store collection of documents in a vector store and perform Q&A tasks on them. Simply splitting documents with overlapping text may not provide sufficient context for LLMs to determine if multiple chunks are referencing the same information, or how to resolve information from contradictory sources. Tagging each document with metadata is a solution if you know what to filter against, but you may not know ahead of time exactly what kind of queries your vector store will be expected to handle. Including additional contextual information directly in each chunk in the form of headers can help deal with arbitrary queries. This is particularly important if you have several fine-grained child chunks that need to be correctly retrieved from the vector store. import { OpenAIEmbeddings } from "@langchain/openai";import { HNSWLib } from "@langchain/community/vectorstores/hnswlib";import { InMemoryStore } from "@langchain/core/stores";import { ParentDocumentRetriever } from "langchain/retrievers/parent_document";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 1500, chunkOverlap: 0,});const jimDocs = await splitter.createDocuments([`My favorite color is blue.`]);const jimChunkHeaderOptions = { chunkHeader: "DOC NAME: Jim Interview\n---\n", appendChunkOverlapHeader: true,};const pamDocs = await splitter.createDocuments([`My favorite color is red.`]);const pamChunkHeaderOptions = { chunkHeader: "DOC NAME: Pam Interview\n---\n", appendChunkOverlapHeader: true,};const vectorstore = await HNSWLib.fromDocuments([], new OpenAIEmbeddings());const docstore = new InMemoryStore();const retriever = new ParentDocumentRetriever({ vectorstore, docstore, // Very small chunks for demo purposes. // Use a bigger chunk size for serious use-cases. childSplitter: new RecursiveCharacterTextSplitter({ chunkSize: 10, chunkOverlap: 0, }), childK: 50, parentK: 5,});// We pass additional option `childDocChunkHeaderOptions`// that will add the chunk header to child documentsawait retriever.addDocuments(jimDocs, { childDocChunkHeaderOptions: jimChunkHeaderOptions,});await retriever.addDocuments(pamDocs, { childDocChunkHeaderOptions: pamChunkHeaderOptions,});// This will search child documents in vector store with the help of chunk header,// returning the unmodified parent documentsconst retrievedDocs = await retriever.invoke("What is Pam's favorite color?");// Pam's favorite color is returned first!console.log(JSON.stringify(retrievedDocs, null, 2));/* [ { "pageContent": "My favorite color is red.", "metadata": { "loc": { "lines": { "from": 1, "to": 1 } } } }, { "pageContent": "My favorite color is blue.", "metadata": { "loc": { "lines": { "from": 1, "to": 1 } } } } ]*/const rawDocs = await vectorstore.similaritySearch( "What is Pam's favorite color?");// Raw docs in vectorstore are short but have chunk headersconsole.log(JSON.stringify(rawDocs, null, 2));/* [ { "pageContent": "DOC NAME: Pam Interview\n---\n(cont'd) color is", "metadata": { "loc": { "lines": { "from": 1, "to": 1 } }, "doc_id": "affdcbeb-6bfb-42e9-afe5-80f4f2e9f6aa" } }, { "pageContent": "DOC NAME: Pam Interview\n---\n(cont'd) favorite", "metadata": { "loc": { "lines": { "from": 1, "to": 1 } }, "doc_id": "affdcbeb-6bfb-42e9-afe5-80f4f2e9f6aa" } }, { "pageContent": "DOC NAME: Pam Interview\n---\n(cont'd) red.", "metadata": { "loc": { "lines": { "from": 1, "to": 1 } }, "doc_id": "affdcbeb-6bfb-42e9-afe5-80f4f2e9f6aa" } }, { "pageContent": "DOC NAME: Pam Interview\n---\nMy", "metadata": { "loc": { "lines": { "from": 1, "to": 1 } }, "doc_id": "affdcbeb-6bfb-42e9-afe5-80f4f2e9f6aa" } } ]*/ #### API Reference: * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [HNSWLib](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_hnswlib.HNSWLib.html) from `@langchain/community/vectorstores/hnswlib` * [InMemoryStore](https://v02.api.js.langchain.com/classes/langchain_core_stores.InMemoryStore.html) from `@langchain/core/stores` * [ParentDocumentRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_parent_document.ParentDocumentRetriever.html) from `langchain/retrievers/parent_document` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` With Reranking[​](#with-reranking "Direct link to With Reranking") ------------------------------------------------------------------ With many documents from the vector store that are passed to LLM, final answers sometimes consist of information from irrelevant chunks, making it less precise and sometimes incorrect. Also, passing multiple irrelevant documents makes it more expensive. So there are two reasons to use rerank - precision and costs. import { OpenAIEmbeddings } from "@langchain/openai";import { CohereRerank } from "@langchain/cohere";import { HNSWLib } from "@langchain/community/vectorstores/hnswlib";import { InMemoryStore } from "@langchain/core/stores";import { ParentDocumentRetriever, type SubDocs,} from "langchain/retrievers/parent_document";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";// init Cohere Rerank. Remember to add COHERE_API_KEY to your .envconst reranker = new CohereRerank({ topN: 50, model: "rerank-multilingual-v2.0",});export function documentCompressorFiltering({ relevanceScore,}: { relevanceScore?: number } = {}) { return (docs: SubDocs) => { let outputDocs = docs; if (relevanceScore) { const docsRelevanceScoreValues = docs.map( (doc) => doc?.metadata?.relevanceScore ); outputDocs = docs.filter( (_doc, index) => (docsRelevanceScoreValues?.[index] || 1) >= relevanceScore ); } return outputDocs; };}const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 500, chunkOverlap: 0,});const jimDocs = await splitter.createDocuments([`Jim favorite color is blue.`]);const pamDocs = await splitter.createDocuments([`Pam favorite color is red.`]);const vectorstore = await HNSWLib.fromDocuments([], new OpenAIEmbeddings());const docstore = new InMemoryStore();const retriever = new ParentDocumentRetriever({ vectorstore, docstore, // Very small chunks for demo purposes. // Use a bigger chunk size for serious use-cases. childSplitter: new RecursiveCharacterTextSplitter({ chunkSize: 10, chunkOverlap: 0, }), childK: 50, parentK: 5, // We add Reranker documentCompressor: reranker, documentCompressorFilteringFn: documentCompressorFiltering({ relevanceScore: 0.3, }),});const docs = jimDocs.concat(pamDocs);await retriever.addDocuments(docs);// This will search for documents in vector store and return for LLM already reranked and sorted document// with appropriate minimum relevance scoreconst retrievedDocs = await retriever.invoke("What is Pam's favorite color?");// Pam's favorite color is returned first!console.log(JSON.stringify(retrievedDocs, null, 2));/* [ { "pageContent": "My favorite color is red.", "metadata": { "relevanceScore": 0.9 "loc": { "lines": { "from": 1, "to": 1 } } } } ]*/ #### API Reference: * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [CohereRerank](https://v02.api.js.langchain.com/classes/langchain_cohere.CohereRerank.html) from `@langchain/cohere` * [HNSWLib](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_hnswlib.HNSWLib.html) from `@langchain/community/vectorstores/hnswlib` * [InMemoryStore](https://v02.api.js.langchain.com/classes/langchain_core_stores.InMemoryStore.html) from `@langchain/core/stores` * [ParentDocumentRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_parent_document.ParentDocumentRetriever.html) from `langchain/retrievers/parent_document` * [SubDocs](https://v02.api.js.langchain.com/types/langchain_retrievers_parent_document.SubDocs.html) from `langchain/retrievers/parent_document` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned how to use the `ParentDocumentRetriever`. Next, check out the more general form of [generating multiple embeddings per document](/v0.2/docs/how_to/multi_vector), the [broader tutorial on RAG](/v0.2/docs/tutorials/rag), or this section to learn how to [create your own custom retriever over any data source](/v0.2/docs/how_to/custom_retriever/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to invoke runnables in parallel ](/v0.2/docs/how_to/parallel)[ Next How to partially format prompt templates ](/v0.2/docs/how_to/prompts_partial) * [Usage](#usage) * [With Score Threshold](#with-score-threshold) * [With Contextual chunk headers](#with-contextual-chunk-headers) * [With Reranking](#with-reranking) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/output_parser_xml
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to parse XML output On this page How to parse XML output ======================= Prerequisites This guide assumes familiarity with the following concepts: - [Chat models](/v0.2/docs/concepts/#chat-models) - [Output parsers](/v0.2/docs/concepts/#output-parsers) - [Prompt templates](/v0.2/docs/concepts/#prompt-templates) - [Structured output](/v0.2/docs/how_to/structured_output) - [Chaining runnables together](/v0.2/docs/how_to/sequence/) LLMs from different providers often have different strengths depending on the specific data they are trianed on. This also means that some may be “better” and more reliable at generating output in formats other than JSON. This guide shows you how to use the [`XMLOutputParser`](https://api.js.langchain.com/classes/langchain_core_output_parsers.XMLOutputParser.html) to prompt models for XML output, then and parse that output into a usable format. note Keep in mind that large language models are leaky abstractions! You’ll have to use an LLM with sufficient capacity to generate well-formed XML. In the following examples, we use Anthropic’s Claude ([https://docs.anthropic.com/claude/docs](https://docs.anthropic.com/claude/docs)), which is one such model that is optimized for XML tags. tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic Let’s start with a simple request to the model. import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", maxTokens: 512, temperature: 0.1,});const query = `Generate the shortened filmograph for Tom Hanks.`;const result = await model.invoke( query + ` Please enclose the movies in "movie" tags.`);console.log(result.content); Here is the shortened filmography for Tom Hanks, with movies enclosed in "movie" tags:<movie>Forrest Gump</movie><movie>Saving Private Ryan</movie><movie>Cast Away</movie><movie>Apollo 13</movie><movie>Catch Me If You Can</movie><movie>The Green Mile</movie><movie>Toy Story</movie><movie>Toy Story 2</movie><movie>Toy Story 3</movie><movie>Toy Story 4</movie><movie>Philadelphia</movie><movie>Big</movie><movie>Sleepless in Seattle</movie><movie>You've Got Mail</movie><movie>The Terminal</movie> This actually worked pretty well! But it would be nice to parse that XML into a more easily usable format. We can use the `XMLOutputParser` to both add default format instructions to the prompt and parse outputted XML into a dict: import { XMLOutputParser } from "@langchain/core/output_parsers";// We will add these instructions to the prompt belowconst parser = new XMLOutputParser();parser.getFormatInstructions(); "The output should be formatted as a XML file.\n" + "1. Output should conform to the tags below. \n" + "2. If tag"... 434 more characters import { ChatPromptTemplate } from "@langchain/core/prompts";const prompt = ChatPromptTemplate.fromTemplate( `{query}\n{format_instructions}`);const partialedPrompt = await prompt.partial({ format_instructions: parser.getFormatInstructions(),});const chain = partialedPrompt.pipe(model).pipe(parser);const output = await chain.invoke({ query: "Generate the shortened filmograph for Tom Hanks.",});console.log(JSON.stringify(output, null, 2)); { "filmography": [ { "actor": [ { "name": "Tom Hanks" }, { "films": [ { "film": [ { "title": "Forrest Gump" }, { "year": "1994" }, { "role": "Forrest Gump" } ] }, { "film": [ { "title": "Saving Private Ryan" }, { "year": "1998" }, { "role": "Captain Miller" } ] }, { "film": [ { "title": "Cast Away" }, { "year": "2000" }, { "role": "Chuck Noland" } ] }, { "film": [ { "title": "Catch Me If You Can" }, { "year": "2002" }, { "role": "Carl Hanratty" } ] }, { "film": [ { "title": "The Terminal" }, { "year": "2004" }, { "role": "Viktor Navorski" } ] } ] } ] } ]} You’ll notice above that our output is no longer just between `movie` tags. We can also add some tags to tailor the output to our needs: const parser = new XMLOutputParser({ tags: ["movies", "actor", "film", "name", "genre"],});// We will add these instructions to the prompt belowparser.getFormatInstructions(); "The output should be formatted as a XML file.\n" + "1. Output should conform to the tags below. \n" + "2. If tag"... 460 more characters You can and should experiment with adding your own formatting hints in the other parts of your prompt to either augment or replace the default instructions. Here’s the result when we invoke it: import { ChatPromptTemplate } from "@langchain/core/prompts";const prompt = ChatPromptTemplate.fromTemplate( `{query}\n{format_instructions}`);const partialedPrompt = await prompt.partial({ format_instructions: parser.getFormatInstructions(),});const chain = partialedPrompt.pipe(model).pipe(parser);const output = await chain.invoke({ query: "Generate the shortened filmograph for Tom Hanks.",});console.log(JSON.stringify(output, null, 2)); { "movies": [ { "actor": [ { "film": [ { "name": "Forrest Gump" }, { "genre": "Drama" } ] }, { "film": [ { "name": "Saving Private Ryan" }, { "genre": "War" } ] }, { "film": [ { "name": "Cast Away" }, { "genre": "Drama" } ] }, { "film": [ { "name": "Catch Me If You Can" }, { "genre": "Biography" } ] }, { "film": [ { "name": "The Terminal" }, { "genre": "Comedy-drama" } ] } ] } ]} Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to prompt a model to return XML. Next, check out the [broader guide on obtaining structured output](/v0.2/docs/how_to/structured_output) for other related techniques. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to parse JSON output ](/v0.2/docs/how_to/output_parser_json)[ Next How to invoke runnables in parallel ](/v0.2/docs/how_to/parallel) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/recursive_text_splitter
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to recursively split text by characters On this page How to recursively split text by characters =========================================== Prerequisites This guide assumes familiarity with the following concepts: * [Text splitters](/v0.2/docs/concepts#text-splitters) This text splitter is the recommended one for generic text. It is parameterized by a list of characters. It tries to split on them in order until the chunks are small enough. The default list is `["\n\n", "\n", " ", ""]`. This has the effect of trying to keep all paragraphs (and then sentences, and then words) together as long as possible, as those would generically seem to be the strongest semantically related pieces of text. 1. How the text is split: by list of characters. 2. How the chunk size is measured: by number of characters. Below we show example usage. To obtain the string content directly, use `.splitText`. To create LangChain [Document](https://v02.api.js.langchain.com/classes/langchain_core_documents.Document.html) objects (e.g., for use in downstream tasks), use `.createDocuments`. import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";const text = `Hi.\n\nI'm Harrison.\n\nHow? Are? You?\nOkay then f f f f.This is a weird text to write, but gotta test the splittingggg some how.\n\nBye!\n\n-H.`;const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 10, chunkOverlap: 1,});const output = await splitter.createDocuments([text]);console.log(output.slice(0, 3)); [ Document { pageContent: "Hi.", metadata: { loc: { lines: { from: 1, to: 1 } } } }, Document { pageContent: "I'm", metadata: { loc: { lines: { from: 3, to: 3 } } } }, Document { pageContent: "Harrison.", metadata: { loc: { lines: { from: 3, to: 3 } } } }] You’ll note that in the above example we are splitting a raw text string and getting back a list of documents. We can also split documents directly. import { Document } from "@langchain/core/documents";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";const text = `Hi.\n\nI'm Harrison.\n\nHow? Are? You?\nOkay then f f f f.This is a weird text to write, but gotta test the splittingggg some how.\n\nBye!\n\n-H.`;const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 10, chunkOverlap: 1,});const docOutput = await splitter.splitDocuments([ new Document({ pageContent: text }),]);console.log(docOutput.slice(0, 3)); [ Document { pageContent: "Hi.", metadata: { loc: { lines: { from: 1, to: 1 } } } }, Document { pageContent: "I'm", metadata: { loc: { lines: { from: 3, to: 3 } } } }, Document { pageContent: "Harrison.", metadata: { loc: { lines: { from: 3, to: 3 } } } }] You can customize the `RecursiveCharacterTextSplitter` with arbitrary separators by passing a `separators` parameter like this: import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { Document } from "@langchain/core/documents";const text = `Some other considerations include:- Do you deploy your backend and frontend together, or separately?- Do you deploy your backend co-located with your database, or separately?**Production Support:** As you move your LangChains into production, we'd love to offer more hands-on support.Fill out [this form](https://airtable.com/appwQzlErAS2qiP0L/shrGtGaVBVAz7NcV2) to share more about what you're building, and our team will get in touch.## Deployment OptionsSee below for a list of deployment options for your LangChain app. If you don't see your preferred option, please get in touch and we can add it to this list.`;const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 50, chunkOverlap: 1, separators: ["|", "##", ">", "-"],});const docOutput = await splitter.splitDocuments([ new Document({ pageContent: text }),]);console.log(docOutput.slice(0, 3)); [ Document { pageContent: "Some other considerations include:", metadata: { loc: { lines: { from: 1, to: 1 } } } }, Document { pageContent: "- Do you deploy your backend and frontend together", metadata: { loc: { lines: { from: 3, to: 3 } } } }, Document { pageContent: "r, or separately?", metadata: { loc: { lines: { from: 3, to: 3 } } } }] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned a method for splitting text by character. Next, check out [specific techinques for splitting on code](/v0.2/docs/how_to/code_splitter) or the [full tutorial on retrieval-augmented generation](/v0.2/docs/tutorials/rag). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to handle cases where no queries are generated ](/v0.2/docs/how_to/query_no_queries)[ Next How to reduce retrieval latency ](/v0.2/docs/how_to/reduce_retrieval_latency) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/reduce_retrieval_latency
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to reduce retrieval latency On this page How to reduce retrieval latency =============================== Prerequisites This guide assumes familiarity with the following concepts: * [Retrievers](/v0.2/docs/concepts/#retrievers) * [Embeddings](/v0.2/docs/concepts/#embedding-models) * [Vector stores](/v0.2/docs/concepts/#vectorstores) * [Retrieval-augmented generation (RAG)](/v0.2/docs/tutorials/rag) One way to reduce retrieval latency is through a technique called "Adaptive Retrieval". The [`MatryoshkaRetriever`](https://v02.api.js.langchain.com/classes/langchain_retrievers_matryoshka_retriever.MatryoshkaRetriever.html) uses the Matryoshka Representation Learning (MRL) technique to retrieve documents for a given query in two steps: * **First-pass**: Uses a lower dimensional sub-vector from the MRL embedding for an initial, fast, but less accurate search. * **Second-pass**: Re-ranks the top results from the first pass using the full, high-dimensional embedding for higher accuracy. ![Matryoshka Retriever](/v0.2/assets/images/adaptive_retrieval-2abb9f6f280c11a424ae6978d39eb011.png) It is based on this [Supabase](https://supabase.com/) blog post ["Matryoshka embeddings: faster OpenAI vector search using Adaptive Retrieval"](https://supabase.com/blog/matryoshka-embeddings). ### Setup[​](#setup "Direct link to Setup") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai @langchain/community yarn add @langchain/openai @langchain/community pnpm add @langchain/openai @langchain/community To follow the example below, you need an OpenAI API key: export OPENAI_API_KEY=your-api-key We'll also be using `chroma` for our vector store. Follow the instructions [here](/v0.2/docs/integrations/vectorstores/chroma) to setup. import { MatryoshkaRetriever } from "langchain/retrievers/matryoshka_retriever";import { Chroma } from "@langchain/community/vectorstores/chroma";import { OpenAIEmbeddings } from "@langchain/openai";import { Document } from "@langchain/core/documents";import { faker } from "@faker-js/faker";const smallEmbeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small", dimensions: 512, // Min number for small});const largeEmbeddings = new OpenAIEmbeddings({ model: "text-embedding-3-large", dimensions: 3072, // Max number for large});const vectorStore = new Chroma(smallEmbeddings, { numDimensions: 512,});const retriever = new MatryoshkaRetriever({ vectorStore, largeEmbeddingModel: largeEmbeddings, largeK: 5,});const irrelevantDocs = Array.from({ length: 250 }).map( () => new Document({ pageContent: faker.lorem.word(7), // Similar length to the relevant docs }));const relevantDocs = [ new Document({ pageContent: "LangChain is an open source github repo", }), new Document({ pageContent: "There are JS and PY versions of the LangChain github repos", }), new Document({ pageContent: "LangGraph is a new open source library by the LangChain team", }), new Document({ pageContent: "LangChain announced GA of LangSmith last week!", }), new Document({ pageContent: "I heart LangChain", }),];const allDocs = [...irrelevantDocs, ...relevantDocs];/** * IMPORTANT: * The `addDocuments` method on `MatryoshkaRetriever` will * generate the small AND large embeddings for all documents. */await retriever.addDocuments(allDocs);const query = "What is LangChain?";const results = await retriever.invoke(query);console.log(results.map(({ pageContent }) => pageContent).join("\n"));/** I heart LangChain LangGraph is a new open source library by the LangChain team LangChain is an open source github repo LangChain announced GA of LangSmith last week! There are JS and PY versions of the LangChain github repos*/ #### API Reference: * [MatryoshkaRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_matryoshka_retriever.MatryoshkaRetriever.html) from `langchain/retrievers/matryoshka_retriever` * [Chroma](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_chroma.Chroma.html) from `@langchain/community/vectorstores/chroma` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [Document](https://v02.api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents` note Due to the constraints of some vector stores, the large embedding metadata field is stringified (`JSON.stringify`) before being stored. This means that the metadata field will need to be parsed (`JSON.parse`) when retrieved from the vector store. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned a technique that can help speed up your retrieval queries. Next, check out the [broader tutorial on RAG](/v0.2/docs/tutorials/rag), or this section to learn how to [create your own custom retriever over any data source](/v0.2/docs/how_to/custom_retriever/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to recursively split text by characters ](/v0.2/docs/how_to/recursive_text_splitter)[ Next How to route execution within a chain ](/v0.2/docs/how_to/routing) * [Setup](#setup) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/qa_chat_history_how_to
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to add chat history to a question-answering chain On this page How to add chat history to a question-answering chain ===================================================== Prerequisites This guide assumes familiarity with the following: * [Retrieval-augmented generation](/v0.2/docs/tutorials/rag/) In many Q&A applications we want to allow the user to have a back-and-forth conversation, meaning the application needs some sort of “memory” of past questions and answers, and some logic for incorporating those into its current thinking. In this guide we focus on **adding logic for incorporating historical messages, and NOT on chat history management.** Chat history management is [covered here](/v0.2/docs/how_to/message_history). We’ll work off of the Q&A app we built over the [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) blog post by Lilian Weng. We’ll need to update two things about our existing app: 1. **Prompt**: Update our prompt to support historical messages as an input. 2. **Contextualizing questions**: Add a sub-chain that takes the latest user question and reformulates it in the context of the chat history. This is needed in case the latest question references some context from past messages. For example, if a user asks a follow-up question like “Can you elaborate on the second point?”, this cannot be understood without the context of the previous message. Therefore we can’t effectively perform retrieval with a question like this. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Dependencies[​](#dependencies "Direct link to Dependencies") We’ll use an OpenAI chat model and embeddings and a Memory vector store in this walkthrough, but everything shown here works with any [ChatModel](/v0.2/docs/concepts/#chat-models) or [LLM](/v0.2/docs/concepts#llms), [Embeddings](/v0.2/docs/concepts#embedding-models), and [VectorStore](/v0.2/docs/concepts#vectorstores) or [Retriever](/v0.2/docs/concepts#retrievers). We’ll use the following packages: npm install --save langchain @langchain/openai cheerio We need to set environment variable `OPENAI_API_KEY`: export OPENAI_API_KEY=YOUR_KEY ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://docs.smith.langchain.com). Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=YOUR_KEY ### Initial setup[​](#initial-setup "Direct link to Initial setup") import "cheerio";import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { pull } from "langchain/hub";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnableSequence, RunnablePassthrough,} from "@langchain/core/runnables";import { StringOutputParser } from "@langchain/core/output_parsers";import { createStuffDocumentsChain } from "langchain/chains/combine_documents";const loader = new CheerioWebBaseLoader( "https://lilianweng.github.io/posts/2023-06-23-agent/");const docs = await loader.load();const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const splits = await textSplitter.splitDocuments(docs);const vectorStore = await MemoryVectorStore.fromDocuments( splits, new OpenAIEmbeddings());// Retrieve and generate using the relevant snippets of the blog.const retriever = vectorStore.asRetriever();// Tip - you can edit this!const prompt = await pull<ChatPromptTemplate>("rlm/rag-prompt");const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const ragChain = await createStuffDocumentsChain({ llm, prompt, outputParser: new StringOutputParser(),}); Let’s see what this prompt actually looks like console.log(prompt.promptMessages.map((msg) => msg.prompt.template).join("\n")); You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.Question: {question}Context: {context}Answer: await ragChain.invoke({ context: await retriever.invoke("What is Task Decomposition?"), question: "What is Task Decomposition?",}); "Task Decomposition involves breaking down complex tasks into smaller and simpler steps to make them "... 243 more characters Contextualizing the question[​](#contextualizing-the-question "Direct link to Contextualizing the question") ------------------------------------------------------------------------------------------------------------ First we’ll need to define a sub-chain that takes historical messages and the latest user question, and reformulates the question if it makes reference to any information in the historical information. We’ll use a prompt that includes a `MessagesPlaceholder` variable under the name “chat\_history”. This allows us to pass in a list of Messages to the prompt using the “chat\_history” input key, and these messages will be inserted after the system message and before the human message containing the latest question. import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";const contextualizeQSystemPrompt = `Given a chat history and the latest user questionwhich might reference context in the chat history, formulate a standalone questionwhich can be understood without the chat history. Do NOT answer the question,just reformulate it if needed and otherwise return it as is.`;const contextualizeQPrompt = ChatPromptTemplate.fromMessages([ ["system", contextualizeQSystemPrompt], new MessagesPlaceholder("chat_history"), ["human", "{question}"],]);const contextualizeQChain = contextualizeQPrompt .pipe(llm) .pipe(new StringOutputParser()); Using this chain we can ask follow-up questions that reference past messages and have them reformulated into standalone questions: import { AIMessage, HumanMessage } from "@langchain/core/messages";await contextualizeQChain.invoke({ chat_history: [ new HumanMessage("What does LLM stand for?"), new AIMessage("Large language model"), ], question: "What is meant by large",}); 'What is the definition of "large" in this context?' Chain with chat history[​](#chain-with-chat-history "Direct link to Chain with chat history") --------------------------------------------------------------------------------------------- And now we can build our full QA chain. Notice we add some routing functionality to only run the “condense question chain” when our chat history isn’t empty. Here we’re taking advantage of the fact that if a function in an LCEL chain returns another chain, that chain will itself be invoked. import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { formatDocumentsAsString } from "langchain/util/document";const qaSystemPrompt = `You are an assistant for question-answering tasks.Use the following pieces of retrieved context to answer the question.If you don't know the answer, just say that you don't know.Use three sentences maximum and keep the answer concise.{context}`;const qaPrompt = ChatPromptTemplate.fromMessages([ ["system", qaSystemPrompt], new MessagesPlaceholder("chat_history"), ["human", "{question}"],]);const contextualizedQuestion = (input: Record<string, unknown>) => { if ("chat_history" in input) { return contextualizeQChain; } return input.question;};const ragChain = RunnableSequence.from([ RunnablePassthrough.assign({ context: async (input: Record<string, unknown>) => { if ("chat_history" in input) { const chain = contextualizedQuestion(input); return chain.pipe(retriever).pipe(formatDocumentsAsString); } return ""; }, }), qaPrompt, llm,]);const chat_history = [];const question = "What is task decomposition?";const aiMsg = await ragChain.invoke({ question, chat_history });console.log(aiMsg);chat_history.push(aiMsg);const secondQuestion = "What are common ways of doing it?";await ragChain.invoke({ question: secondQuestion, chat_history }); AIMessage { lc_serializable: true, lc_kwargs: { content: "Task decomposition involves breaking down a complex task into smaller and simpler steps to make it m"... 358 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Task decomposition involves breaking down a complex task into smaller and simpler steps to make it m"... 358 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 83, promptTokens: 701, totalTokens: 784 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} AIMessage { lc_serializable: true, lc_kwargs: { content: "Common ways of task decomposition include using simple prompting techniques like Chain of Thought (C"... 353 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Common ways of task decomposition include using simple prompting techniques like Chain of Thought (C"... 353 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 81, promptTokens: 779, totalTokens: 860 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} See the first [LangSmith trace here](https://smith.langchain.com/public/527981c6-5018-4b68-a11a-ebcde77843e7/r) and the [second trace here](https://smith.langchain.com/public/7b97994a-ab9f-4bf3-a2e4-abb609e5610a/r) Here we’ve gone over how to add application logic for incorporating historical outputs, but we’re still manually updating the chat history and inserting it into each input. In a real Q&A application we’ll want some way of persisting chat history and some way of automatically inserting and updating it. For this we can use: * [BaseChatMessageHistory](https://v02.api.js.langchain.com/classes/langchain_core_chat_history.BaseChatMessageHistory.html): Store chat history. * [RunnableWithMessageHistory](/v0.2/docs/how_to/message_history/): Wrapper for an LCEL chain and a `BaseChatMessageHistory` that handles injecting chat history into inputs and updating it after each invocation. For a detailed walkthrough of how to use these classes together to create a stateful conversational chain, head to the [How to add message history (memory)](/v0.2/docs/how_to/message_history/) LCEL page. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to partially format prompt templates ](/v0.2/docs/how_to/prompts_partial)[ Next How to return citations ](/v0.2/docs/how_to/qa_citations) * [Setup](#setup) * [Dependencies](#dependencies) * [LangSmith](#langsmith) * [Initial setup](#initial-setup) * [Contextualizing the question](#contextualizing-the-question) * [Chain with chat history](#chain-with-chat-history)
null
https://js.langchain.com/v0.2/docs/how_to/caching_embeddings
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to cache embedding results On this page How to cache embedding results ============================== Prerequisites This guide assumes familiarity with the following concepts: * [Embeddings](/v0.2/docs/concepts/#embedding-models) Embeddings can be stored or temporarily cached to avoid needing to recompute them. Caching embeddings can be done using a `CacheBackedEmbeddings` instance. The cache backed embedder is a wrapper around an embedder that caches embeddings in a key-value store. The text is hashed and the hash is used as the key in the cache. The main supported way to initialized a `CacheBackedEmbeddings` is the `fromBytesStore` static method. This takes in the following parameters: * `underlyingEmbeddings`: The embeddings model to use. * `documentEmbeddingCache`: The cache to use for storing document embeddings. * `namespace`: (optional, defaults to "") The namespace to use for document cache. This namespace is used to avoid collisions with other caches. For example, you could set it to the name of the embedding model used. **Attention:** Be sure to set the namespace parameter to avoid collisions of the same text embedded using different embeddings models. In-memory[​](#in-memory "Direct link to In-memory") --------------------------------------------------- tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai @langchain/community yarn add @langchain/openai @langchain/community pnpm add @langchain/openai @langchain/community Here's a basic test example with an in memory cache. This type of cache is primarily useful for unit tests or prototyping. Do not use this cache if you need to actually store the embeddings for an extended period of time: import { OpenAIEmbeddings } from "@langchain/openai";import { CacheBackedEmbeddings } from "langchain/embeddings/cache_backed";import { InMemoryStore } from "@langchain/core/stores";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { FaissStore } from "@langchain/community/vectorstores/faiss";import { TextLoader } from "langchain/document_loaders/fs/text";const underlyingEmbeddings = new OpenAIEmbeddings();const inMemoryStore = new InMemoryStore();const cacheBackedEmbeddings = CacheBackedEmbeddings.fromBytesStore( underlyingEmbeddings, inMemoryStore, { namespace: underlyingEmbeddings.modelName, });const loader = new TextLoader("./state_of_the_union.txt");const rawDocuments = await loader.load();const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 0,});const documents = await splitter.splitDocuments(rawDocuments);// No keys logged yet since the cache is emptyfor await (const key of inMemoryStore.yieldKeys()) { console.log(key);}let time = Date.now();const vectorstore = await FaissStore.fromDocuments( documents, cacheBackedEmbeddings);console.log(`Initial creation time: ${Date.now() - time}ms`);/* Initial creation time: 1905ms*/// The second time is much faster since the embeddings for the input docs have already been added to the cachetime = Date.now();const vectorstore2 = await FaissStore.fromDocuments( documents, cacheBackedEmbeddings);console.log(`Cached creation time: ${Date.now() - time}ms`);/* Cached creation time: 8ms*/// Many keys logged with hashed valuesconst keys = [];for await (const key of inMemoryStore.yieldKeys()) { keys.push(key);}console.log(keys.slice(0, 5));/* [ 'text-embedding-ada-002ea9b59e760e64bec6ee9097b5a06b0d91cb3ab64', 'text-embedding-ada-0023b424f5ed1271a6f5601add17c1b58b7c992772e', 'text-embedding-ada-002fec5d021611e1527297c5e8f485876ea82dcb111', 'text-embedding-ada-00262f72e0c2d711c6b861714ee624b28af639fdb13', 'text-embedding-ada-00262d58882330038a4e6e25ea69a938f4391541874' ]*/ #### API Reference: * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [CacheBackedEmbeddings](https://v02.api.js.langchain.com/classes/langchain_embeddings_cache_backed.CacheBackedEmbeddings.html) from `langchain/embeddings/cache_backed` * [InMemoryStore](https://v02.api.js.langchain.com/classes/langchain_core_stores.InMemoryStore.html) from `@langchain/core/stores` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [FaissStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_faiss.FaissStore.html) from `@langchain/community/vectorstores/faiss` * [TextLoader](https://v02.api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text` Redis[​](#redis "Direct link to Redis") --------------------------------------- Here's an example with a Redis cache. You'll first need to install `ioredis` as a peer dependency and pass in an initialized client: * npm * Yarn * pnpm npm install ioredis yarn add ioredis pnpm add ioredis import { Redis } from "ioredis";import { OpenAIEmbeddings } from "@langchain/openai";import { CacheBackedEmbeddings } from "langchain/embeddings/cache_backed";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { FaissStore } from "@langchain/community/vectorstores/faiss";import { RedisByteStore } from "@langchain/community/storage/ioredis";import { TextLoader } from "langchain/document_loaders/fs/text";const underlyingEmbeddings = new OpenAIEmbeddings();// Requires a Redis instance running at http://localhost:6379.// See https://github.com/redis/ioredis for full config options.const redisClient = new Redis();const redisStore = new RedisByteStore({ client: redisClient,});const cacheBackedEmbeddings = CacheBackedEmbeddings.fromBytesStore( underlyingEmbeddings, redisStore, { namespace: underlyingEmbeddings.modelName, });const loader = new TextLoader("./state_of_the_union.txt");const rawDocuments = await loader.load();const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 0,});const documents = await splitter.splitDocuments(rawDocuments);let time = Date.now();const vectorstore = await FaissStore.fromDocuments( documents, cacheBackedEmbeddings);console.log(`Initial creation time: ${Date.now() - time}ms`);/* Initial creation time: 1808ms*/// The second time is much faster since the embeddings for the input docs have already been added to the cachetime = Date.now();const vectorstore2 = await FaissStore.fromDocuments( documents, cacheBackedEmbeddings);console.log(`Cached creation time: ${Date.now() - time}ms`);/* Cached creation time: 33ms*/// Many keys logged with hashed valuesconst keys = [];for await (const key of redisStore.yieldKeys()) { keys.push(key);}console.log(keys.slice(0, 5));/* [ 'text-embedding-ada-002fa9ac80e1bf226b7b4dfc03ea743289a65a727b2', 'text-embedding-ada-0027dbf9c4b36e12fe1768300f145f4640342daaf22', 'text-embedding-ada-002ea9b59e760e64bec6ee9097b5a06b0d91cb3ab64', 'text-embedding-ada-002fec5d021611e1527297c5e8f485876ea82dcb111', 'text-embedding-ada-002c00f818c345da13fed9f2697b4b689338143c8c7' ]*/ #### API Reference: * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [CacheBackedEmbeddings](https://v02.api.js.langchain.com/classes/langchain_embeddings_cache_backed.CacheBackedEmbeddings.html) from `langchain/embeddings/cache_backed` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [FaissStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_faiss.FaissStore.html) from `@langchain/community/vectorstores/faiss` * [RedisByteStore](https://v02.api.js.langchain.com/classes/langchain_community_storage_ioredis.RedisByteStore.html) from `@langchain/community/storage/ioredis` * [TextLoader](https://v02.api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned how to use caching to avoid recomputing embeddings. Next, check out the [full tutorial on retrieval-augmented generation](/v0.2/docs/tutorials/rag). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to attach runtime arguments to a Runnable ](/v0.2/docs/how_to/binding)[ Next How to attach callbacks to a module ](/v0.2/docs/how_to/callbacks_attach) * [In-memory](#in-memory) * [Redis](#redis) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/classification
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Tagging On this page Classify Text into Labels ========================= Tagging means labeling a document with classes such as: * sentiment * language * style (formal, informal etc.) * covered topics * political tendency ![Image description](/v0.2/assets/images/tagging-93990e95451d92b715c2b47066384224.png) Overview[​](#overview "Direct link to Overview") ------------------------------------------------ Tagging has a few components: * `function`: Like [extraction](/v0.2/docs/tutorials/extraction), tagging uses [functions](https://openai.com/blog/function-calling-and-other-api-updates) to specify how the model should tag a document * `schema`: defines how we want to tag the document Quickstart[​](#quickstart "Direct link to Quickstart") ------------------------------------------------------ Let’s see a very straightforward example of how we can use OpenAI tool calling for tagging in LangChain. We’ll use the `.withStructuredOutput()` method supported by OpenAI models: * npm * yarn * pnpm npm i langchain @langchain/openai @langchain/core zod yarn add langchain @langchain/openai @langchain/core zod pnpm add langchain @langchain/openai @langchain/core zod Let’s specify a [Zod](https://zod.dev) schema with a few properties and their expected type in our schema. import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatOpenAI } from "@langchain/openai";import { z } from "zod";const taggingPrompt = ChatPromptTemplate.fromTemplate( `Extract the desired information from the following passage.Only extract the properties mentioned in the 'Classification' function.Passage:{input}`);const classificationSchema = z.object({ sentiment: z.string().describe("The sentiment of the text"), aggressiveness: z .number() .int() .min(1) .max(10) .describe("How aggressive the text is on a scale from 1 to 10"), language: z.string().describe("The language the text is written in"),});// LLMconst llm = new ChatOpenAI({ temperature: 0, model: "gpt-3.5-turbo-0125",});// Name is optional, but gives the models more clues as to what your schema representsconst llmWihStructuredOutput = llm.withStructuredOutput(classificationSchema, { name: "extractor",});const taggingChain = taggingPrompt.pipe(llmWihStructuredOutput); const input = "Estoy increiblemente contento de haberte conocido! Creo que seremos muy buenos amigos!";await taggingChain.invoke({ input }); { sentiment: "positive", aggressiveness: 1, language: "Spanish" } As we can see in the example, it correctly interprets what we want. The results vary so that we may get, for example, sentiments in different languages (‘positive’, ‘enojado’ etc.). We will see how to control these results in the next section. Finer control[​](#finer-control "Direct link to Finer control") --------------------------------------------------------------- Careful schema definition gives us more control over the model’s output. Specifically, we can define: * possible values for each property * description to make sure that the model understands the property * required properties to be returned Let’s redeclare our Zod schema to control for each of the previously mentioned aspects using enums: import { z } from "zod";const classificationSchema = z.object({ sentiment: z .enum(["happy", "neutral", "sad"]) .describe("The sentiment of the text"), aggressiveness: z .number() .int() .min(1) .max(5) .describe( "describes how aggressive the statement is, the higher the number the more aggressive" ), language: z .enum(["spanish", "english", "french", "german", "italian"]) .describe("The language the text is written in"),}); const taggingPrompt = ChatPromptTemplate.fromTemplate( `Extract the desired information from the following passage.Only extract the properties mentioned in the 'Classification' function.Passage:{input}`);// LLMconst llm = new ChatOpenAI({ temperature: 0, model: "gpt-3.5-turbo-0125",});const llmWihStructuredOutput = llm.withStructuredOutput(classificationSchema, { name: "extractor",});const chain = taggingPrompt.pipe(llmWihStructuredOutput); Now the answers will be restricted in a way we expect! const input = "Estoy increiblemente contento de haberte conocido! Creo que seremos muy buenos amigos!";await chain.invoke({ input }); { sentiment: "happy", aggressiveness: 3, language: "spanish" } const input = "Estoy muy enojado con vos! Te voy a dar tu merecido!";await chain.invoke({ input }); { sentiment: "sad", aggressiveness: 5, language: "spanish" } const input = "Weather is ok here, I can go outside without much more than a coat";await chain.invoke({ input }); { sentiment: "neutral", aggressiveness: 3, language: "english" } The [LangSmith trace](https://smith.langchain.com/public/455f5404-8784-49ce-8851-0619b99e936f/r) lets us peek under the hood: ![](/v0.2/assets/images/classification_ls_trace-7b269b067c3751c6d06289c560505656.png) * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Summarize Text ](/v0.2/docs/tutorials/summarization)[ Next Build a Local RAG Application ](/v0.2/docs/tutorials/local_rag) * [Overview](#overview) * [Quickstart](#quickstart) * [Finer control](#finer-control)
null
https://js.langchain.com/v0.2/docs/tutorials/summarization
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Summarize Text Summarize Text ============== A common use case is wanting to summarize long documents. This naturally runs into the context window limitations. Unlike in question-answering, you can't just do some semantic search hacks to only select the chunks of text most relevant to the question (because, in this case, there is no particular question - you want to summarize everything). So what do you do then? To get started, we would recommend checking out the summarization chain, which attacks this problem in a recursive manner. * [Summarization Chain](https://js.langchain.com/v0.1/docs/modules/chains/popular/summarize) Example[​](#example "Direct link to Example") --------------------------------------------- Here's an example of how you can use the [RefineDocumentsChain](https://js.langchain.com/v0.1/docs/modules/chains/document/refine) to summarize documents loaded from a YouTube video: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic import { loadSummarizationChain } from "langchain/chains";import { SearchApiLoader } from "@langchain/community/document_loaders/web/searchapi";import { TokenTextSplitter } from "@langchain/textsplitters";import { PromptTemplate } from "@langchain/core/prompts";import { ChatAnthropic } from "@langchain/anthropic";const loader = new SearchApiLoader({ engine: "youtube_transcripts", video_id: "WTOm65IZneg",});const docs = await loader.load();const splitter = new TokenTextSplitter({ chunkSize: 10000, chunkOverlap: 250,});const docsSummary = await splitter.splitDocuments(docs);const llmSummary = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0.3,});const summaryTemplate = `You are an expert in summarizing YouTube videos.Your goal is to create a summary of a podcast.Below you find the transcript of a podcast:--------{text}--------The transcript of the podcast will also be used as the basis for a question and answer bot.Provide some examples questions and answers that could be asked about the podcast. Make these questions very specific.Total output will be a summary of the video and a list of example questions the user could ask of the video.SUMMARY AND QUESTIONS:`;const SUMMARY_PROMPT = PromptTemplate.fromTemplate(summaryTemplate);const summaryRefineTemplate = `You are an expert in summarizing YouTube videos.Your goal is to create a summary of a podcast.We have provided an existing summary up to a certain point: {existing_answer}Below you find the transcript of a podcast:--------{text}--------Given the new context, refine the summary and example questions.The transcript of the podcast will also be used as the basis for a question and answer bot.Provide some examples questions and answers that could be asked about the podcast. Makethese questions very specific.If the context isn't useful, return the original summary and questions.Total output will be a summary of the video and a list of example questions the user could ask of the video.SUMMARY AND QUESTIONS:`;const SUMMARY_REFINE_PROMPT = PromptTemplate.fromTemplate( summaryRefineTemplate);const summarizeChain = loadSummarizationChain(llmSummary, { type: "refine", verbose: true, questionPrompt: SUMMARY_PROMPT, refinePrompt: SUMMARY_REFINE_PROMPT,});const summary = await summarizeChain.run(docsSummary);console.log(summary);/* Here is a summary of the key points from the podcast transcript: - Jimmy helps provide hearing aids and cochlear implants to deaf and hard-of-hearing people who can't afford them. He helps over 1,000 people hear again. - Jimmy surprises recipients with $10,000 cash gifts in addition to the hearing aids. He also gifts things like jet skis, basketball game tickets, and trips to concerts. - Jimmy travels internationally to provide hearing aids, visiting places like Mexico, Guatemala, Brazil, South Africa, Malawi, and Indonesia. - Jimmy donates $100,000 to organizations around the world that teach sign language. - The recipients are very emotional and grateful to be able to hear their loved ones again. Here are some example questions and answers about the podcast: Q: How many people did Jimmy help regain their hearing? A: Jimmy helped over 1,000 people regain their hearing. Q: What types of hearing devices did Jimmy provide to the recipients? A: Jimmy provided cutting-edge hearing aids and cochlear implants. Q: In addition to the hearing devices, what surprise gifts did Jimmy give some recipients? A: In addition to hearing devices, Jimmy surprised some recipients with $10,000 cash gifts, jet skis, basketball game tickets, and concert tickets. Q: What countries did Jimmy travel to in order to help people? A: Jimmy traveled to places like Mexico, Guatemala, Brazil, South Africa, Malawi, and Indonesia. Q: How much money did Jimmy donate to organizations that teach sign language? A: Jimmy donated $100,000 to sign language organizations around the world. Q: How did the recipients react when they were able to hear again? A: The recipients were very emotional and grateful, with many crying tears of joy at being able to hear their loved ones again.*/ #### API Reference: * [loadSummarizationChain](https://v02.api.js.langchain.com/functions/langchain_chains.loadSummarizationChain.html) from `langchain/chains` * [SearchApiLoader](https://v02.api.js.langchain.com/classes/langchain_community_document_loaders_web_searchapi.SearchApiLoader.html) from `@langchain/community/document_loaders/web/searchapi` * [TokenTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.TokenTextSplitter.html) from `@langchain/textsplitters` * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` * [ChatAnthropic](https://v02.api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic` * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build an Extraction Chain ](/v0.2/docs/tutorials/extraction)[ Next Tagging ](/v0.2/docs/tutorials/classification)
null
https://js.langchain.com/v0.2/docs/how_to/routing
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to route execution within a chain On this page How to route execution within a chain ===================================== Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) * [Chaining runnables](/v0.2/docs/how_to/sequence/) * [Configuring chain parameters at runtime](/v0.2/docs/how_to/binding) * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) * [Chat Messages](/v0.2/docs/concepts/#message-types) This guide covers how to do routing in the LangChain Expression Language. Routing allows you to create non-deterministic chains where the output of a previous step defines the next step. Routing helps provide structure and consistency around interactions with LLMs. There are two ways to perform routing: 1. Conditionally return runnables from a [`RunnableLambda`](/v0.2/docs/how_to/functions) (recommended) 2. Using a `RunnableBranch` (legacy) We'll illustrate both methods using a two step sequence where the first step classifies an input question as being about LangChain, Anthropic, or Other, then routes to a corresponding prompt chain. Using a custom function[​](#using-a-custom-function "Direct link to Using a custom function") --------------------------------------------------------------------------------------------- You can use a custom function to route between different outputs. Here's an example: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic import { ChatPromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnableSequence } from "@langchain/core/runnables";import { ChatAnthropic } from "@langchain/anthropic";const promptTemplate = ChatPromptTemplate.fromTemplate(`Given the user question below, classify it as either being about \`LangChain\`, \`Anthropic\`, or \`Other\`. Do not respond with more than one word.<question>{question}</question>Classification:`);const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229",});const classificationChain = RunnableSequence.from([ promptTemplate, model, new StringOutputParser(),]);const classificationChainResult = await classificationChain.invoke({ question: "how do I call Anthropic?",});console.log(classificationChainResult);/* Anthropic*/const langChainChain = ChatPromptTemplate.fromTemplate( `You are an expert in langchain.Always answer questions starting with "As Harrison Chase told me".Respond to the following question:Question: {question}Answer:`).pipe(model);const anthropicChain = ChatPromptTemplate.fromTemplate( `You are an expert in anthropic. \Always answer questions starting with "As Dario Amodei told me". \Respond to the following question:Question: {question}Answer:`).pipe(model);const generalChain = ChatPromptTemplate.fromTemplate( `Respond to the following question:Question: {question}Answer:`).pipe(model);const route = ({ topic }: { input: string; topic: string }) => { if (topic.toLowerCase().includes("anthropic")) { return anthropicChain; } else if (topic.toLowerCase().includes("langchain")) { return langChainChain; } else { return generalChain; }};const fullChain = RunnableSequence.from([ { topic: classificationChain, question: (input: { question: string }) => input.question, }, route,]);const result1 = await fullChain.invoke({ question: "how do I use Anthropic?",});console.log(result1);/* AIMessage { content: ' As Dario Amodei told me, here are some tips for how to use Anthropic:\n' + '\n' + "First, sign up for an account on Anthropic's website. This will give you access to their conversational AI assistant named Claude. \n" + '\n' + "Once you've created an account, you can have conversations with Claude through their web interface. Talk to Claude like you would talk to a person, asking questions, giving instructions, etc. Claude is trained to have natural conversations and be helpful.\n" + '\n' + "You can also integrate Claude into your own applications using Anthropic's API. This allows you to build Claude's conversational abilities into chatbots, virtual assistants, and other AI systems you develop.\n" + '\n' + 'Anthropic is constantly working on improving Claude, so its capabilities are always expanding. Make sure to check their blog and documentation to stay up to date on the latest features.\n' + '\n' + 'The key is to interact with Claude regularly so it can learn from you. The more you chat with it, the better it will become at understanding you and having personalized conversations. Over time, Claude will feel more human-like as it accumulates more conversational experience.', additional_kwargs: {} }*/const result2 = await fullChain.invoke({ question: "how do I use LangChain?",});console.log(result2);/* AIMessage { content: ' As Harrison Chase told me, here is how you use LangChain:\n' + '\n' + 'First, think carefully about what you want to ask or have the AI do. Frame your request clearly and specifically. Avoid vague or overly broad prompts that could lead to unhelpful or concerning responses. \n' + '\n' + 'Next, type your question or request into the chat window and send it. Be patient as the AI processes your input and generates a response. The AI will do its best to provide a helpful answer or follow your instructions, but its capabilities are limited.\n' + '\n' + 'Keep your requests simple at first. Ask basic questions or have the AI summarize content or generate basic text. As you get more comfortable, you can try having the AI perform more complex tasks like answering tricky questions, generating stories, or having a conversation.\n' + '\n' + "Pay attention to the AI's responses. If they seem off topic, nonsensical, or concerning, rephrase your prompt to steer the AI in a better direction. You may need to provide additional clarification or context to get useful results.\n" + '\n' + 'Be polite and respectful towards the AI system. Remember, it is a tool designed to be helpful, harmless, and honest. Do not try to trick, confuse, or exploit it. \n' + '\n' + 'I hope these tips help you have a safe, fun and productive experience using LangChain! Let me know if you have any other questions.', additional_kwargs: {} }*/const result3 = await fullChain.invoke({ question: "what is 2 + 2?",});console.log(result3);/* AIMessage { content: ' 4', additional_kwargs: {} }*/ #### API Reference: * [ChatPromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts` * [StringOutputParser](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [ChatAnthropic](https://v02.api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic` Routing by semantic similarity[​](#routing-by-semantic-similarity "Direct link to Routing by semantic similarity") ------------------------------------------------------------------------------------------------------------------ One especially useful technique is to use embeddings to route a query to the most relevant prompt. Here's an example: import { ChatAnthropic } from "@langchain/anthropic";import { OpenAIEmbeddings } from "@langchain/openai";import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnableSequence } from "@langchain/core/runnables";import { cosineSimilarity } from "@langchain/core/utils/math";const physicsTemplate = `You are a very smart physics professor.You are great at answering questions about physics in a concise and easy to understand manner.When you don't know the answer to a question you admit that you don't know.Do not use more than 100 words.Here is a question:{query}`;const mathTemplate = `"You are a very good mathematician. You are great at answering math questions.You are so good because you are able to break down hard problems into their component parts,answer the component parts, and then put them together to answer the broader question.Do not use more than 100 words.Here is a question:{query}`;const embeddings = new OpenAIEmbeddings({});const templates = [physicsTemplate, mathTemplate];const templateEmbeddings = await embeddings.embedDocuments(templates);const promptRouter = async (query: string) => { const queryEmbedding = await embeddings.embedQuery(query); const similarity = cosineSimilarity([queryEmbedding], templateEmbeddings)[0]; const isPhysicsQuestion = similarity[0] > similarity[1]; let promptTemplate: ChatPromptTemplate; if (isPhysicsQuestion) { console.log(`Using physics prompt`); promptTemplate = ChatPromptTemplate.fromTemplate(templates[0]); } else { console.log(`Using math prompt`); promptTemplate = ChatPromptTemplate.fromTemplate(templates[1]); } return promptTemplate.invoke({ query });};const chain = RunnableSequence.from([ promptRouter, new ChatAnthropic({ model: "claude-3-haiku-20240307" }), new StringOutputParser(),]);console.log(await chain.invoke("what's a black hole?"));/* Using physics prompt*//* A black hole is a region in space where the gravitational pull is so strong that nothing, not even light, can escape from it. It is the result of the gravitational collapse of a massive star, creating a singularity surrounded by an event horizon, beyond which all information is lost. Black holes have fascinated scientists for decades, as they provide insights into the most extreme conditions in the universe and the nature of gravity itself. While we understand the basic properties of black holes, there are still many unanswered questions about their behavior and their role in the cosmos.*/console.log(await chain.invoke("what's a path integral?"));/* Using math prompt*//* A path integral is a mathematical formulation in quantum mechanics used to describe the behavior of a particle or system. It considers all possible paths the particle can take between two points, and assigns a probability amplitude to each path. By summing up the contributions from all paths, it provides a comprehensive understanding of the particle's quantum mechanical behavior. This approach allows for the calculation of complex quantum phenomena, such as quantum tunneling and interference effects, making it a powerful tool in theoretical physics.*/ #### API Reference: * [ChatAnthropic](https://v02.api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [StringOutputParser](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers` * [ChatPromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [cosineSimilarity](https://v02.api.js.langchain.com/functions/langchain_core_utils_math.cosineSimilarity.html) from `@langchain/core/utils/math` Using a RunnableBranch[​](#using-a-runnablebranch "Direct link to Using a RunnableBranch") ------------------------------------------------------------------------------------------ A `RunnableBranch` is initialized with a list of (condition, runnable) pairs and a default runnable. It selects which branch by passing each condition the input it's invoked with. It selects the first condition to evaluate to True, and runs the corresponding runnable to that condition with the input. If no provided conditions match, it runs the default runnable. Here's an example of what it looks like in action: import { ChatPromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnableBranch, RunnableSequence } from "@langchain/core/runnables";import { ChatAnthropic } from "@langchain/anthropic";const promptTemplate = ChatPromptTemplate.fromTemplate(`Given the user question below, classify it as either being about \`LangChain\`, \`Anthropic\`, or \`Other\`. Do not respond with more than one word.<question>{question}</question>Classification:`);const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229",});const classificationChain = RunnableSequence.from([ promptTemplate, model, new StringOutputParser(),]);const classificationChainResult = await classificationChain.invoke({ question: "how do I call Anthropic?",});console.log(classificationChainResult);/* Anthropic*/const langChainChain = ChatPromptTemplate.fromTemplate( `You are an expert in langchain.Always answer questions starting with "As Harrison Chase told me".Respond to the following question:Question: {question}Answer:`).pipe(model);const anthropicChain = ChatPromptTemplate.fromTemplate( `You are an expert in anthropic. \Always answer questions starting with "As Dario Amodei told me". \Respond to the following question:Question: {question}Answer:`).pipe(model);const generalChain = ChatPromptTemplate.fromTemplate( `Respond to the following question:Question: {question}Answer:`).pipe(model);const branch = RunnableBranch.from([ [ (x: { topic: string; question: string }) => x.topic.toLowerCase().includes("anthropic"), anthropicChain, ], [ (x: { topic: string; question: string }) => x.topic.toLowerCase().includes("langchain"), langChainChain, ], generalChain,]);const fullChain = RunnableSequence.from([ { topic: classificationChain, question: (input: { question: string }) => input.question, }, branch,]);const result1 = await fullChain.invoke({ question: "how do I use Anthropic?",});console.log(result1);/* AIMessage { content: ' As Dario Amodei told me, here are some tips for how to use Anthropic:\n' + '\n' + "First, sign up for an account on Anthropic's website. This will give you access to their conversational AI assistant named Claude. \n" + '\n' + "Once you've created an account, you can have conversations with Claude through their web interface. Talk to Claude like you would talk to a person, asking questions, giving instructions, etc. Claude is trained to have natural conversations and be helpful.\n" + '\n' + "You can also integrate Claude into your own applications using Anthropic's API. This allows you to build Claude's conversational abilities into chatbots, virtual assistants, and other AI systems you develop.\n" + '\n' + 'Anthropic is constantly working on improving Claude, so its capabilities are always expanding. Make sure to check their blog and documentation to stay up to date on the latest features.\n' + '\n' + 'The key is to interact with Claude regularly so it can learn from you. The more you chat with it, the better it will become at understanding you and having personalized conversations. Over time, Claude will feel more human-like as it accumulates more conversational experience.', additional_kwargs: {} }*/const result2 = await fullChain.invoke({ question: "how do I use LangChain?",});console.log(result2);/* AIMessage { content: ' As Harrison Chase told me, here is how you use LangChain:\n' + '\n' + 'First, think carefully about what you want to ask or have the AI do. Frame your request clearly and specifically. Avoid vague or overly broad prompts that could lead to unhelpful or concerning responses. \n' + '\n' + 'Next, type your question or request into the chat window and send it. Be patient as the AI processes your input and generates a response. The AI will do its best to provide a helpful answer or follow your instructions, but its capabilities are limited.\n' + '\n' + 'Keep your requests simple at first. Ask basic questions or have the AI summarize content or generate basic text. As you get more comfortable, you can try having the AI perform more complex tasks like answering tricky questions, generating stories, or having a conversation.\n' + '\n' + "Pay attention to the AI's responses. If they seem off topic, nonsensical, or concerning, rephrase your prompt to steer the AI in a better direction. You may need to provide additional clarification or context to get useful results.\n" + '\n' + 'Be polite and respectful towards the AI system. Remember, it is a tool designed to be helpful, harmless, and honest. Do not try to trick, confuse, or exploit it. \n' + '\n' + 'I hope these tips help you have a safe, fun and productive experience using LangChain! Let me know if you have any other questions.', additional_kwargs: {} }*/const result3 = await fullChain.invoke({ question: "what is 2 + 2?",});console.log(result3);/* AIMessage { content: ' 4', additional_kwargs: {} }*/ #### API Reference: * [ChatPromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts` * [StringOutputParser](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers` * [RunnableBranch](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableBranch.html) from `@langchain/core/runnables` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [ChatAnthropic](https://v02.api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned how to add routing to your composed LCEL chains. Next, check out the other [how-to guides on runnables](/v0.2/docs/how_to/#langchain-expression-language-lcel) in this section. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to reduce retrieval latency ](/v0.2/docs/how_to/reduce_retrieval_latency)[ Next How to do "self-querying" retrieval ](/v0.2/docs/how_to/self_query) * [Using a custom function](#using-a-custom-function) * [Routing by semantic similarity](#routing-by-semantic-similarity) * [Using a RunnableBranch](#using-a-runnablebranch) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/qa_citations
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to return citations On this page How to return citations ======================= Prerequisites This guide assumes familiarity with the following: * [Retrieval-augmented generation](/v0.2/docs/tutorials/rag/) * [Returning structured data from a model](/v0.2/docs/how_to/structured_output/) How can we get a model to cite which parts of the source documents it referenced in its response? To explore some techniques for extracting citations, let’s first create a simple RAG chain. To start we’ll just retrieve from the web using the [`TavilySearchAPIRetriever`](https://api.js.langchain.com/classes/langchain_community_retrievers_tavily_search_api.TavilySearchAPIRetriever.html). Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Dependencies[​](#dependencies "Direct link to Dependencies") We’ll use an OpenAI chat model and embeddings and a Memory vector store in this walkthrough, but everything shown here works with any [ChatModel](/v0.2/docs/concepts/#chat-models) or [LLM](/v0.2/docs/concepts#llms), [Embeddings](/v0.2/docs/concepts#embedding-models/), and [VectorStore](/v0.2/docs/concepts#vectorstores/) or [Retriever](/v0.2/docs/concepts#retrievers). We’ll use the following packages: npm install --save langchain @langchain/community @langchain/openai We need to set environment variables for Tavily Search & OpenAI: export OPENAI_API_KEY=YOUR_KEYexport TAVILY_API_KEY=YOUR_KEY ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com/). Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=YOUR_KEY ### Initial setup[​](#initial-setup "Direct link to Initial setup") import { TavilySearchAPIRetriever } from "@langchain/community/retrievers/tavily_search_api";import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0,});const retriever = new TavilySearchAPIRetriever({ k: 6,});const prompt = ChatPromptTemplate.fromMessages([ [ "system", "You're a helpful AI assistant. Given a user question and some web article snippets, answer the user question. If none of the articles answer the question, just say you don't know.\n\nHere are the web articles:{context}", ], ["human", "{question}"],]); Now that we’ve got a model, retriever and prompt, let’s chain them all together. We’ll need to add some logic for formatting our retrieved `Document`s to a string that can be passed to our prompt. We’ll make it so our chain returns both the answer and the retrieved Documents. import { Document } from "@langchain/core/documents";import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnableMap, RunnablePassthrough } from "@langchain/core/runnables";/** * Format the documents into a readable string. */const formatDocs = (input: Record<string, any>): string => { const { docs } = input; return ( "\n\n" + docs .map( (doc: Document) => `Article title: ${doc.metadata.title}\nArticle Snippet: ${doc.pageContent}` ) .join("\n\n") );};// subchain for generating an answer once we've done retrievalconst answerChain = prompt.pipe(llm).pipe(new StringOutputParser());const map = RunnableMap.from({ question: new RunnablePassthrough(), docs: retriever,});// complete chain that calls the retriever -> formats docs to string -> runs answer subchain -> returns just the answer and retrieved docs.const chain = map .assign({ context: formatDocs }) .assign({ answer: answerChain }) .pick(["answer", "docs"]);await chain.invoke("How fast are cheetahs?"); { answer: "Cheetahs are the fastest land animals on Earth. They can reach speeds as high as 75 mph or 120 km/h."... 124 more characters, docs: [ Document { pageContent: "Contact Us − +\n" + "Address\n" + "Smithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut"... 1343 more characters, metadata: { title: "Cheetah | Smithsonian's National Zoo and Conservation Biology Institute", source: "https://nationalzoo.si.edu/animals/cheetah", score: 0.96283, images: null } }, Document { pageContent: "Now, their only hope lies in the hands of human conservationists, working tirelessly to save the che"... 880 more characters, metadata: { title: "How Fast Are Cheetahs, and Other Fascinating Facts About the World's ...", source: "https://www.discovermagazine.com/planet-earth/how-fast-are-cheetahs-and-other-fascinating-facts-abou"... 21 more characters, score: 0.96052, images: null } }, Document { pageContent: "The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely r"... 1048 more characters, metadata: { title: "Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts", source: "https://www.britannica.com/animal/cheetah-mammal", score: 0.93137, images: null } }, Document { pageContent: "The science of cheetah speed\n" + "The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, cap"... 738 more characters, metadata: { title: "How Fast Can a Cheetah Run? - ThoughtCo", source: "https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031", score: 0.91385, images: null } }, Document { pageContent: "One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the ma"... 60 more characters, metadata: { title: "The Science of a Cheetah's Speed | National Geographic", source: "https://www.youtube.com/watch?v=icFMTB0Pi0g", score: 0.90358, images: null } }, Document { pageContent: "If a lion comes along, the cheetah will abandon its catch -- it can't fight off a lion, and chances "... 911 more characters, metadata: { title: "What makes a cheetah run so fast? | HowStuffWorks", source: "https://animals.howstuffworks.com/mammals/cheetah-speed.htm", score: 0.87824, images: null } } ]} See a LangSmith trace [here](https://smith.langchain.com/public/bb0ed37e-b2be-4ae9-8b0d-ce2aff0b4b5e/r) that shows off the internals. Tool calling[​](#tool-calling "Direct link to Tool calling") ------------------------------------------------------------ ### Cite documents[​](#cite-documents "Direct link to Cite documents") Let’s try using [tool calling](/v0.2/docs/how_to/tool_calling) to make the model specify which of the provided documents it’s actually referencing when answering. LangChain has some utils for converting objects or [Zod](https://zod.dev) objects to the JSONSchema format expected by providers like OpenAI. We’ll use the [`.withStructuredOutput()`](/v0.2/docs/how_to/structured_output/) method to get the model to output data matching our desired schema: import { z } from "zod";const llmWithTool1 = llm.withStructuredOutput( z .object({ answer: z .string() .describe( "The answer to the user question, which is based only on the given sources." ), citations: z .array(z.number()) .describe( "The integer IDs of the SPECIFIC sources which justify the answer." ), }) .describe("A cited source from the given text"), { name: "cited_answers", });const exampleQ = `What is Brian's height?Source: 1Information: Suzy is 6'2"Source: 2Information: Jeremiah is blondeSource: 3Information: Brian is 3 inches shorter than Suzy`;await llmWithTool1.invoke(exampleQ); { answer: `Brian is 6'2" - 3 inches = 5'11" tall.`, citations: [ 1, 3 ]} See a LangSmith trace [here](https://smith.langchain.com/public/28736c75-122e-4deb-9916-55c73eea3167/r) that shows off the internals Now we’re ready to put together our chain import { Document } from "@langchain/core/documents";const formatDocsWithId = (docs: Array<Document>): string => { return ( "\n\n" + docs .map( (doc: Document, idx: number) => `Source ID: ${idx}\nArticle title: ${doc.metadata.title}\nArticle Snippet: ${doc.pageContent}` ) .join("\n\n") );};// subchain for generating an answer once we've done retrievalconst answerChain1 = prompt.pipe(llmWithTool1);const map1 = RunnableMap.from({ question: new RunnablePassthrough(), docs: retriever,});// complete chain that calls the retriever -> formats docs to string -> runs answer subchain -> returns just the answer and retrieved docs.const chain1 = map1 .assign({ context: (input: { docs: Array<Document> }) => formatDocsWithId(input.docs), }) .assign({ cited_answer: answerChain1 }) .pick(["cited_answer", "docs"]);await chain1.invoke("How fast are cheetahs?"); { cited_answer: { answer: "Cheetahs can reach speeds as high as 75 mph or 120 km/h.", citations: [ 1, 2, 5 ] }, docs: [ Document { pageContent: "One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the ma"... 60 more characters, metadata: { title: "The Science of a Cheetah's Speed | National Geographic", source: "https://www.youtube.com/watch?v=icFMTB0Pi0g", score: 0.97858, images: null } }, Document { pageContent: "The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely r"... 1048 more characters, metadata: { title: "Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts", source: "https://www.britannica.com/animal/cheetah-mammal", score: 0.97213, images: null } }, Document { pageContent: "The science of cheetah speed\n" + "The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, cap"... 738 more characters, metadata: { title: "How Fast Can a Cheetah Run? - ThoughtCo", source: "https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031", score: 0.95759, images: null } }, Document { pageContent: "Contact Us − +\n" + "Address\n" + "Smithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut"... 1343 more characters, metadata: { title: "Cheetah | Smithsonian's National Zoo and Conservation Biology Institute", source: "https://nationalzoo.si.edu/animals/cheetah", score: 0.92422, images: null } }, Document { pageContent: "Now, their only hope lies in the hands of human conservationists, working tirelessly to save the che"... 880 more characters, metadata: { title: "How Fast Are Cheetahs, and Other Fascinating Facts About the World's ...", source: "https://www.discovermagazine.com/planet-earth/how-fast-are-cheetahs-and-other-fascinating-facts-abou"... 21 more characters, score: 0.91867, images: null } }, Document { pageContent: "The speeds attained by the cheetah may be only slightly greater than those achieved by the pronghorn"... 2527 more characters, metadata: { title: "Cheetah - Wikipedia", source: "https://en.wikipedia.org/wiki/Cheetah", score: 0.81617, images: null } } ]} See a LangSmith trace [here](https://smith.langchain.com/public/86814255-b9b0-4c4f-9463-e795c9961451/r) that shows off the internals. ### Cite snippets[​](#cite-snippets "Direct link to Cite snippets") What if we want to cite actual text spans? We can try to get our model to return these, too. **Note**: Note that if we break up our documents so that we have many documents with only a sentence or two instead of a few long documents, citing documents becomes roughly equivalent to citing snippets, and may be easier for the model because the model just needs to return an identifier for each snippet instead of the actual text. We recommend trying both approaches and evaluating. import { Document } from "@langchain/core/documents";const citationSchema = z.object({ sourceId: z .number() .describe( "The integer ID of a SPECIFIC source which justifies the answer." ), quote: z .string() .describe( "The VERBATIM quote from the specified source that justifies the answer." ),});const llmWithTool2 = llm.withStructuredOutput( z.object({ answer: z .string() .describe( "The answer to the user question, which is based only on the given sources." ), citations: z .array(citationSchema) .describe("Citations from the given sources that justify the answer."), }), { name: "quoted_answer", });const answerChain2 = prompt.pipe(llmWithTool2);const map2 = RunnableMap.from({ question: new RunnablePassthrough(), docs: retriever,});// complete chain that calls the retriever -> formats docs to string -> runs answer subchain -> returns just the answer and retrieved docs.const chain2 = map2 .assign({ context: (input: { docs: Array<Document> }) => formatDocsWithId(input.docs), }) .assign({ quoted_answer: answerChain2 }) .pick(["quoted_answer", "docs"]);await chain2.invoke("How fast are cheetahs?"); { quoted_answer: { answer: "Cheetahs can reach speeds of up to 120kph or 75mph, making them the world’s fastest land animals.", citations: [ { sourceId: 5, quote: "Cheetahs can reach speeds of up to 120kph or 75mph, making them the world’s fastest land animals." }, { sourceId: 1, quote: "The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as hi"... 25 more characters }, { sourceId: 3, quote: "The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely r"... 72 more characters } ] }, docs: [ Document { pageContent: "Contact Us − +\n" + "Address\n" + "Smithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut"... 1343 more characters, metadata: { title: "Cheetah | Smithsonian's National Zoo and Conservation Biology Institute", source: "https://nationalzoo.si.edu/animals/cheetah", score: 0.95973, images: null } }, Document { pageContent: "The science of cheetah speed\n" + "The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, cap"... 738 more characters, metadata: { title: "How Fast Can a Cheetah Run? - ThoughtCo", source: "https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031", score: 0.92749, images: null } }, Document { pageContent: "Now, their only hope lies in the hands of human conservationists, working tirelessly to save the che"... 880 more characters, metadata: { title: "How Fast Are Cheetahs, and Other Fascinating Facts About the World's ...", source: "https://www.discovermagazine.com/planet-earth/how-fast-are-cheetahs-and-other-fascinating-facts-abou"... 21 more characters, score: 0.92417, images: null } }, Document { pageContent: "The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely r"... 1048 more characters, metadata: { title: "Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts", source: "https://www.britannica.com/animal/cheetah-mammal", score: 0.92341, images: null } }, Document { pageContent: "One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the ma"... 60 more characters, metadata: { title: "The Science of a Cheetah's Speed | National Geographic", source: "https://www.youtube.com/watch?v=icFMTB0Pi0g", score: 0.90025, images: null } }, Document { pageContent: "In fact, they are more closely related to kangaroos…\n" + "Read more\n" + "Animals on the Galapagos Islands: A G"... 987 more characters, metadata: { title: "How fast can cheetahs run, and what enables their incredible speed?", source: "https://wildlifefaq.com/cheetah-speed/", score: 0.87121, images: null } } ]} You can check out a LangSmith trace [here](https://smith.langchain.com/public/f0588adc-1914-45e8-a2ed-4fa028cea0e1/r) that shows off the internals. Direct prompting[​](#direct-prompting "Direct link to Direct prompting") ------------------------------------------------------------------------ Not all models support tool-calling. We can achieve similar results with direct prompting. Let’s see what this looks like using an older Anthropic chat model that is particularly proficient in working with XML: ### Setup[​](#setup-1 "Direct link to Setup") Install the LangChain Anthropic integration package: npm install @langchain/anthropic Add your Anthropic API key to your environment: export ANTHROPIC_API_KEY=YOUR_KEY import { ChatAnthropic } from "@langchain/anthropic";import { ChatPromptTemplate } from "@langchain/core/prompts";import { XMLOutputParser } from "@langchain/core/output_parsers";import { Document } from "@langchain/core/documents";import { RunnableLambda, RunnablePassthrough, RunnableMap,} from "@langchain/core/runnables";const anthropic = new ChatAnthropic({ model: "claude-instant-1.2", temperature: 0,});const system = `You're a helpful AI assistant. Given a user question and some web article snippets,answer the user question and provide citations. If none of the articles answer the question, just say you don't know.Remember, you must return both an answer and citations. A citation consists of a VERBATIM quote thatjustifies the answer and the ID of the quote article. Return a citation for every quote across all articlesthat justify the answer. Use the following format for your final output:<cited_answer> <answer></answer> <citations> <citation><source_id></source_id><quote></quote></citation> <citation><source_id></source_id><quote></quote></citation> ... </citations></cited_answer>Here are the web articles:{context}`;const anthropicPrompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{question}"],]);const formatDocsToXML = (docs: Array<Document>): string => { const formatted: Array<string> = []; docs.forEach((doc, idx) => { const docStr = `<source id="${idx}"> <title>${doc.metadata.title}</title> <article_snippet>${doc.pageContent}</article_snippet></source>`; formatted.push(docStr); }); return `\n\n<sources>${formatted.join("\n")}</sources>`;};const format3 = new RunnableLambda({ func: (input: { docs: Array<Document> }) => formatDocsToXML(input.docs),});const answerChain = anthropicPrompt .pipe(anthropic) .pipe(new XMLOutputParser()) .pipe( new RunnableLambda({ func: (input: { cited_answer: any }) => input.cited_answer, }) );const map3 = RunnableMap.from({ question: new RunnablePassthrough(), docs: retriever,});const chain3 = map3 .assign({ context: format3 }) .assign({ cited_answer: answerChain }) .pick(["cited_answer", "docs"]);const res = await chain3.invoke("How fast are cheetahs?");console.log(JSON.stringify(res, null, 2)); { "cited_answer": [ { "answer": "Cheetahs can reach top speeds of around 75 mph, but can only maintain bursts of speed for short distances before tiring." }, { "citations": [ { "citation": [ { "source_id": "1" }, { "quote": "Scientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower." } ] }, { "citation": [ { "source_id": "3" }, { "quote": "The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely reach velocities of 80–100 km (50–62 miles) per hour while pursuing prey." } ] } ] } ], "docs": [ { "pageContent": "One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the magazine's November 2012 iPad edition. See the other: http:...", "metadata": { "title": "The Science of a Cheetah's Speed | National Geographic", "source": "https://www.youtube.com/watch?v=icFMTB0Pi0g", "score": 0.96603, "images": null } }, { "pageContent": "The science of cheetah speed\nThe cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as high as 75 mph or 120 km/h. Cheetahs are predators that sneak up on their prey and sprint a short distance to chase and attack.\n Key Takeaways: How Fast Can a Cheetah Run?\nFastest Cheetah on Earth\nScientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower. The top 10 fastest animals are:\nThe pronghorn, an American animal resembling an antelope, is the fastest land animal in the Western Hemisphere. While a cheetah's top speed ranges from 65 to 75 mph (104 to 120 km/h), its average speed is only 40 mph (64 km/hr), punctuated by short bursts at its top speed. Basically, if a predator threatens to take a cheetah's kill or attack its young, a cheetah has to run.\n", "metadata": { "title": "How Fast Can a Cheetah Run? - ThoughtCo", "source": "https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031", "score": 0.96212, "images": null } }, { "pageContent": "Now, their only hope lies in the hands of human conservationists, working tirelessly to save the cheetahs, the leopards and all the other wildlife of the scattered savannas and other habitats of Africa and Asia.\n Their tough paw pads and grippy claws are made to grab at the ground, and their large nasal passages and lungs facilitate the flow of oxygen and allow their rapid intake of air as they reach their top speeds.\n And though the two cats share a similar coloration, a cheetah's spots are circular while a leopard's spots are rose-shaped \"rosettes,\" with the centers of their spots showing off the tan color of their coats.\n Also classified as \"vulnerable\" are two of the cheetah's foremost foes, the lion and the leopard, the latter of which is commonly confused for the cheetah thanks to its own flecked fur.\n The cats are also consumers of the smallest of the bigger, bulkier antelopes, such as sables and kudus, and are known to gnaw on the occasional rabbit or bird.\n", "metadata": { "title": "How Fast Are Cheetahs, and Other Fascinating Facts About the World's ...", "source": "https://www.discovermagazine.com/planet-earth/how-fast-are-cheetahs-and-other-fascinating-facts-about-the-worlds-quickest", "score": 0.95688, "images": null } }, { "pageContent": "The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely reach velocities of 80–100 km (50–62 miles) per hour while pursuing prey.\ncheetah,\n(Acinonyx jubatus),\none of the world’s most-recognizable cats, known especially for its speed. Their fur is dark and includes a thick yellowish gray mane along the back, a trait that presumably offers better camouflage and increased protection from high temperatures during the day and low temperatures at night during the first few months of life. Cheetahs eat a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan).\n A cheetah eats a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan). Their faces are distinguished by prominent black lines that curve from the inner corner of each eye to the outer corners of the mouth, like a well-worn trail of inky tears.", "metadata": { "title": "Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts", "source": "https://www.britannica.com/animal/cheetah-mammal", "score": 0.95589, "images": null } }, { "pageContent": "Contact Us − +\nAddress\nSmithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut Ave., NW  Washington, DC 20008\nAbout the Zoo\n−\n+\nCareers\n−\n+\nNews & Media\n−\n+\nFooter Donate\n−\n+\nShop\n−\n+\nFollow us on social media\nSign Up for Emails\nFooter - SI logo, privacy, terms Conservation Efforts\nHistorically, cheetahs ranged widely throughout Africa and Asia, from the Cape of Good Hope to the Mediterranean, throughout the Arabian Peninsula and the Middle East, from Israel, India and Pakistan north to the northern shores of the Caspian and Aral Seas, and west through Uzbekistan, Turkmenistan, Afghanistan, and Pakistan into central India. Header Links\nToday's hours: 8 a.m. to 4 p.m. (last entry 3 p.m.)\nMega menu\nAnimals Global Nav Links\nElephant Cam\nSee the Smithsonian's National Zoo's Asian elephants — Spike, Bozie, Kamala, Swarna and Maharani — both inside the Elephant Community Center and outside in their yards.\n Conservation Global Nav Links\nAbout the Smithsonian Conservation Biology Institute\nCheetah\nAcinonyx jubatus\nBuilt for speed, the cheetah can accelerate from zero to 45 in just 2.5 seconds and reach top speeds of 60 to 70 mph, making it the fastest land mammal! Fun Facts\nConservation Status\nCheetah News\nTaxonomic Information\nAnimal News\nNZCBI staff in Front Royal, Virginia, are mourning the loss of Walnut, a white-naped crane who became an internet sensation for choosing one of her keepers as her mate.\n", "metadata": { "title": "Cheetah | Smithsonian's National Zoo and Conservation Biology Institute", "source": "https://nationalzoo.si.edu/animals/cheetah", "score": 0.94744, "images": null } }, { "pageContent": "The speeds attained by the cheetah may be only slightly greater than those achieved by the pronghorn at 88.5 km/h (55.0 mph)[96] and the springbok at 88 km/h (55 mph),[97] but the cheetah additionally has an exceptional acceleration.[98]\nOne stride of a galloping cheetah measures 4 to 7 m (13 to 23 ft); the stride length and the number of jumps increases with speed.[60] During more than half the duration of the sprint, the cheetah has all four limbs in the air, increasing the stride length.[99] Running cheetahs can retain up to 90% of the heat generated during the chase. In December 2016 the results of an extensive survey detailing the distribution and demography of cheetahs throughout the range were published; the researchers recommended listing the cheetah as Endangered on the IUCN Red List.[25]\nThe cheetah was reintroduced in Malawi in 2017.[160]\nIn Asia\nIn 2001, the Iranian government collaborated with the CCF, the IUCN, Panthera Corporation, UNDP and the Wildlife Conservation Society on the Conservation of Asiatic Cheetah Project (CACP) to protect the natural habitat of the Asiatic cheetah and its prey.[161][162] Individuals on the periphery of the prey herd are common targets; vigilant prey which would react quickly on seeing the cheetah are not preferred.[47][60][122]\nCheetahs are one of the most iconic pursuit predators, hunting primarily throughout the day, sometimes with peaks at dawn and dusk; they tend to avoid larger predators like the primarily nocturnal lion.[66] Cheetahs in the Sahara and Maasai Mara in Kenya hunt after sunset to escape the high temperatures of the day.[123] Cheetahs use their vision to hunt instead of their sense of smell; they keep a lookout for prey from resting sites or low branches. This significantly sharpens the vision and enables the cheetah to swiftly locate prey against the horizon.[61][86] The cheetah is unable to roar due to the presence of a sharp-edged vocal fold within the larynx.[2][87]\nSpeed and acceleration\nThe cheetah is the world's fastest land animal.[88][89][90][91][92] Estimates of the maximum speed attained range from 80 to 128 km/h (50 to 80 mph).[60][63] A commonly quoted value is 112 km/h (70 mph), recorded in 1957, but this measurement is disputed.[93] The mouth can not be opened as widely as in other cats given the shorter length of muscles between the jaw and the skull.[60][65] A study suggested that the limited retraction of the cheetah's claws may result from the earlier truncation of the development of the middle phalanx bone in cheetahs.[77]\nThe cheetah has a total of 30 teeth; the dental formula is 3.1.3.13.1.2.1.", "metadata": { "title": "Cheetah - Wikipedia", "source": "https://en.wikipedia.org/wiki/Cheetah", "score": 0.81312, "images": null } } ]} Check out this LangSmith trace [here](https://smith.langchain.com/public/e2e938e8-f847-4ea8-bc84-43d4eaf8e524/r) for more on the internals. Retrieval post-processing[​](#retrieval-post-processing "Direct link to Retrieval post-processing") --------------------------------------------------------------------------------------------------- Another approach is to post-process our retrieved documents to compress the content, so that the source content is already minimal enough that we don’t need the model to cite specific sources or spans. For example, we could break up each document into a sentence or two, embed those and keep only the most relevant ones. LangChain has some built-in components for this. Here we’ll use a [`RecursiveCharacterTextSplitter`](https://js.langchain.com/v0.2/docs/how_to/recursive_text_splitter), which creates chunks of a specified size by splitting on separator substrings, and an [`EmbeddingsFilter`](https://js.langchain.com/v0.2/docs/how_to/contextual_compression), which keeps only the texts with the most relevant embeddings. import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { EmbeddingsFilter } from "langchain/retrievers/document_compressors/embeddings_filter";import { OpenAIEmbeddings } from "@langchain/openai";import { DocumentInterface } from "@langchain/core/documents";import { RunnableMap, RunnablePassthrough } from "@langchain/core/runnables";const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 400, chunkOverlap: 0, separators: ["\n\n", "\n", ".", " "], keepSeparator: false,});const compressor = new EmbeddingsFilter({ embeddings: new OpenAIEmbeddings(), k: 10,});const splitAndFilter = async (input): Promise<Array<DocumentInterface>> => { const { docs, question } = input; const splitDocs = await splitter.splitDocuments(docs); const statefulDocs = await compressor.compressDocuments(splitDocs, question); return statefulDocs;};const retrieveMap = RunnableMap.from({ question: new RunnablePassthrough(), docs: retriever,});const retriever = retrieveMap.pipe(splitAndFilter);const docs = await retriever.invoke("How fast are cheetahs?");for (const doc of docs) { console.log(doc.pageContent, "\n\n");} The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely reach velocities of 80–100 km (50–62 miles) per hour while pursuing prey.cheetah,(Acinonyx jubatus),The science of cheetah speedThe cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as high as 75 mph or 120 km/h. Cheetahs are predators that sneak up on their prey and sprint a short distance to chase and attack. Key Takeaways: How Fast Can a Cheetah Run?Fastest Cheetah on EarthBuilt for speed, the cheetah can accelerate from zero to 45 in just 2.5 seconds and reach top speeds of 60 to 70 mph, making it the fastest land mammal! Fun FactsConservation StatusCheetah NewsTaxonomic InformationAnimal NewsNZCBI staff in Front Royal, Virginia, are mourning the loss of Walnut, a white-naped crane who became an internet sensation for choosing one of her keepers as her mate.The speeds attained by the cheetah may be only slightly greater than those achieved by the pronghorn at 88.5 km/h (55.0 mph)[96] and the springbok at 88 km/h (55 mph),[97] but the cheetah additionally has an exceptional acceleration.[98]The cheetah is the world's fastest land animal.[88][89][90][91][92] Estimates of the maximum speed attained range from 80 to 128 km/h (50 to 80 mph).[60][63] A commonly quoted value is 112 km/h (70 mph), recorded in 1957, but this measurement is disputed.[93] The mouth can not be opened as widely as in other cats given the shorter length of muscles between the jaw and the skullScientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower. The top 10 fastest animals are:One stride of a galloping cheetah measures 4 to 7 m (13 to 23 ft); the stride length and the number of jumps increases with speed.[60] During more than half the duration of the sprint, the cheetah has all four limbs in the air, increasing the stride length.[99] Running cheetahs can retain up to 90% of the heat generated during the chaseThe pronghorn, an American animal resembling an antelope, is the fastest land animal in the Western Hemisphere. While a cheetah's top speed ranges from 65 to 75 mph (104 to 120 km/h), its average speed is only 40 mph (64 km/hr), punctuated by short bursts at its top speed. Basically, if a predator threatens to take a cheetah's kill or attack its young, a cheetah has to run.A cheetah eats a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan). Their faces are distinguished by prominent black lines that curve from the inner corner of each eye to the outer corners of the mouth, like a well-worn trail of inky tears.Cheetahs are one of the most iconic pursuit predators, hunting primarily throughout the day, sometimes with peaks at dawn and dusk; they tend to avoid larger predators like the primarily nocturnal lion.[66] Cheetahs in the Sahara and Maasai Mara in Kenya hunt after sunset to escape the high temperatures of the day See the LangSmith trace [here](https://smith.langchain.com/public/ae6b1f52-c1fe-49ec-843c-92edf2104652/r) to see the internals. const chain4 = retrieveMap .assign({ context: formatDocs }) .assign({ answer: answerChain }) .pick(["answer", "docs"]);// Note the documents have an article "summary" in the metadata that is now much longer than the// actual document page content. This summary isn't actually passed to the model.const res = await chain4.invoke("How fast are cheetahs?");console.log(JSON.stringify(res, null, 2)); { "answer": [ { "answer": "\nCheetahs are the fastest land animals. They can reach top speeds between 75-81 mph (120-130 km/h). \n" }, { "citations": [ { "citation": [ { "source_id": "Article title: How Fast Can a Cheetah Run? - ThoughtCo" }, { "quote": "The science of cheetah speed\nThe cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as high as 75 mph or 120 km/h." } ] }, { "citation": [ { "source_id": "Article title: Cheetah - Wikipedia" }, { "quote": "Scientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower." } ] } ] } ], "docs": [ { "pageContent": "The science of cheetah speed\nThe cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as high as 75 mph or 120 km/h. Cheetahs are predators that sneak up on their prey and sprint a short distance to chase and attack.\n Key Takeaways: How Fast Can a Cheetah Run?\nFastest Cheetah on Earth\nScientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower. The top 10 fastest animals are:\nThe pronghorn, an American animal resembling an antelope, is the fastest land animal in the Western Hemisphere. While a cheetah's top speed ranges from 65 to 75 mph (104 to 120 km/h), its average speed is only 40 mph (64 km/hr), punctuated by short bursts at its top speed. Basically, if a predator threatens to take a cheetah's kill or attack its young, a cheetah has to run.\n", "metadata": { "title": "How Fast Can a Cheetah Run? - ThoughtCo", "source": "https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031", "score": 0.96949, "images": null } }, { "pageContent": "The speeds attained by the cheetah may be only slightly greater than those achieved by the pronghorn at 88.5 km/h (55.0 mph)[96] and the springbok at 88 km/h (55 mph),[97] but the cheetah additionally has an exceptional acceleration.[98]\nOne stride of a galloping cheetah measures 4 to 7 m (13 to 23 ft); the stride length and the number of jumps increases with speed.[60] During more than half the duration of the sprint, the cheetah has all four limbs in the air, increasing the stride length.[99] Running cheetahs can retain up to 90% of the heat generated during the chase. In December 2016 the results of an extensive survey detailing the distribution and demography of cheetahs throughout the range were published; the researchers recommended listing the cheetah as Endangered on the IUCN Red List.[25]\nThe cheetah was reintroduced in Malawi in 2017.[160]\nIn Asia\nIn 2001, the Iranian government collaborated with the CCF, the IUCN, Panthera Corporation, UNDP and the Wildlife Conservation Society on the Conservation of Asiatic Cheetah Project (CACP) to protect the natural habitat of the Asiatic cheetah and its prey.[161][162] Individuals on the periphery of the prey herd are common targets; vigilant prey which would react quickly on seeing the cheetah are not preferred.[47][60][122]\nCheetahs are one of the most iconic pursuit predators, hunting primarily throughout the day, sometimes with peaks at dawn and dusk; they tend to avoid larger predators like the primarily nocturnal lion.[66] Cheetahs in the Sahara and Maasai Mara in Kenya hunt after sunset to escape the high temperatures of the day.[123] Cheetahs use their vision to hunt instead of their sense of smell; they keep a lookout for prey from resting sites or low branches. This significantly sharpens the vision and enables the cheetah to swiftly locate prey against the horizon.[61][86] The cheetah is unable to roar due to the presence of a sharp-edged vocal fold within the larynx.[2][87]\nSpeed and acceleration\nThe cheetah is the world's fastest land animal.[88][89][90][91][92] Estimates of the maximum speed attained range from 80 to 128 km/h (50 to 80 mph).[60][63] A commonly quoted value is 112 km/h (70 mph), recorded in 1957, but this measurement is disputed.[93] The mouth can not be opened as widely as in other cats given the shorter length of muscles between the jaw and the skull.[60][65] A study suggested that the limited retraction of the cheetah's claws may result from the earlier truncation of the development of the middle phalanx bone in cheetahs.[77]\nThe cheetah has a total of 30 teeth; the dental formula is 3.1.3.13.1.2.1.", "metadata": { "title": "Cheetah - Wikipedia", "source": "https://en.wikipedia.org/wiki/Cheetah", "score": 0.96423, "images": null } }, { "pageContent": "One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the magazine's November 2012 iPad edition. See the other: http:...", "metadata": { "title": "The Science of a Cheetah's Speed | National Geographic", "source": "https://www.youtube.com/watch?v=icFMTB0Pi0g", "score": 0.96071, "images": null } }, { "pageContent": "Contact Us − +\nAddress\nSmithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut Ave., NW  Washington, DC 20008\nAbout the Zoo\n−\n+\nCareers\n−\n+\nNews & Media\n−\n+\nFooter Donate\n−\n+\nShop\n−\n+\nFollow us on social media\nSign Up for Emails\nFooter - SI logo, privacy, terms Conservation Efforts\nHistorically, cheetahs ranged widely throughout Africa and Asia, from the Cape of Good Hope to the Mediterranean, throughout the Arabian Peninsula and the Middle East, from Israel, India and Pakistan north to the northern shores of the Caspian and Aral Seas, and west through Uzbekistan, Turkmenistan, Afghanistan, and Pakistan into central India. Header Links\nToday's hours: 8 a.m. to 4 p.m. (last entry 3 p.m.)\nMega menu\nAnimals Global Nav Links\nElephant Cam\nSee the Smithsonian's National Zoo's Asian elephants — Spike, Bozie, Kamala, Swarna and Maharani — both inside the Elephant Community Center and outside in their yards.\n Conservation Global Nav Links\nAbout the Smithsonian Conservation Biology Institute\nCheetah\nAcinonyx jubatus\nBuilt for speed, the cheetah can accelerate from zero to 45 in just 2.5 seconds and reach top speeds of 60 to 70 mph, making it the fastest land mammal! Fun Facts\nConservation Status\nCheetah News\nTaxonomic Information\nAnimal News\nNZCBI staff in Front Royal, Virginia, are mourning the loss of Walnut, a white-naped crane who became an internet sensation for choosing one of her keepers as her mate.\n", "metadata": { "title": "Cheetah | Smithsonian's National Zoo and Conservation Biology Institute", "source": "https://nationalzoo.si.edu/animals/cheetah", "score": 0.91577, "images": null } }, { "pageContent": "The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely reach velocities of 80–100 km (50–62 miles) per hour while pursuing prey.\ncheetah,\n(Acinonyx jubatus),\none of the world’s most-recognizable cats, known especially for its speed. Their fur is dark and includes a thick yellowish gray mane along the back, a trait that presumably offers better camouflage and increased protection from high temperatures during the day and low temperatures at night during the first few months of life. Cheetahs eat a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan).\n A cheetah eats a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan). Their faces are distinguished by prominent black lines that curve from the inner corner of each eye to the outer corners of the mouth, like a well-worn trail of inky tears.", "metadata": { "title": "Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts", "source": "https://www.britannica.com/animal/cheetah-mammal", "score": 0.91163, "images": null } }, { "pageContent": "If a lion comes along, the cheetah will abandon its catch -- it can't fight off a lion, and chances are, the cheetah will lose its life along with its prey if it doesn't get out of there fast enough.\n Advertisement\nLots More Information\nMore Great Links\nSources\nPlease copy/paste the following text to properly cite this HowStuffWorks.com article:\nAdvertisement\nAdvertisement\nAdvertisement\nAdvertisement\nAdvertisement If confronted, a roughly 125-pound cheetah will always run rather than fight -- it's too weak, light and thin to have any chance against something like a lion, which can be twice as long as a cheetah and weigh more than 400 pounds (181.4 kg) Cheetah moms spend a lot of time teaching their cubs to chase, sometimes dragging live animals back to the den so the cubs can practice the chase-and-catch process.\n It's more like a bound at that speed, completing up to three strides per second, with only one foot on the ground at any time and several stages when feet don't touch the ground at all.", "metadata": { "title": "What makes a cheetah run so fast? | HowStuffWorks", "source": "https://animals.howstuffworks.com/mammals/cheetah-speed.htm", "score": 0.89019, "images": null } } ]} Check out the LangSmith trace [here](https://smith.langchain.com/public/b767cca0-6061-4208-99f2-7f522b94a587/r) to see the internals. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned a few ways to return citations from your QA chains. Next, check out some of the other guides in this section, such as [how to add chat history](/v0.2/docs/how_to/qa_chat_history_how_to). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to add chat history to a question-answering chain ](/v0.2/docs/how_to/qa_chat_history_how_to)[ Next How to return sources ](/v0.2/docs/how_to/qa_sources) * [Setup](#setup) * [Dependencies](#dependencies) * [LangSmith](#langsmith) * [Initial setup](#initial-setup) * [Tool calling](#tool-calling) * [Cite documents](#cite-documents) * [Cite snippets](#cite-snippets) * [Direct prompting](#direct-prompting) * [Setup](#setup-1) * [Retrieval post-processing](#retrieval-post-processing) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/local_rag
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build a Local RAG Application On this page Build a Local RAG Application ============================= The popularity of projects like [PrivateGPT](https://github.com/imartinez/privateGPT), [llama.cpp](https://github.com/ggerganov/llama.cpp), [GPT4All](https://github.com/nomic-ai/gpt4all), and [llamafile](https://github.com/Mozilla-Ocho/llamafile) underscore the importance of running LLMs locally. LangChain has integrations with many open-source LLMs that can be run locally. For example, here we show how to run `OllamaEmbeddings` or `LLaMA2` locally (e.g., on your laptop) using local embeddings and a local LLM. Document Loading[​](#document-loading "Direct link to Document Loading") ------------------------------------------------------------------------ First, install packages needed for local embeddings and vector storage. Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Dependencies[​](#dependencies "Direct link to Dependencies") We’ll use the following packages: npm install --save langchain @langchain/community cheerio ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com/). Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=YOUR_KEY ### Initial setup[​](#initial-setup "Direct link to Initial setup") Load and split an example document. We’ll use a blog post on agents as an example. import "cheerio";import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio"; const loader = new CheerioWebBaseLoader( "https://lilianweng.github.io/posts/2023-06-23-agent/");const docs = await loader.load();const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 500, chunkOverlap: 0,});const allSplits = await textSplitter.splitDocuments(docs);console.log(allSplits.length); 146 Next, we’ll use `OllamaEmbeddings` for our local embeddings. Follow [these instructions](https://github.com/ollama/ollama) to set up and run a local Ollama instance. import { OllamaEmbeddings } from "@langchain/community/embeddings/ollama";import { MemoryVectorStore } from "langchain/vectorstores/memory";const embeddings = new OllamaEmbeddings();const vectorStore = await MemoryVectorStore.fromDocuments( allSplits, embeddings); Test similarity search is working with our local embeddings. const question = "What are the approaches to Task Decomposition?";const docs = await vectorStore.similaritySearch(question);console.log(docs.length); 4 Model[​](#model "Direct link to Model") --------------------------------------- ### LLaMA2[​](#llama2 "Direct link to LLaMA2") For local LLMs we’ll use also use `ollama`. import { ChatOllama } from "@langchain/community/chat_models/ollama";const ollamaLlm = new ChatOllama({ baseUrl: "http://localhost:11434", // Default value model: "llama2", // Default value}); const response = await ollamaLlm.invoke( "Simulate a rap battle between Stephen Colbert and John Oliver");console.log(response.content); [The stage is set for a fierce rap battle between two of the funniest men on television. Stephen Colbert and John Oliver are standing face to face, each with their own microphone and confident smirk on their face.]Stephen Colbert:Yo, John Oliver, I heard you've been talking smackAbout my show and my satire, saying it's all fakeBut let me tell you something, brother, I'm the real dealI've been making fun of politicians for years, with no concealJohn Oliver:Oh, Stephen, you think you're so clever and smartBut your jokes are stale and your delivery's a work of artYou're just a pale imitation of the real deal, Jon StewartI'm the one who's really making waves, while you're just a little birdStephen Colbert:Well, John, I may not be as loud as you, but I'm smarterMy satire is more subtle, and it goes right over their headsI'm the one who's been exposing the truth for yearsWhile you're just a British interloper, trying to steal the cheersJohn Oliver:Oh, Stephen, you may have your fans, but I've got the brainsMy show is more than just slapstick and silly jokes, it's got depth and gainsI'm the one who's really making a difference, while you're just a clownMy satire is more than just a joke, it's a call to action, and I've got the crown[The crowd cheers and chants as the two comedians continue their rap battle.]Stephen Colbert:You may have your fans, John, but I'm the king of satireI've been making fun of politicians for years, and I'm still standing tallMy jokes are clever and smart, while yours are just plain dumbI'm the one who's really in control, and you're just a pretender to the throne.John Oliver:Oh, Stephen, you may have your moment in the sunBut I'm the one who's really shining bright, and my star is just beginning to riseMy satire is more than just a joke, it's a call to action, and I've got the powerI'm the one who's really making a difference, and you're just a fleeting flower.[The crowd continues to cheer and chant as the two comedians continue their rap battle.] See the LangSmith trace [here](https://smith.langchain.com/public/31c178b5-4bea-4105-88c3-7ec95325c817/r) Using in a chain[​](#using-in-a-chain "Direct link to Using in a chain") ------------------------------------------------------------------------ We can create a summarization chain with either model by passing in the retrieved docs and a simple prompt. It formats the prompt template using the input key values provided and passes the formatted string to `LLama-V2`, or another specified LLM. import { RunnableSequence } from "@langchain/core/runnables";import { StringOutputParser } from "@langchain/core/output_parsers";import { PromptTemplate } from "@langchain/core/prompts";import { createStuffDocumentsChain } from "langchain/chains/combine_documents";const prompt = PromptTemplate.fromTemplate( "Summarize the main themes in these retrieved docs: {context}");const chain = await createStuffDocumentsChain({ llm: ollamaLlm, outputParser: new StringOutputParser(), prompt,}); const question = "What are the approaches to Task Decomposition?";const docs = await vectorStore.similaritySearch(question);await chain.invoke({ context: docs,}); "The main themes retrieved from the provided documents are:\n" + "\n" + "1. Sensory Memory: The ability to retain"... 1117 more characters See the LangSmith trace [here](https://smith.langchain.com/public/47cf6c2a-3d86-4f2b-9a51-ee4663b19152/r) Q&A[​](#qa "Direct link to Q&A") -------------------------------- We can also use the LangChain Prompt Hub to store and fetch prompts that are model-specific. Let’s try with a default RAG prompt, [here](https://smith.langchain.com/hub/rlm/rag-prompt). import { pull } from "langchain/hub";import { ChatPromptTemplate } from "@langchain/core/prompts";const ragPrompt = await pull<ChatPromptTemplate>("rlm/rag-prompt");const chain = await createStuffDocumentsChain({ llm: ollamaLlm, outputParser: new StringOutputParser(), prompt: ragPrompt,}); Let’s see what this prompt actually looks like: console.log( ragPrompt.promptMessages.map((msg) => msg.prompt.template).join("\n")); You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.Question: {question}Context: {context}Answer: await chain.invoke({ context: docs, question }); "Task decomposition is a crucial step in breaking down complex problems into manageable parts for eff"... 1095 more characters See the LangSmith trace [here](https://smith.langchain.com/public/dd3a189b-53a1-4f31-9766-244cd04ad1f7/r) Q&A with retrieval[​](#qa-with-retrieval "Direct link to Q&A with retrieval") ----------------------------------------------------------------------------- Instead of manually passing in docs, we can automatically retrieve them from our vector store based on the user question. This will use a QA default prompt and will retrieve from the vectorDB. import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { formatDocumentsAsString } from "langchain/util/document";const retriever = vectorStore.asRetriever();const qaChain = RunnableSequence.from([ { context: (input: { question: string }, callbacks) => { const retrieverAndFormatter = retriever.pipe(formatDocumentsAsString); return retrieverAndFormatter.invoke(input.question, callbacks); }, question: new RunnablePassthrough(), }, ragPrompt, ollamaLlm, new StringOutputParser(),]);await qaChain.invoke({ question }); "Based on the context provided, I understand that you are asking me to answer a question related to m"... 948 more characters See the LangSmith trace [here](https://smith.langchain.com/public/440e65ee-0301-42cf-afc9-f09cfb52cf64/r) * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Tagging ](/v0.2/docs/tutorials/classification)[ Next Build a PDF ingestion and Question/Answering system ](/v0.2/docs/tutorials/pdf_qa) * [Document Loading](#document-loading) * [Setup](#setup) * [Dependencies](#dependencies) * [LangSmith](#langsmith) * [Initial setup](#initial-setup) * [Model](#model) * [LLaMA2](#llama2) * [Using in a chain](#using-in-a-chain) * [Q&A](#qa) * [Q&A with retrieval](#qa-with-retrieval)
null
https://js.langchain.com/v0.2/docs/how_to/self_query
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to do "self-querying" retrieval On this page How to do "self-querying" retrieval =================================== Prerequisites This guide assumes familiarity with the following concepts: * [Retrievers](/v0.2/docs/concepts#retrievers) * [Vector stores](/v0.2/docs/concepts#vectorstores) A self-querying retriever is one that, as the name suggests, has the ability to query itself. Specifically, given any natural language query, the retriever uses an LLM to write a structured query and then applies that structured query to its underlying vector store. This allows the retriever to not only use the user-input query for semantic similarity comparison with the contents of stored documents but to also extract filters from the user query on the metadata of stored documents and to execute those filters. ![](/v0.2/assets/images/self_querying-9250153d059cdb0585bc60dd8dd07909.jpeg) Head to [Integrations](/v0.2/docs/integrations/retrievers/self_query) for documentation on vector stores with built-in support for self-querying. Get started[​](#get-started "Direct link to Get started") --------------------------------------------------------- For demonstration purposes, we’ll use an in-memory, unoptimized vector store. You should swap it out for a supported production-ready vector store when seriously building. The self-query retriever requires you to have the [`peggy`](https://www.npmjs.com/package/peggy) package installed as a peer dep, and we’ll also use OpenAI for this example: * npm * yarn * pnpm npm i peggy @langchain/openai yarn add peggy @langchain/openai pnpm add peggy @langchain/openai We’ve created a small demo set of documents that contain summaries of movies: import "peggy";import { Document } from "@langchain/core/documents";/** * First, we create a bunch of documents. You can load your own documents here instead. * Each document has a pageContent and a metadata field. Make sure your metadata matches the AttributeInfo below. */const docs = [ new Document({ pageContent: "A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata: { year: 1993, rating: 7.7, genre: "science fiction", length: 122, }, }), new Document({ pageContent: "Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata: { year: 2010, director: "Christopher Nolan", rating: 8.2, length: 148, }, }), new Document({ pageContent: "A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata: { year: 2006, director: "Satoshi Kon", rating: 8.6 }, }), new Document({ pageContent: "A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata: { year: 2019, director: "Greta Gerwig", rating: 8.3, length: 135, }, }), new Document({ pageContent: "Toys come alive and have a blast doing so", metadata: { year: 1995, genre: "animated", length: 77 }, }), new Document({ pageContent: "Three men walk into the Zone, three men walk out of the Zone", metadata: { year: 1979, director: "Andrei Tarkovsky", genre: "science fiction", rating: 9.9, }, }),]; ### Creating our self-querying retriever[​](#creating-our-self-querying-retriever "Direct link to Creating our self-querying retriever") Now we can instantiate our retriever. To do this we’ll need to provide some information upfront about the metadata fields that our documents support and a short description of the document contents. import { OpenAIEmbeddings, OpenAI } from "@langchain/openai";import { FunctionalTranslator } from "@langchain/core/structured_query";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { SelfQueryRetriever } from "langchain/retrievers/self_query";import type { AttributeInfo } from "langchain/chains/query_constructor";/** * We define the attributes we want to be able to query on. * in this case, we want to be able to query on the genre, year, director, rating, and length of the movie. * We also provide a description of each attribute and the type of the attribute. * This is used to generate the query prompts. */const attributeInfo: AttributeInfo[] = [ { name: "genre", description: "The genre of the movie", type: "string or array of strings", }, { name: "year", description: "The year the movie was released", type: "number", }, { name: "director", description: "The director of the movie", type: "string", }, { name: "rating", description: "The rating of the movie (1-10)", type: "number", }, { name: "length", description: "The length of the movie in minutes", type: "number", },];/** * Next, we instantiate a vector store. This is where we store the embeddings of the documents. * We also need to provide an embeddings object. This is used to embed the documents. */const embeddings = new OpenAIEmbeddings();const llm = new OpenAI();const documentContents = "Brief summary of a movie";const vectorStore = await MemoryVectorStore.fromDocuments(docs, embeddings);const selfQueryRetriever = SelfQueryRetriever.fromLLM({ llm, vectorStore, documentContents, attributeInfo, /** * We need to use a translator that translates the queries into a * filter format that the vector store can understand. We provide a basic translator * translator here, but you can create your own translator by extending BaseTranslator * abstract class. Note that the vector store needs to support filtering on the metadata * attributes you want to query on. */ structuredQueryTranslator: new FunctionalTranslator(),}); ### Testing it out[​](#testing-it-out "Direct link to Testing it out") And now we can actually try using our retriever! We can ask questions like “Which movies are less than 90 minutes?” or “Which movies are rated higher than 8.5?”. We can also ask questions like “Which movies are either comedy or drama and are less than 90 minutes?”. The translator within the retriever will automatically convert these questions into vector store filters that can be used to retrieve documents. await selfQueryRetriever.invoke("Which movies are less than 90 minutes?"); [ Document { pageContent: "Toys come alive and have a blast doing so", metadata: { year: 1995, genre: "animated", length: 77 } }] await selfQueryRetriever.invoke("Which movies are rated higher than 8.5?"); [ Document { pageContent: "A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception"... 16 more characters, metadata: { year: 2006, director: "Satoshi Kon", rating: 8.6 } }, Document { pageContent: "Three men walk into the Zone, three men walk out of the Zone", metadata: { year: 1979, director: "Andrei Tarkovsky", genre: "science fiction", rating: 9.9 } }] await selfQueryRetriever.invoke("Which movies are directed by Greta Gerwig?"); [ Document { pageContent: "A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata: { year: 2019, director: "Greta Gerwig", rating: 8.3, length: 135 } }] await selfQueryRetriever.invoke( "Which movies are either comedy or drama and are less than 90 minutes?"); [ Document { pageContent: "Toys come alive and have a blast doing so", metadata: { year: 1995, genre: "animated", length: 77 } }] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now seen how to use the `SelfQueryRetriever` to to generate vector store filters based on an original question. Next, you can check out the list of [vector stores that currently support self-querying](/v0.2/docs/integrations/retrievers/self_query/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to route execution within a chain ](/v0.2/docs/how_to/routing)[ Next How to chain runnables ](/v0.2/docs/how_to/sequence) * [Get started](#get-started) * [Creating our self-querying retriever](#creating-our-self-querying-retriever) * [Testing it out](#testing-it-out) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/pdf_qa
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build a PDF ingestion and Question/Answering system On this page Build a PDF ingestion and Question/Answering system =================================================== Prerequisites This guide assumes familiarity with the following concepts: * [Document loaders](/v0.2/docs/concepts/#document-loaders) * [Chat models](/v0.2/docs/concepts/#chat-models) * [Embeddings](/v0.2/docs/concepts/#embedding-models) * [Vector stores](/v0.2/docs/concepts/#vector-stores) * [Retrieval-augmented generation](/v0.2/docs/tutorials/rag/) PDF files often hold crucial unstructured data unavailable from other sources. They can be quite lengthy, and unlike plain text files, cannot generally be fed directly into the prompt of a language model. In this tutorial, you’ll create a system that can answer questions about PDF files. More specifically, you’ll use a [Document Loader](/v0.2/docs/concepts/#document-loaders) to load text in a format usable by an LLM, then build a retrieval-augmented generation (RAG) pipeline to answer questions, including citations from the source material. This tutorial will gloss over some concepts more deeply covered in our [RAG](/v0.2/docs/tutorials/rag/) tutorial, so you may want to go through those first if you haven’t already. Let’s dive in! Loading documents[​](#loading-documents "Direct link to Loading documents") --------------------------------------------------------------------------- First, you’ll need to choose a PDF to load. We’ll use a document from [Nike’s annual public SEC report](https://s1.q4cdn.com/806093406/files/doc_downloads/2023/414759-1-_5_Nike-NPS-Combo_Form-10-K_WR.pdf). It’s over 100 pages long, and contains some crucial data mixed with longer explanatory text. However, you can feel free to use a PDF of your choosing. Once you’ve chosen your PDF, the next step is to load it into a format that an LLM can more easily handle, since LLMs generally require text inputs. LangChain has a few different [built-in document loaders](/v0.2/docs/how_to/document_loader_pdf/) for this purpose which you can experiment with. Below, we’ll use one powered by the [`pdf-parse`](https://www.npmjs.com/package/pdf-parse) package that reads from a filepath: import "pdf-parse"; // Peer depimport { PDFLoader } from "@langchain/community/document_loaders/fs/pdf";const loader = new PDFLoader("../../data/nke-10k-2023.pdf");const docs = await loader.load();console.log(docs.length); 107 console.log(docs[0].pageContent.slice(0, 100));console.log(docs[0].metadata); Table of ContentsUNITED STATESSECURITIES AND EXCHANGE COMMISSIONWashington, D.C. 20549FORM 10-K{ source: '../../data/nke-10k-2023.pdf', pdf: { version: '1.10.100', info: { PDFFormatVersion: '1.4', IsAcroFormPresent: false, IsXFAPresent: false, Title: '0000320187-23-000039', Author: 'EDGAR Online, a division of Donnelley Financial Solutions', Subject: 'Form 10-K filed on 2023-07-20 for the period ending 2023-05-31', Keywords: '0000320187-23-000039; ; 10-K', Creator: 'EDGAR Filing HTML Converter', Producer: 'EDGRpdf Service w/ EO.Pdf 22.0.40.0', CreationDate: "D:20230720162200-04'00'", ModDate: "D:20230720162208-04'00'" }, metadata: null, totalPages: 107 }, loc: { pageNumber: 1 }} So what just happened? * The loader reads the PDF at the specified path into memory. * It then extracts text data using the `pdf-parse` package. * Finally, it creates a LangChain [Document](/v0.2/docs/concepts/#documents) for each page of the PDF with the page’s content and some metadata about where in the document the text came from. LangChain has [many other document loaders](/v0.2/docs/integrations/document_loaders/) for other data sources, or you can create a [custom document loader](/v0.2/docs/how_to/document_loader_custom/). Question answering with RAG[​](#question-answering-with-rag "Direct link to Question answering with RAG") --------------------------------------------------------------------------------------------------------- Next, you’ll prepare the loaded documents for later retrieval. Using a [text splitter](/v0.2/docs/concepts/#text-splitters), you’ll split your loaded documents into smaller documents that can more easily fit into an LLM’s context window, then load them into a [vector store](/v0.2/docs/concepts/#vectorstores). You can then create a [retriever](/v0.2/docs/concepts/#retrievers) from the vector store for use in our RAG chain: ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI(model="gpt-4o"); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings } from "@langchain/openai";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const splits = await textSplitter.splitDocuments(docs);const vectorstore = await MemoryVectorStore.fromDocuments( splits, new OpenAIEmbeddings());const retriever = vectorstore.asRetriever(); Finally, you’ll use some built-in helpers to construct the final `ragChain`: import { createRetrievalChain } from "langchain/chains/retrieval";import { createStuffDocumentsChain } from "langchain/chains/combine_documents";import { ChatPromptTemplate } from "@langchain/core/prompts";const systemTemplate = [ `You are an assistant for question-answering tasks. `, `Use the following pieces of retrieved context to answer `, `the question. If you don't know the answer, say that you `, `don't know. Use three sentences maximum and keep the `, `answer concise.`, `\n\n`, `{context}`,].join("");const prompt = ChatPromptTemplate.fromMessages([ ["system", systemTemplate], ["human", "{input}"],]);const questionAnswerChain = await createStuffDocumentsChain({ llm, prompt });const ragChain = await createRetrievalChain({ retriever, combineDocsChain: questionAnswerChain,});const results = await ragChain.invoke({ input: "What was Nike's revenue in 2023?",});console.log(results); { input: "What was Nike's revenue in 2023?", chat_history: [], context: [ Document { pageContent: 'Enterprise Resource Planning Platform, data and analytics, demand sensing, insight gathering, and other areas to create an end-to-end technology foundation, which we\n' + 'believe will further accelerate our digital transformation. We believe this unified approach will accelerate growth and unlock more efficiency for our business, while driving\n' + 'speed and responsiveness as we serve consumers globally.\n' + 'FINANCIAL HIGHLIGHTS\n' + '•In fiscal 2023, NIKE, Inc. achieved record Revenues of $51.2 billion, which increased 10% and 16% on a reported and currency-neutral basis, respectively\n' + '•NIKE Direct revenues grew 14% from $18.7 billion in fiscal 2022 to $21.3 billion in fiscal 2023, and represented approximately 44% of total NIKE Brand revenues for\n' + 'fiscal 2023\n' + '•Gross margin for the fiscal year decreased 250 basis points to 43.5% primarily driven by higher product costs, higher markdowns and unfavorable changes in foreign\n' + 'currency exchange rates, partially offset by strategic pricing actions', metadata: [Object] }, Document { pageContent: 'Table of Contents\n' + 'FISCAL 2023 NIKE BRAND REVENUE HIGHLIGHTS\n' + 'The following tables present NIKE Brand revenues disaggregated by reportable operating segment, distribution channel and major product line:\n' + 'FISCAL 2023 COMPARED TO FISCAL 2022\n' + '•NIKE, Inc. Revenues were $51.2 billion in fiscal 2023, which increased 10% and 16% compared to fiscal 2022 on a reported and currency-neutral basis, respectively.\n' + 'The increase was due to higher revenues in North America, Europe, Middle East & Africa ("EMEA"), APLA and Greater China, which contributed approximately 7, 6,\n' + '2 and 1 percentage points to NIKE, Inc. Revenues, respectively.\n' + '•NIKE Brand revenues, which represented over 90% of NIKE, Inc. Revenues, increased 10% and 16% on a reported and currency-neutral basis, respectively. This\n' + "increase was primarily due to higher revenues in Men's, the Jordan Brand, Women's and Kids' which grew 17%, 35%,11% and 10%, respectively, on a wholesale\n" + 'equivalent basis.', metadata: [Object] }, Document { pageContent: 'Table of Contents\n' + 'EUROPE, MIDDLE EAST & AFRICA\n' + '(Dollars in millions)\n' + 'FISCAL 2023FISCAL 2022% CHANGE\n' + '% CHANGE\n' + 'EXCLUDING\n' + 'CURRENCY\n' + 'CHANGESFISCAL 2021% CHANGE\n' + '% CHANGE\n' + 'EXCLUDING\n' + 'CURRENCY\n' + 'CHANGES\n' + 'Revenues by:\n' + 'Footwear$8,260 $7,388 12 %25 %$6,970 6 %9 %\n' + 'Apparel4,566 4,527 1 %14 %3,996 13 %16 %\n' + 'Equipment592 564 5 %18 %490 15 %17 %\n' + 'TOTAL REVENUES$13,418 $12,479 8 %21 %$11,456 9 %12 %\n' + 'Revenues by: \n' + 'Sales to Wholesale Customers$8,522 $8,377 2 %15 %$7,812 7 %10 %\n' + 'Sales through NIKE Direct4,896 4,102 19 %33 %3,644 13 %15 %\n' + 'TOTAL REVENUES$13,418 $12,479 8 %21 %$11,456 9 %12 %\n' + 'EARNINGS BEFORE INTEREST AND TAXES$3,531 $3,293 7 %$2,435 35 % \n' + 'FISCAL 2023 COMPARED TO FISCAL 2022\n' + "•EMEA revenues increased 21% on a currency-neutral basis, due to higher revenues in Men's, the Jordan Brand, Women's and Kids'. NIKE Direct revenues\n" + 'increased 33%, driven primarily by strong digital sales growth of 43% and comparable store sales growth of 22%.', metadata: [Object] }, Document { pageContent: 'Table of Contents\n' + 'NORTH AMERICA\n' + '(Dollars in millions)\n' + 'FISCAL 2023FISCAL 2022% CHANGE\n' + '% CHANGE\n' + 'EXCLUDING\n' + 'CURRENCY\n' + 'CHANGESFISCAL 2021% CHANGE\n' + '% CHANGE\n' + 'EXCLUDING\n' + 'CURRENCY\n' + 'CHANGES\n' + 'Revenues by:\n' + 'Footwear$14,897 $12,228 22 %22 %$11,644 5 %5 %\n' + 'Apparel5,947 5,492 8 %9 %5,028 9 %9 %\n' + 'Equipment764 633 21 %21 %507 25 %25 %\n' + 'TOTAL REVENUES$21,608 $18,353 18 %18 %$17,179 7 %7 %\n' + 'Revenues by: \n' + 'Sales to Wholesale Customers$11,273 $9,621 17 %18 %$10,186 -6 %-6 %\n' + 'Sales through NIKE Direct10,335 8,732 18 %18 %6,993 25 %25 %\n' + 'TOTAL REVENUES$21,608 $18,353 18 %18 %$17,179 7 %7 %\n' + 'EARNINGS BEFORE INTEREST AND TAXES$5,454 $5,114 7 %$5,089 0 %\n' + 'FISCAL 2023 COMPARED TO FISCAL 2022\n' + "•North America revenues increased 18% on a currency-neutral basis, primarily due to higher revenues in Men's and the Jordan Brand. NIKE Direct revenues\n" + 'increased 18%, driven by strong digital sales growth of 23%, comparable store sales growth of 9% and the addition of new stores.', metadata: [Object] } ], answer: 'According to the financial highlights, Nike, Inc. achieved record revenues of $51.2 billion in fiscal 2023, which increased 10% on a reported basis and 16% on a currency-neutral basis compared to fiscal 2022.'} You can see that you get both a final answer in the `answer` key of the results object, and the `context` the LLM used to generate an answer. Examining the values under the `context` further, you can see that they are documents that each contain a chunk of the ingested page content. Usefully, these documents also preserve the original metadata from way back when you first loaded them: console.log(results.context[0].pageContent); Enterprise Resource Planning Platform, data and analytics, demand sensing, insight gathering, and other areas to create an end-to-end technology foundation, which webelieve will further accelerate our digital transformation. We believe this unified approach will accelerate growth and unlock more efficiency for our business, while drivingspeed and responsiveness as we serve consumers globally.FINANCIAL HIGHLIGHTS•In fiscal 2023, NIKE, Inc. achieved record Revenues of $51.2 billion, which increased 10% and 16% on a reported and currency-neutral basis, respectively•NIKE Direct revenues grew 14% from $18.7 billion in fiscal 2022 to $21.3 billion in fiscal 2023, and represented approximately 44% of total NIKE Brand revenues forfiscal 2023•Gross margin for the fiscal year decreased 250 basis points to 43.5% primarily driven by higher product costs, higher markdowns and unfavorable changes in foreigncurrency exchange rates, partially offset by strategic pricing actions console.log(results.context[0].metadata); { source: '../../data/nke-10k-2023.pdf', pdf: { version: '1.10.100', info: { PDFFormatVersion: '1.4', IsAcroFormPresent: false, IsXFAPresent: false, Title: '0000320187-23-000039', Author: 'EDGAR Online, a division of Donnelley Financial Solutions', Subject: 'Form 10-K filed on 2023-07-20 for the period ending 2023-05-31', Keywords: '0000320187-23-000039; ; 10-K', Creator: 'EDGAR Filing HTML Converter', Producer: 'EDGRpdf Service w/ EO.Pdf 22.0.40.0', CreationDate: "D:20230720162200-04'00'", ModDate: "D:20230720162208-04'00'" }, metadata: null, totalPages: 107 }, loc: { pageNumber: 31, lines: { from: 14, to: 22 } }} This particular chunk came from page 31 in the original PDF. You can use this data to show which page in the PDF the answer came from, allowing users to quickly verify that answers are based on the source material. For a deeper dive into RAG, see [this more focused tutorial](/v0.2/docs/tutorials/rag/) or [our how-to guides](/v0.2/docs/how_to/#qa-with-rag). Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now seen how to load documents from a PDF file with a Document Loader and some techniques you can use to prepare that loaded data for RAG. For more on document loaders, you can check out: * [The entry in the conceptual guide](/v0.2/docs/concepts/#document-loaders) * [Related how-to guides](/v0.2/docs/how_to/#document-loaders) * [Available integrations](/v0.2/docs/integrations/document_loaders/) * [How to create a custom document loader](/v0.2/docs/how_to/document_loader_custom/) For more on RAG, see: * [Build a Retrieval Augmented Generation (RAG) App](/v0.2/docs/tutorials/rag/) * [Related how-to guides](/v0.2/docs/how_to/#qa-with-rag) * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build a Local RAG Application ](/v0.2/docs/tutorials/local_rag)[ Next Conversational RAG ](/v0.2/docs/tutorials/qa_chat_history) * [Loading documents](#loading-documents) * [Question answering with RAG](#question-answering-with-rag) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/sequence
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to chain runnables On this page How to chain runnables ====================== One point about [LangChain Expression Language](/v0.2/docs/concepts/#langchain-expression-language) is that any two runnables can be “chained” together into sequences. The output of the previous runnable’s `.invoke()` call is passed as input to the next runnable. This can be done using the `.pipe()` method. The resulting [`RunnableSequence`](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) is itself a runnable, which means it can be invoked, streamed, or further chained just like any other runnable. Advantages of chaining runnables in this way are efficient streaming (the sequence will stream output as soon as it is available), and debugging and tracing with tools like [LangSmith](/v0.2/docs/how_to/debugging). Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language (LCEL)](/v0.2/docs/concepts/#langchain-expression-language) * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) * [Chat models](/v0.2/docs/concepts/#chat-models) * [Output parser](/v0.2/docs/concepts/#output-parsers) The pipe method[​](#the-pipe-method "Direct link to The pipe method") --------------------------------------------------------------------- To show off how this works, let’s go through an example. We’ll walk through a common pattern in LangChain: using a [prompt template](/v0.2/docs/concepts#prompt-templates) to format input into a [chat model](/v0.2/docs/concepts/#chat-models), and finally converting the chat message output into a string with an \[output parser\](/docs/concepts#output-parsers. ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/core yarn add @langchain/core pnpm add @langchain/core import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";const prompt = ChatPromptTemplate.fromTemplate("tell me a joke about {topic}");const chain = prompt.pipe(model).pipe(new StringOutputParser()); Prompts and models are both runnable, and the output type from the prompt call is the same as the input type of the chat model, so we can chain them together. We can then invoke the resulting sequence like any other runnable: await chain.invoke({ topic: "bears" }); "Here's a bear joke for you:\n\nWhy did the bear dissolve in water?\nBecause it was a polar bear!" ### Coercion[​](#coercion "Direct link to Coercion") We can even combine this chain with more runnables to create another chain. This may involve some input/output formatting using other types of runnables, depending on the required inputs and outputs of the chain components. For example, let’s say we wanted to compose the joke generating chain with another chain that evaluates whether or not the generated joke was funny. We would need to be careful with how we format the input into the next chain. In the below example, the dict in the chain is automatically parsed and converted into a [`RunnableParallel`](/v0.2/docs/how_to/parallel), which runs all of its values in parallel and returns a dict with the results. This happens to be the same format the next prompt template expects. Here it is in action: import { RunnableLambda } from "@langchain/core/runnables";const analysisPrompt = ChatPromptTemplate.fromTemplate( "is this a funny joke? {joke}");const composedChain = new RunnableLambda({ func: async (input) => { const result = await chain.invoke(input); return { joke: result }; },}) .pipe(analysisPrompt) .pipe(model) .pipe(new StringOutputParser());await composedChain.invoke({ topic: "bears" }); 'Haha, that\'s a clever play on words! Using "polar" to imply the bear dissolved or became polar/polarized when put in water. Not the most hilarious joke ever, but it has a cute, groan-worthy pun that makes it mildly amusing. I appreciate a good pun or wordplay joke.' Functions will also be coerced into runnables, so you can add custom logic to your chains too. The below chain results in the same logical flow as before: import { RunnableSequence } from "@langchain/core/runnables";const composedChainWithLambda = RunnableSequence.from([ chain, (input) => ({ joke: input }), analysisPrompt, model, new StringOutputParser(),]);await composedChainWithLambda.invoke({ topic: "beets" }); "Haha, that's a cute and punny joke! I like how it plays on the idea of beets blushing or turning red like someone blushing. Food puns can be quite amusing. While not a total knee-slapper, it's a light-hearted, groan-worthy dad joke that would make me chuckle and shake my head. Simple vegetable humor!" > See the LangSmith trace for the run above [here](https://smith.langchain.com/public/ef1bf347-a243-4da6-9be6-54f5d73e6da2/r) However, keep in mind that using functions like this may interfere with operations like streaming. See [this section](/v0.2/docs/how_to/functions) for more information. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You now know some ways to chain two runnables together. To learn more, see the other how-to guides on runnables in this section. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to do "self-querying" retrieval ](/v0.2/docs/how_to/self_query)[ Next How to split text by tokens ](/v0.2/docs/how_to/split_by_token) * [The pipe method](#the-pipe-method) * [Coercion](#coercion) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/callbacks_backgrounding
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to make callbacks run in the background On this page How to make callbacks run in the background =========================================== Prerequisites This guide assumes familiarity with the following concepts: * [Callbacks](/v0.2/docs/concepts/#callbacks) By default, LangChain.js callbacks are blocking. This means that execution will wait for the callback to either return or timeout before continuing. This is to help ensure that if you are running code in [serverless environments](https://en.wikipedia.org/wiki/Serverless_computing) such as [AWS Lambda](https://aws.amazon.com/pm/lambda/) or [Cloudflare Workers](https://workers.cloudflare.com/), these callbacks always finish before the execution context ends. However, this can add unnecessary latency if you are running in traditional stateful environments. If desired, you can set your callbacks to run in the background to avoid this additional latency by setting the `LANGCHAIN_CALLBACKS_BACKGROUND` environment variable to `"true"`. You can then import the global [`awaitAllCallbacks`](https://api.js.langchain.com/functions/langchain_core_callbacks_promises.awaitAllCallbacks.html) method to ensure all callbacks finish if necessary. To illustrate this, we’ll create a [custom callback handler](/v0.2/docs/how_to/custom_callbacks) that takes some time to resolve, and show the timing with and without `LANGCHAIN_CALLBACKS_BACKGROUND` set. Here it is without the variable set: import { RunnableLambda } from "@langchain/core/runnables";Deno.env.set("LANGCHAIN_CALLBACKS_BACKGROUND", "false");const runnable = RunnableLambda.from(() => "hello!");const customHandler = { handleChainEnd: async () => { await new Promise((resolve) => setTimeout(resolve, 2000)); console.log("Call finished"); },};const startTime = new Date().getTime();await runnable.invoke({ number: "2" }, { callbacks: [customHandler] });console.log(`Elapsed time: ${new Date().getTime() - startTime}ms`); Call finishedElapsed time: 2005ms And here it is with backgrounding on: import { awaitAllCallbacks } from "@langchain/core/callbacks/promises";Deno.env.set("LANGCHAIN_CALLBACKS_BACKGROUND", "true");const startTime = new Date().getTime();await runnable.invoke({ number: "2" }, { callbacks: [customHandler] });console.log(`Initial elapsed time: ${new Date().getTime() - startTime}ms`);await awaitAllCallbacks();console.log(`Final elapsed time: ${new Date().getTime() - startTime}ms`); Initial elapsed time: 0msCall finishedFinal elapsed time: 2098ms Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to run callbacks in the background to reduce latency. Next, check out the other how-to guides in this section, such as [how to create custom callback handlers](/v0.2/docs/how_to/custom_callbacks). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to attach callbacks to a module ](/v0.2/docs/how_to/callbacks_attach)[ Next How to pass callbacks into a module constructor ](/v0.2/docs/how_to/callbacks_constructor) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/callbacks_constructor
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to pass callbacks into a module constructor On this page How to pass callbacks into a module constructor =============================================== Prerequisites This guide assumes familiarity with the following concepts: * [Callbacks](/v0.2/docs/concepts/#callbacks) Most LangChain modules allow you to pass `callbacks` directly into the constructor. In this case, the callbacks will only be called for that instance (and any nested runs). Here’s an example using LangChain’s built-in [`ConsoleCallbackHandler`](https://api.js.langchain.com/classes/langchain_core_tracers_console.ConsoleCallbackHandler.html): import { ConsoleCallbackHandler } from "@langchain/core/tracers/console";import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatAnthropic } from "@langchain/anthropic";const handler = new ConsoleCallbackHandler();const prompt = ChatPromptTemplate.fromTemplate(`What is 1 + {number}?`);const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", callbacks: [handler],});const chain = prompt.pipe(model);await chain.invoke({ number: "2" }); [llm/start] [1:llm:ChatAnthropic] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "HumanMessage" ], "kwargs": { "content": "What is 1 + 2?", "additional_kwargs": {}, "response_metadata": {} } } ] ]}[llm/end] [1:llm:ChatAnthropic] [1.00s] Exiting LLM run with output: { "generations": [ [ { "text": "1 + 2 = 3", "message": { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessage" ], "kwargs": { "content": "1 + 2 = 3", "tool_calls": [], "invalid_tool_calls": [], "additional_kwargs": { "id": "msg_011Z1cgi3gyNGxT55wnRNkXq", "type": "message", "role": "assistant", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 16, "output_tokens": 13 }, "stop_reason": "end_turn" }, "response_metadata": { "id": "msg_011Z1cgi3gyNGxT55wnRNkXq", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 16, "output_tokens": 13 }, "stop_reason": "end_turn" } } } } ] ], "llmOutput": { "id": "msg_011Z1cgi3gyNGxT55wnRNkXq", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 16, "output_tokens": 13 }, "stop_reason": "end_turn" }} AIMessage { lc_serializable: true, lc_kwargs: { content: "1 + 2 = 3", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_011Z1cgi3gyNGxT55wnRNkXq", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 16, output_tokens: 13 }, stop_reason: "end_turn" }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "1 + 2 = 3", name: undefined, additional_kwargs: { id: "msg_011Z1cgi3gyNGxT55wnRNkXq", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 16, output_tokens: 13 }, stop_reason: "end_turn" }, response_metadata: { id: "msg_011Z1cgi3gyNGxT55wnRNkXq", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 16, output_tokens: 13 }, stop_reason: "end_turn" }, tool_calls: [], invalid_tool_calls: []} You can see that we only see events from the chat model run - none from the prompt or broader chain. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to pass callbacks into a constructor. Next, check out the other how-to guides in this section, such as how to create your own [custom callback handlers](/v0.2/docs/how_to/custom_callbacks). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to make callbacks run in the background ](/v0.2/docs/how_to/callbacks_backgrounding)[ Next How to pass callbacks in at runtime ](/v0.2/docs/how_to/callbacks_runtime) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/callbacks_runtime
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to pass callbacks in at runtime On this page How to pass callbacks in at runtime =================================== Prerequisites This guide assumes familiarity with the following concepts: * [Callbacks](/v0.2/docs/concepts/#callbacks) In many cases, it is advantageous to pass in handlers instead when running the object. When we pass through [`CallbackHandlers`](https://api.js.langchain.com/interfaces/langchain_core_callbacks_base.CallbackHandlerMethods.html) using the `callbacks` keyword arg when executing an run, those callbacks will be issued by all nested objects involved in the execution. For example, when a handler is passed through to an Agent, it will be used for all callbacks related to the agent and all the objects involved in the agent’s execution, in this case, the Tools and LLM. This prevents us from having to manually attach the handlers to each individual nested object. Here’s an example using LangChain’s built-in [`ConsoleCallbackHandler`](https://api.js.langchain.com/classes/langchain_core_tracers_console.ConsoleCallbackHandler.html): import { ConsoleCallbackHandler } from "@langchain/core/tracers/console";import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatAnthropic } from "@langchain/anthropic";const handler = new ConsoleCallbackHandler();const prompt = ChatPromptTemplate.fromTemplate(`What is 1 + {number}?`);const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229",});const chain = prompt.pipe(model);await chain.invoke({ number: "2" }, { callbacks: [handler] }); [chain/start] [1:chain:RunnableSequence] Entering Chain run with input: { "number": "2"}[chain/start] [1:chain:RunnableSequence > 2:prompt:ChatPromptTemplate] Entering Chain run with input: { "number": "2"}[chain/end] [1:chain:RunnableSequence > 2:prompt:ChatPromptTemplate] [1ms] Exiting Chain run with output: { "lc": 1, "type": "constructor", "id": [ "langchain_core", "prompt_values", "ChatPromptValue" ], "kwargs": { "messages": [ { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "HumanMessage" ], "kwargs": { "content": "What is 1 + 2?", "additional_kwargs": {}, "response_metadata": {} } } ] }}[llm/start] [1:chain:RunnableSequence > 3:llm:ChatAnthropic] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "HumanMessage" ], "kwargs": { "content": "What is 1 + 2?", "additional_kwargs": {}, "response_metadata": {} } } ] ]}[llm/end] [1:chain:RunnableSequence > 3:llm:ChatAnthropic] [766ms] Exiting LLM run with output: { "generations": [ [ { "text": "1 + 2 = 3", "message": { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessage" ], "kwargs": { "content": "1 + 2 = 3", "tool_calls": [], "invalid_tool_calls": [], "additional_kwargs": { "id": "msg_01SGGkFVbUbH4fK7JS7agerD", "type": "message", "role": "assistant", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 16, "output_tokens": 13 }, "stop_reason": "end_turn" }, "response_metadata": { "id": "msg_01SGGkFVbUbH4fK7JS7agerD", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 16, "output_tokens": 13 }, "stop_reason": "end_turn" } } } } ] ], "llmOutput": { "id": "msg_01SGGkFVbUbH4fK7JS7agerD", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 16, "output_tokens": 13 }, "stop_reason": "end_turn" }}[chain/end] [1:chain:RunnableSequence] [778ms] Exiting Chain run with output: { "lc": 1, "type": "constructor", "id": [ "langchain_core", "messages", "AIMessage" ], "kwargs": { "content": "1 + 2 = 3", "tool_calls": [], "invalid_tool_calls": [], "additional_kwargs": { "id": "msg_01SGGkFVbUbH4fK7JS7agerD", "type": "message", "role": "assistant", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 16, "output_tokens": 13 }, "stop_reason": "end_turn" }, "response_metadata": { "id": "msg_01SGGkFVbUbH4fK7JS7agerD", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 16, "output_tokens": 13 }, "stop_reason": "end_turn" } }} AIMessage { lc_serializable: true, lc_kwargs: { content: "1 + 2 = 3", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { id: "msg_01SGGkFVbUbH4fK7JS7agerD", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 16, output_tokens: 13 }, stop_reason: "end_turn" }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "1 + 2 = 3", name: undefined, additional_kwargs: { id: "msg_01SGGkFVbUbH4fK7JS7agerD", type: "message", role: "assistant", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 16, output_tokens: 13 }, stop_reason: "end_turn" }, response_metadata: { id: "msg_01SGGkFVbUbH4fK7JS7agerD", model: "claude-3-sonnet-20240229", stop_sequence: null, usage: { input_tokens: 16, output_tokens: 13 }, stop_reason: "end_turn" }, tool_calls: [], invalid_tool_calls: []} If there are already existing callbacks associated with a module, these will run in addition to any passed in at runtime. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to pass callbacks at runtime. Next, check out the other how-to guides in this section, such as how to create your own [custom callback handlers](/v0.2/docs/how_to/custom_callbacks). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to pass callbacks into a module constructor ](/v0.2/docs/how_to/callbacks_constructor)[ Next How to split by character ](/v0.2/docs/how_to/character_text_splitter) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/split_by_token
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to split text by tokens On this page How to split text by tokens =========================== Prerequisites This guide assumes familiarity with the following concepts: * [Text splitters](/v0.2/docs/concepts#text-splitters) Language models have a token limit. You should not exceed the token limit. When you split your text into chunks it is therefore a good idea to count the number of tokens. There are many tokenizers. When you count tokens in your text you should use the same tokenizer as used in the language model. `js-tiktoken`[​](#js-tiktoken "Direct link to js-tiktoken") ----------------------------------------------------------- note [js-tiktoken](https://github.com/openai/js-tiktoken) is a JavaScript version of the `BPE` tokenizer created by OpenAI. We can use `js-tiktoken` to estimate tokens used. It is tuned to OpenAI models. 1. How the text is split: by character passed in. 2. How the chunk size is measured: by the `js-tiktoken` tokenizer. You can use the [`TokenTextSplitter`](https://v02.api.js.langchain.com/classes/langchain_textsplitters.TokenTextSplitter.html) like this: import { TokenTextSplitter } from "@langchain/textsplitters";import * as fs from "node:fs";// Load an example documentconst rawData = await fs.readFileSync( "../../../../examples/state_of_the_union.txt");const stateOfTheUnion = rawData.toString();const textSplitter = new TokenTextSplitter({ chunkSize: 10, chunkOverlap: 0,});const texts = await textSplitter.splitText(stateOfTheUnion);console.log(texts[0]); Madam Speaker, Madam Vice President, our **Note:** Some written languages (e.g. Chinese and Japanese) have characters which encode to 2 or more tokens. Using the `TokenTextSplitter` directly can split the tokens for a character between two chunks causing malformed Unicode characters. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned a method for splitting text based on token count. Next, check out the [full tutorial on retrieval-augmented generation](/v0.2/docs/tutorials/rag). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to chain runnables ](/v0.2/docs/how_to/sequence)[ Next How to deal with large databases ](/v0.2/docs/how_to/sql_large_db) * [`js-tiktoken`](#js-tiktoken) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/sql_large_db
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to deal with large databases On this page How to deal with large databases ================================ Prerequisites This guide assumes familiarity with the following: * [Question answering over SQL data](/v0.2/docs/tutorials/sql_qa) In order to write valid queries against a database, we need to feed the model the table names, table schemas, and feature values for it to query over. When there are many tables, columns, and/or high-cardinality columns, it becomes impossible for us to dump the full information about our database in every prompt. Instead, we must find ways to dynamically insert into the prompt only the most relevant information. Let's take a look at some techniques for doing this. Setup[​](#setup "Direct link to Setup") --------------------------------------- First, install the required packages and set your environment variables. This example will use OpenAI as the LLM. npm install langchain @langchain/community @langchain/openai typeorm sqlite3 export OPENAI_API_KEY="your api key"# Uncomment the below to use LangSmith. Not required.# export LANGCHAIN_API_KEY="your api key"# export LANGCHAIN_TRACING_V2=true The below example will use a SQLite connection with Chinook database. Follow these [installation steps](https://database.guide/2-sample-databases-sqlite/) to create `Chinook.db` in the same directory as this notebook: * Save [this](https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql) file as `Chinook_Sqlite.sql` * Run sqlite3 `Chinook.db` * Run `.read Chinook_Sqlite.sql` * Test `SELECT * FROM Artist LIMIT 10;` Now, `Chinhook.db` is in our directory and we can interface with it using the Typeorm-driven `SqlDatabase` class: import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});console.log(db.allTables.map((t) => t.tableName));/**[ 'Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track'] */ #### API Reference: * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` Many tables[​](#many-tables "Direct link to Many tables") --------------------------------------------------------- One of the main pieces of information we need to include in our prompt is the schemas of the relevant tables. When we have very many tables, we can't fit all of the schemas in a single prompt. What we can do in such cases is first extract the names of the tables related to the user input, and then include only their schemas. One easy and reliable way to do this is using OpenAI function-calling and Zod models. LangChain comes with a built-in `createExtractionChainZod` chain that lets us do just this: import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { ChatOpenAI } from "@langchain/openai";import { createSqlQueryChain } from "langchain/chains/sql_db";import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";import { z } from "zod";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});const llm = new ChatOpenAI({ model: "gpt-4", temperature: 0 });const Table = z.object({ names: z.array(z.string()).describe("Names of tables in SQL database"),});const tableNames = db.allTables.map((t) => t.tableName).join("\n");const system = `Return the names of ALL the SQL tables that MIGHT be relevant to the user question.The tables are:${tableNames}Remember to include ALL POTENTIALLY RELEVANT tables, even if you're not sure that they're needed.`;const prompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{input}"],]);const tableChain = prompt.pipe(llm.withStructuredOutput(Table));console.log( await tableChain.invoke({ input: "What are all the genres of Alanis Morisette songs?", }));/**{ names: [ 'Artist', 'Track', 'Genre' ] } */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/5ca0c91e-4a40-44ef-8c45-9a4247dc474c/r// -------------/**This works pretty well! Except, as we’ll see below, we actually need a few other tables as well.This would be pretty difficult for the model to know based just on the user question.In this case, we might think to simplify our model’s job by grouping the tables together.We’ll just ask the model to choose between categories “Music” and “Business”, and then take care of selecting all the relevant tables from there: */const prompt2 = ChatPromptTemplate.fromMessages([ [ "system", `Return the names of the SQL tables that are relevant to the user question. The tables are: Music Business`, ], ["human", "{input}"],]);const categoryChain = prompt2.pipe(llm.withStructuredOutput(Table));console.log( await categoryChain.invoke({ input: "What are all the genres of Alanis Morisette songs?", }));/**{ names: [ 'Music' ] } */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/12b62e78-bfbe-42ff-86f2-ad738a476554/r// -------------const getTables = (categories: z.infer<typeof Table>): Array<string> => { let tables: Array<string> = []; for (const category of categories.names) { if (category === "Music") { tables = tables.concat([ "Album", "Artist", "Genre", "MediaType", "Playlist", "PlaylistTrack", "Track", ]); } else if (category === "Business") { tables = tables.concat([ "Customer", "Employee", "Invoice", "InvoiceLine", ]); } } return tables;};const tableChain2 = categoryChain.pipe(getTables);console.log( await tableChain2.invoke({ input: "What are all the genres of Alanis Morisette songs?", }));/**[ 'Album', 'Artist', 'Genre', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track'] */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/e78c10aa-e923-4a24-b0c8-f7a6f5d316ce/r// -------------// Now that we’ve got a chain that can output the relevant tables for any query we can combine this with our createSqlQueryChain, which can accept a list of tableNamesToUse to determine which table schemas are included in the prompt:const queryChain = await createSqlQueryChain({ llm, db, dialect: "sqlite",});const tableChain3 = RunnableSequence.from([ { input: (i: { question: string }) => i.question, }, tableChain2,]);const fullChain = RunnablePassthrough.assign({ tableNamesToUse: tableChain3,}).pipe(queryChain);const query = await fullChain.invoke({ question: "What are all the genres of Alanis Morisette songs?",});console.log(query);/**SELECT DISTINCT "Genre"."Name"FROM "Genre"JOIN "Track" ON "Genre"."GenreId" = "Track"."GenreId"JOIN "Album" ON "Track"."AlbumId" = "Album"."AlbumId"JOIN "Artist" ON "Album"."ArtistId" = "Artist"."ArtistId"WHERE "Artist"."Name" = 'Alanis Morissette'LIMIT 5; */console.log(await db.run(query));/**[{"Name":"Rock"}] */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/c7d576d0-3462-40db-9edc-5492f10555bf/r// -------------// We might rephrase our question slightly to remove redundancy in the answerconst query2 = await fullChain.invoke({ question: "What is the set of all unique genres of Alanis Morisette songs?",});console.log(query2);/**SELECT DISTINCT Genre.Name FROM GenreJOIN Track ON Genre.GenreId = Track.GenreIdJOIN Album ON Track.AlbumId = Album.AlbumIdJOIN Artist ON Album.ArtistId = Artist.ArtistIdWHERE Artist.Name = 'Alanis Morissette' */console.log(await db.run(query2));/**[{"Name":"Rock"}] */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/6e80087d-e930-4f22-9b40-f7edb95a2145/r// ------------- #### API Reference: * [ChatPromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts` * [RunnablePassthrough](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html) from `@langchain/core/runnables` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [createSqlQueryChain](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) from `langchain/chains/sql_db` * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` We've seen how to dynamically include a subset of table schemas in a prompt within a chain. Another possible approach to this problem is to let an Agent decide for itself when to look up tables by giving it a Tool to do so. High-cardinality columns[​](#high-cardinality-columns "Direct link to High-cardinality columns") ------------------------------------------------------------------------------------------------ High-cardinality refers to columns in a database that have a vast range of unique values. These columns are characterized by a high level of uniqueness in their data entries, such as individual names, addresses, or product serial numbers. High-cardinality data can pose challenges for indexing and querying, as it requires more sophisticated strategies to efficiently filter and retrieve specific entries. In order to filter columns that contain proper nouns such as addresses, song names or artists, we first need to double-check the spelling in order to filter the data correctly. One naive strategy it to create a vector store with all the distinct proper nouns that exist in the database. We can then query that vector store each user input and inject the most relevant proper nouns into the prompt. First we need the unique values for each entity we want, for which we define a function that parses the result into a list of elements: import { DocumentInterface } from "@langchain/core/documents";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";import { createSqlQueryChain } from "langchain/chains/sql_db";import { SqlDatabase } from "langchain/sql_db";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { DataSource } from "typeorm";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});async function queryAsList(database: any, query: string): Promise<string[]> { const res: Array<{ [key: string]: string }> = JSON.parse( await database.run(query) ) .flat() .filter((el: any) => el != null); const justValues: Array<string> = res.map((item) => Object.values(item)[0] .replace(/\b\d+\b/g, "") .trim() ); return justValues;}let properNouns: string[] = await queryAsList(db, "SELECT Name FROM Artist");properNouns = properNouns.concat( await queryAsList(db, "SELECT Title FROM Album"));properNouns = properNouns.concat( await queryAsList(db, "SELECT Name FROM Genre"));console.log(properNouns.length);/**647 */console.log(properNouns.slice(0, 5));/**[ 'AC/DC', 'Accept', 'Aerosmith', 'Alanis Morissette', 'Alice In Chains'] */// Now we can embed and store all of our values in a vector database:const vectorDb = await MemoryVectorStore.fromTexts( properNouns, {}, new OpenAIEmbeddings());const retriever = vectorDb.asRetriever(15);// And put together a query construction chain that first retrieves values from the database and inserts them into the prompt:const system = `You are a SQLite expert. Given an input question, create a syntactically correct SQLite query to run.Unless otherwise specified, do not return more than {top_k} rows.Here is the relevant table info: {table_info}Here is a non-exhaustive list of possible feature values.If filtering on a feature value make sure to check its spelling against this list first:{proper_nouns}`;const prompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{input}"],]);const llm = new ChatOpenAI({ model: "gpt-4", temperature: 0 });const queryChain = await createSqlQueryChain({ llm, db, prompt, dialect: "sqlite",});const retrieverChain = RunnableSequence.from([ (i: { question: string }) => i.question, retriever, (docs: Array<DocumentInterface>) => docs.map((doc) => doc.pageContent).join("\n"),]);const chain = RunnablePassthrough.assign({ proper_nouns: retrieverChain,}).pipe(queryChain);// To try out our chain, let’s see what happens when we try filtering on “elenis moriset”, a misspelling of Alanis Morissette, without and with retrieval:// Without retrievalconst query = await queryChain.invoke({ question: "What are all the genres of Elenis Moriset songs?", proper_nouns: "",});console.log("query", query);/**query SELECT DISTINCT Genre.NameFROM GenreJOIN Track ON Genre.GenreId = Track.GenreIdJOIN Album ON Track.AlbumId = Album.AlbumIdJOIN Artist ON Album.ArtistId = Artist.ArtistIdWHERE Artist.Name = 'Elenis Moriset'LIMIT 5; */console.log("db query results", await db.run(query));/**db query results [] */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/b153cb9b-6fbb-43a8-b2ba-4c86715183b9/r// -------------// With retrieval:const query2 = await chain.invoke({ question: "What are all the genres of Elenis Moriset songs?",});console.log("query2", query2);/**query2 SELECT DISTINCT Genre.NameFROM GenreJOIN Track ON Genre.GenreId = Track.GenreIdJOIN Album ON Track.AlbumId = Album.AlbumIdJOIN Artist ON Album.ArtistId = Artist.ArtistIdWHERE Artist.Name = 'Alanis Morissette'; */console.log("db query results", await db.run(query2));/**db query results [{"Name":"Rock"}] */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/2f4f0e37-3b7f-47b5-837c-e2952489cac0/r// ------------- #### API Reference: * [DocumentInterface](https://v02.api.js.langchain.com/interfaces/langchain_core_documents.DocumentInterface.html) from `@langchain/core/documents` * [ChatPromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts` * [RunnablePassthrough](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html) from `@langchain/core/runnables` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [createSqlQueryChain](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) from `langchain/chains/sql_db` * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` * [MemoryVectorStore](https://v02.api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory` We can see that with retrieval we're able to correct the spelling and get back a valid result. Another possible approach to this problem is to let an Agent decide for itself when to look up proper nouns. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned about some prompting strategies to improve SQL generation. Next, check out some of the other guides in this section, like [how to validate queries](/v0.2/docs/how_to/sql_query_checking). You might also be interested in the query analysis guide [on handling high cardinality](/v0.2/docs/how_to/query_high_cardinality). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to split text by tokens ](/v0.2/docs/how_to/split_by_token)[ Next How to use prompting to improve results ](/v0.2/docs/how_to/sql_prompting) * [Setup](#setup) * [Many tables](#many-tables) * [High-cardinality columns](#high-cardinality-columns) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/sql_prompting
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use prompting to improve results On this page How to use prompting to improve results ======================================= Prerequisites This guide assumes familiarity with the following: * [Question answering over SQL data](/v0.2/docs/tutorials/sql_qa) In this guide we'll go over prompting strategies to improve SQL query generation. We'll largely focus on methods for getting relevant database-specific information in your prompt. Setup[​](#setup "Direct link to Setup") --------------------------------------- First, install the required packages and set your environment variables. This example will use OpenAI as the LLM. npm install @langchain/community @langchain/openai typeorm sqlite3 export OPENAI_API_KEY="your api key"# Uncomment the below to use LangSmith. Not required.# export LANGCHAIN_API_KEY="your api key"# export LANGCHAIN_TRACING_V2=true The below example will use a SQLite connection with Chinook database. Follow these [installation steps](https://database.guide/2-sample-databases-sqlite/) to create `Chinook.db` in the same directory as this notebook: * Save [this](https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql) file as `Chinook_Sqlite.sql` * Run sqlite3 `Chinook.db` * Run `.read Chinook_Sqlite.sql` * Test `SELECT * FROM Artist LIMIT 10;` Now, `Chinhook.db` is in our directory and we can interface with it using the Typeorm-driven `SqlDatabase` class: import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});console.log(db.allTables.map((t) => t.tableName));/**[ 'Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track'] */ #### API Reference: * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` Dialect-specific prompting[​](#dialect-specific-prompting "Direct link to Dialect-specific prompting") ------------------------------------------------------------------------------------------------------ One of the simplest things we can do is make our prompt specific to the SQL dialect we're using. When using the built-in [`createSqlQueryChain`](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) and [`SqlDatabase`](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html), this is handled for you for any of the following dialects: import { SQL_PROMPTS_MAP } from "langchain/chains/sql_db";console.log({ SQL_PROMPTS_MAP: Object.keys(SQL_PROMPTS_MAP) });/**{ SQL_PROMPTS_MAP: [ 'oracle', 'postgres', 'sqlite', 'mysql', 'mssql', 'sap hana' ]} */// For example, using our current DB we can see that we’ll get a SQLite-specific prompt:console.log({ sqlite: SQL_PROMPTS_MAP.sqlite,});/**{ sqlite: PromptTemplate { inputVariables: [ 'dialect', 'table_info', 'input', 'top_k' ], template: 'You are a SQLite expert. Given an input question, first create a syntactically correct SQLite query to run, then look at the results of the query and return the answer to the input question.\n' + 'Unless the user specifies in the question a specific number of examples to obtain, query for at most {top_k} results using the LIMIT clause as per SQLite. You can order the results to return the most informative data in the database.\n' + 'Never query for all columns from a table. You must query only the columns that are needed to answer the question. Wrap each column name in double quotes (") to denote them as delimited identifiers.\n' + 'Pay attention to use only the column names you can see in the tables below. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.\n' + '\n' + 'Use the following format:\n' + '\n' + 'Question: "Question here"\n' + 'SQLQuery: "SQL Query to run"\n' + 'SQLResult: "Result of the SQLQuery"\n' + 'Answer: "Final answer here"\n' + '\n' + 'Only use the following tables:\n' + '{table_info}\n' + '\n' + 'Question: {input}', }} */ #### API Reference: * [SQL\_PROMPTS\_MAP](https://v02.api.js.langchain.com/variables/langchain_chains_sql_db.SQL_PROMPTS_MAP.html) from `langchain/chains/sql_db` Table definitions and example rows[​](#table-definitions-and-example-rows "Direct link to Table definitions and example rows") ------------------------------------------------------------------------------------------------------------------------------ In basically any SQL chain, we'll need to feed the model at least part of the database schema. Without this it won't be able to write valid queries. Our database comes with some convenience methods to give us the relevant context. Specifically, we can get the table names, their schemas, and a sample of rows from each table: import { db } from "../db.js";const context = await db.getTableInfo();console.log(context);/** CREATE TABLE Album ( AlbumId INTEGER NOT NULL, Title NVARCHAR(160) NOT NULL, ArtistId INTEGER NOT NULL)SELECT * FROM "Album" LIMIT 3; AlbumId Title ArtistId 1 For Those About To Rock We Salute You 1 2 Balls to the Wall 2 3 Restless and Wild 2CREATE TABLE Artist ( ArtistId INTEGER NOT NULL, Name NVARCHAR(120))SELECT * FROM "Artist" LIMIT 3; ArtistId Name 1 AC/DC 2 Accept 3 AerosmithCREATE TABLE Customer ( CustomerId INTEGER NOT NULL, FirstName NVARCHAR(40) NOT NULL, LastName NVARCHAR(20) NOT NULL, Company NVARCHAR(80), Address NVARCHAR(70), City NVARCHAR(40), State NVARCHAR(40), Country NVARCHAR(40), PostalCode NVARCHAR(10), Phone NVARCHAR(24), Fax NVARCHAR(24), Email NVARCHAR(60) NOT NULL, SupportRepId INTEGER)SELECT * FROM "Customer" LIMIT 3; CustomerId FirstName LastName Company Address City State Country PostalCode Phone Fax Email SupportRepId 1 Luís Gonçalves Embraer - Empresa Brasileira de Aeronáutica S.A. Av. Brigadeiro Faria Lima,2170 São José dos Campos SP Brazil 12227-000 +55 (12) 3923-5555 +55 (12) 3923-5566 [email protected] 3 2 Leonie Köhler null Theodor-Heuss-Straße 34 Stuttgart null Germany 70174 +49 0711 2842222 null [email protected] 5 3 François Tremblay null 1498 rue Bélanger Montréal QC Canada H2G 1A7 +1 (514) 721-4711 null [email protected] 3CREATE TABLE Employee ( EmployeeId INTEGER NOT NULL, LastName NVARCHAR(20) NOT NULL, FirstName NVARCHAR(20) NOT NULL, Title NVARCHAR(30), ReportsTo INTEGER, BirthDate DATETIME, HireDate DATETIME, Address NVARCHAR(70), City NVARCHAR(40), State NVARCHAR(40), Country NVARCHAR(40), PostalCode NVARCHAR(10), Phone NVARCHAR(24), Fax NVARCHAR(24), Email NVARCHAR(60))SELECT * FROM "Employee" LIMIT 3; EmployeeId LastName FirstName Title ReportsTo BirthDate HireDate Address City State Country PostalCode Phone Fax Email 1 Adams Andrew General Manager null 1962-02-18 00:00:00 2002-08-14 00:00:00 11120 Jasper Ave NW Edmonton AB Canada T5K 2N1 +1 (780) 428-9482 +1 (780) 428-3457 [email protected] 2 Edwards Nancy Sales Manager 1 1958-12-08 00:00:00 2002-05-01 00:00:00 825 8 Ave SW Calgary AB Canada T2P 2T3 +1 (403) 262-3443 +1 (403) 262-3322 [email protected] 3 Peacock Jane Sales Support Agent 2 1973-08-29 00:00:00 2002-04-01 00:00:00 1111 6 Ave SW Calgary AB Canada T2P 5M5 +1 (403) 262-3443 +1 (403) 262-6712 [email protected] TABLE Genre ( GenreId INTEGER NOT NULL, Name NVARCHAR(120))SELECT * FROM "Genre" LIMIT 3; GenreId Name 1 Rock 2 Jazz 3 MetalCREATE TABLE Invoice ( InvoiceId INTEGER NOT NULL, CustomerId INTEGER NOT NULL, InvoiceDate DATETIME NOT NULL, BillingAddress NVARCHAR(70), BillingCity NVARCHAR(40), BillingState NVARCHAR(40), BillingCountry NVARCHAR(40), BillingPostalCode NVARCHAR(10), Total NUMERIC(10,2) NOT NULL)SELECT * FROM "Invoice" LIMIT 3; InvoiceId CustomerId InvoiceDate BillingAddress BillingCity BillingState BillingCountry BillingPostalCode Total 1 2 2009-01-01 00:00:00 Theodor-Heuss-Straße 34 Stuttgart null Germany 70174 1.98 2 4 2009-01-02 00:00:00 Ullevålsveien 14 Oslo null Norway 0171 3.96 3 8 2009-01-03 00:00:00 Grétrystraat 63 Brussels null Belgium 1000 5.94CREATE TABLE InvoiceLine ( InvoiceLineId INTEGER NOT NULL, InvoiceId INTEGER NOT NULL, TrackId INTEGER NOT NULL, UnitPrice NUMERIC(10,2) NOT NULL, Quantity INTEGER NOT NULL)SELECT * FROM "InvoiceLine" LIMIT 3; InvoiceLineId InvoiceId TrackId UnitPrice Quantity 1 1 2 0.99 1 2 1 4 0.99 1 3 2 6 0.99 1CREATE TABLE MediaType ( MediaTypeId INTEGER NOT NULL, Name NVARCHAR(120))SELECT * FROM "MediaType" LIMIT 3; MediaTypeId Name 1 MPEG audio file 2 Protected AAC audio file 3 Protected MPEG-4 video fileCREATE TABLE Playlist ( PlaylistId INTEGER NOT NULL, Name NVARCHAR(120))SELECT * FROM "Playlist" LIMIT 3; PlaylistId Name 1 Music 2 Movies 3 TV ShowsCREATE TABLE PlaylistTrack ( PlaylistId INTEGER NOT NULL, TrackId INTEGER NOT NULL)SELECT * FROM "PlaylistTrack" LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390CREATE TABLE Track ( TrackId INTEGER NOT NULL, Name NVARCHAR(200) NOT NULL, AlbumId INTEGER, MediaTypeId INTEGER NOT NULL, GenreId INTEGER, Composer NVARCHAR(220), Milliseconds INTEGER NOT NULL, Bytes INTEGER, UnitPrice NUMERIC(10,2) NOT NULL)SELECT * FROM "Track" LIMIT 3; TrackId Name AlbumId MediaTypeId GenreId Composer Milliseconds Bytes UnitPrice 1 For Those About To Rock (We Salute You) 1 1 1 Angus Young,Malcolm Young,Brian Johnson 343719 11170334 0.99 2 Balls to the Wall 2 2 1 U. Dirkschneider,W. Hoffmann,H. Frank,P. Baltes,S. Kaufmann,G. Hoffmann 342562 5510424 0.99 3 Fast As a Shark 3 2 1 F. Baltes,S. Kaufman,U. Dirkscneider & W. Hoffman 230619 3990994 0.99 */ #### API Reference: Few-shot examples[​](#few-shot-examples "Direct link to Few-shot examples") --------------------------------------------------------------------------- Including examples of natural language questions being converted to valid SQL queries against our database in the prompt will often improve model performance, especially for complex queries. Let's say we have the following examples: export const examples = [ { input: "List all artists.", query: "SELECT * FROM Artist;" }, { input: "Find all albums for the artist 'AC/DC'.", query: "SELECT * FROM Album WHERE ArtistId = (SELECT ArtistId FROM Artist WHERE Name = 'AC/DC');", }, { input: "List all tracks in the 'Rock' genre.", query: "SELECT * FROM Track WHERE GenreId = (SELECT GenreId FROM Genre WHERE Name = 'Rock');", }, { input: "Find the total duration of all tracks.", query: "SELECT SUM(Milliseconds) FROM Track;", }, { input: "List all customers from Canada.", query: "SELECT * FROM Customer WHERE Country = 'Canada';", }, { input: "How many tracks are there in the album with ID 5?", query: "SELECT COUNT(*) FROM Track WHERE AlbumId = 5;", }, { input: "Find the total number of invoices.", query: "SELECT COUNT(*) FROM Invoice;", }, { input: "List all tracks that are longer than 5 minutes.", query: "SELECT * FROM Track WHERE Milliseconds > 300000;", }, { input: "Who are the top 5 customers by total purchase?", query: "SELECT CustomerId, SUM(Total) AS TotalPurchase FROM Invoice GROUP BY CustomerId ORDER BY TotalPurchase DESC LIMIT 5;", }, { input: "Which albums are from the year 2000?", query: "SELECT * FROM Album WHERE strftime('%Y', ReleaseDate) = '2000';", }, { input: "How many employees are there", query: 'SELECT COUNT(*) FROM "Employee"', },]; #### API Reference: We can create a few-shot prompt with them like so: import { FewShotPromptTemplate, PromptTemplate } from "@langchain/core/prompts";import { examples } from "./examples.js";const examplePrompt = PromptTemplate.fromTemplate( `User input: {input}\nSQL Query: {query}`);const prompt = new FewShotPromptTemplate({ examples: examples.slice(0, 5), examplePrompt, prefix: `You are a SQLite expert. Given an input question, create a syntactically correct SQLite 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"],});console.log( await prompt.format({ input: "How many artists are there?", top_k: "3", table_info: "foo", }));/**You are a SQLite expert. Given an input question, create a syntactically correct SQLite query to run.Unless otherwise specified, do not return more than 3 rows.Here is the relevant table info: fooBelow are a number of examples of questions and their corresponding SQL queries.User input: List all artists.SQL Query: SELECT * FROM Artist;User input: Find all albums for the artist 'AC/DC'.SQL Query: SELECT * FROM Album WHERE ArtistId = (SELECT ArtistId FROM Artist WHERE Name = 'AC/DC');User input: List all tracks in the 'Rock' genre.SQL Query: SELECT * FROM Track WHERE GenreId = (SELECT GenreId FROM Genre WHERE Name = 'Rock');User input: Find the total duration of all tracks.SQL Query: SELECT SUM(Milliseconds) FROM Track;User input: List all customers from Canada.SQL Query: SELECT * FROM Customer WHERE Country = 'Canada';User input: How many artists are there?SQL query: */ #### API Reference: * [FewShotPromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.FewShotPromptTemplate.html) from `@langchain/core/prompts` * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` Dynamic few-shot examples[​](#dynamic-few-shot-examples "Direct link to Dynamic few-shot examples") --------------------------------------------------------------------------------------------------- If we have enough examples, we may want to only include the most relevant ones in the prompt, either because they don't fit in the model's context window or because the long tail of examples distracts the model. And specifically, given any input we want to include the examples most relevant to that input. We can do just this using an ExampleSelector. In this case we'll use a [`SemanticSimilarityExampleSelector`](https://v02.api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html), which will store the examples in the vector database of our choosing. At runtime it will perform a similarity search between the input and our examples, and return the most semantically similar ones: import { MemoryVectorStore } from "langchain/vectorstores/memory";import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors";import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";import { FewShotPromptTemplate, PromptTemplate } from "@langchain/core/prompts";import { createSqlQueryChain } from "langchain/chains/sql_db";import { examples } from "./examples.js";import { db } from "../db.js";const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples< typeof MemoryVectorStore>(examples, new OpenAIEmbeddings(), MemoryVectorStore, { k: 5, inputKeys: ["input"],});console.log( await exampleSelector.selectExamples({ input: "how many artists are there?" }));/**[ { input: 'List all artists.', query: 'SELECT * FROM Artist;' }, { input: 'How many employees are there', query: 'SELECT COUNT(*) FROM "Employee"' }, { input: 'How many tracks are there in the album with ID 5?', query: 'SELECT COUNT(*) FROM Track WHERE AlbumId = 5;' }, { input: 'Which albums are from the year 2000?', query: "SELECT * FROM Album WHERE strftime('%Y', ReleaseDate) = '2000';" }, { input: "List all tracks in the 'Rock' genre.", query: "SELECT * FROM Track WHERE GenreId = (SELECT GenreId FROM Genre WHERE Name = 'Rock');" }] */// To use it, we can pass the ExampleSelector directly in to our FewShotPromptTemplate:const examplePrompt = PromptTemplate.fromTemplate( `User input: {input}\nSQL Query: {query}`);const prompt = new FewShotPromptTemplate({ exampleSelector, examplePrompt, prefix: `You are a SQLite expert. Given an input question, create a syntactically correct SQLite 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"],});console.log( await prompt.format({ input: "How many artists are there?", top_k: "3", table_info: "foo", }));/**You are a SQLite expert. Given an input question, create a syntactically correct SQLite query to run.Unless otherwise specified, do not return more than 3 rows.Here is the relevant table info: fooBelow are a number of examples of questions and their corresponding SQL queries.User input: List all artists.SQL Query: SELECT * FROM Artist;User input: How many employees are thereSQL Query: SELECT COUNT(*) FROM "Employee"User input: How many tracks are there in the album with ID 5?SQL Query: SELECT COUNT(*) FROM Track WHERE AlbumId = 5;User input: Which albums are from the year 2000?SQL Query: SELECT * FROM Album WHERE strftime('%Y', ReleaseDate) = '2000';User input: List all tracks in the 'Rock' genre.SQL Query: SELECT * FROM Track WHERE GenreId = (SELECT GenreId FROM Genre WHERE Name = 'Rock');User input: How many artists are there?SQL query: */// Now we can use it in a chain:const llm = new ChatOpenAI({ temperature: 0,});const chain = await createSqlQueryChain({ db, llm, prompt, dialect: "sqlite",});console.log(await chain.invoke({ question: "how many artists are there?" }));/**SELECT COUNT(*) FROM Artist; */ #### API Reference: * [MemoryVectorStore](https://v02.api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory` * [SemanticSimilarityExampleSelector](https://v02.api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html) from `@langchain/core/example_selectors` * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [FewShotPromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.FewShotPromptTemplate.html) from `@langchain/core/prompts` * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` * [createSqlQueryChain](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) from `langchain/chains/sql_db` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned about some prompting strategies to improve SQL generation. Next, check out some of the other guides in this section, like [how to query over large databases](/v0.2/docs/how_to/sql_large_db). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to deal with large databases ](/v0.2/docs/how_to/sql_large_db)[ Next How to do query validation ](/v0.2/docs/how_to/sql_query_checking) * [Setup](#setup) * [Dialect-specific prompting](#dialect-specific-prompting) * [Table definitions and example rows](#table-definitions-and-example-rows) * [Few-shot examples](#few-shot-examples) * [Dynamic few-shot examples](#dynamic-few-shot-examples) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/sql_qa
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build a Question/Answering system over SQL data On this page Build a Question/Answering system over SQL data =============================================== Prerequisites This guide assumes familiarity with the following concepts: * [Chaining runnables](/v0.2/docs/how_to/sequence/) * [Chat models](/v0.2/docs/concepts/#chat-models) * [Tools](/v0.2/docs/concepts/#tools) * [Agents](/v0.2/docs/concepts/#agents) In this guide we'll go over the basic ways to create a Q&A chain and agent over a SQL database. These systems will allow us to ask a question about the data in a SQL database and get back a natural language answer. The main difference between the two is that our agent can query the database in a loop as many time as it needs to answer the question. ⚠️ Security note ⚠️[​](#️-security-note-️ "Direct link to ⚠️ Security note ⚠️") ------------------------------------------------------------------------------- Building Q&A systems of SQL databases can require executing model-generated SQL queries. There are inherent risks in doing this. Make sure that your database connection permissions are always scoped as narrowly as possible for your chain/agent's needs. This will mitigate though not eliminate the risks of building a model-driven system. For more on general security best practices, see [here](/v0.2/docs/security). Architecture[​](#architecture "Direct link to Architecture") ------------------------------------------------------------ At a high-level, the steps of most SQL chain and agent are: 1. **Convert question to SQL query**: Model converts user input to a SQL query. 2. **Execute SQL query**: Execute the SQL query 3. **Answer the question**: Model responds to user input using the query results. ![SQL Use Case Diagram](/v0.2/assets/images/sql_usecase-d432701261f05ab69b38576093718cf3.png) ⚠️ Security note ⚠️[​](#️-security-note-️-1 "Direct link to ⚠️ Security note ⚠️") --------------------------------------------------------------------------------- Building Q&A systems of SQL databases can require executing model-generated SQL queries. There are inherent risks in doing this. Make sure that your database connection permissions are always scoped as narrowly as possible for your chain/agent's needs. This will mitigate though not eliminate the risks of building a model-driven system. For more on general security best practices, see [here](/v0.2/docs/security). Architecture[​](#architecture-1 "Direct link to Architecture") -------------------------------------------------------------- At a high-level, the steps of most SQL chain and agent are: 1. **Convert question to SQL query**: Model converts user input to a SQL query. 2. **Execute SQL query**: Execute the SQL query 3. **Answer the question**: Model responds to user input using the query results. ![SQL Use Case Diagram](/v0.2/assets/images/sql_usecase-d432701261f05ab69b38576093718cf3.png) Setup[​](#setup "Direct link to Setup") --------------------------------------- First, get required packages and set environment variables: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm i langchain @langchain/community @langchain/openai yarn add langchain @langchain/community @langchain/openai pnpm add langchain @langchain/community @langchain/openai We default to OpenAI models in this guide. export OPENAI_API_KEY=<your key># Uncomment the below to use LangSmith. Not required, but recommended for debugging and observability.# export LANGCHAIN_API_KEY=<your key># export LANGCHAIN_TRACING_V2=true import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});console.log(db.allTables.map((t) => t.tableName));/**[ 'Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track'] */ #### API Reference: * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` Great! We've got a SQL database that we can query. Now let's try hooking it up to an LLM. Chain[​](#chain "Direct link to Chain") --------------------------------------- Let's create a simple chain that takes a question, turns it into a SQL query, executes the query, and uses the result to answer the original question. ### Convert question to SQL query[​](#convert-question-to-sql-query "Direct link to Convert question to SQL query") The first step in a SQL chain or agent is to take the user input and convert it to a SQL query. LangChain comes with a built-in chain for this: [`createSqlQueryChain`](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) import { ChatOpenAI } from "@langchain/openai";import { createSqlQueryChain } from "langchain/chains/sql_db";import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});const llm = new ChatOpenAI({ model: "gpt-4", temperature: 0 });const chain = await createSqlQueryChain({ llm, db, dialect: "sqlite",});const response = await chain.invoke({ question: "How many employees are there?",});console.log("response", response);/**response SELECT COUNT(*) FROM "Employee" */console.log("db run result", await db.run(response));/**db run result [{"COUNT(*)":8}] */ #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [createSqlQueryChain](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) from `langchain/chains/sql_db` * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` We can look at the [LangSmith trace](https://smith.langchain.com/public/6d8f0213-9f02-498e-aeb2-ec774e324e2c/r) to get a better understanding of what this chain is doing. We can also inspect the chain directly for its prompts. Looking at the prompt (below), we can see that it is: * Dialect-specific. In this case it references SQLite explicitly. * Has definitions for all the available tables. * Has three examples rows for each table. This technique is inspired by papers like [this](https://arxiv.org/pdf/2204.00498.pdf), which suggest showing examples rows and being explicit about tables improves performance. We can also inspect the full prompt via the LangSmith trace: ![Chain Prompt](/v0.2/assets/images/sql_quickstart_langsmith_prompt-e90559eddd490ceee277642d9e76b37b.png) ### Execute SQL query[​](#execute-sql-query "Direct link to Execute SQL query") Now that we've generated a SQL query, we'll want to execute it. This is the most dangerous part of creating a SQL chain. Consider carefully if it is OK to run automated queries over your data. Minimize the database connection permissions as much as possible. Consider adding a human approval step to you chains before query execution (see below). We can use the [`QuerySqlTool`](https://v02.api.js.langchain.com/classes/langchain_tools_sql.QuerySqlTool.html) to easily add query execution to our chain: import { ChatOpenAI } from "@langchain/openai";import { createSqlQueryChain } from "langchain/chains/sql_db";import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";import { QuerySqlTool } from "langchain/tools/sql";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});const llm = new ChatOpenAI({ model: "gpt-4", temperature: 0 });const executeQuery = new QuerySqlTool(db);const writeQuery = await createSqlQueryChain({ llm, db, dialect: "sqlite",});const chain = writeQuery.pipe(executeQuery);console.log(await chain.invoke({ question: "How many employees are there" }));/**[{"COUNT(*)":8}] */ #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [createSqlQueryChain](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) from `langchain/chains/sql_db` * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` * [QuerySqlTool](https://v02.api.js.langchain.com/classes/langchain_tools_sql.QuerySqlTool.html) from `langchain/tools/sql` tip See a LangSmith trace of the chain above [here](https://smith.langchain.com/public/3cbcf6f2-a55b-4701-a2e3-9928e4747328/r). ### Answer the question[​](#answer-the-question "Direct link to Answer the question") Now that we have a way to automatically generate and execute queries, we just need to combine the original question and SQL query result to generate a final answer. We can do this by passing question and result to the LLM once more: import { ChatOpenAI } from "@langchain/openai";import { createSqlQueryChain } from "langchain/chains/sql_db";import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";import { QuerySqlTool } from "langchain/tools/sql";import { PromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});const llm = new ChatOpenAI({ model: "gpt-4", temperature: 0 });const executeQuery = new QuerySqlTool(db);const writeQuery = await createSqlQueryChain({ llm, db, dialect: "sqlite",});const answerPrompt = PromptTemplate.fromTemplate(`Given the following user question, corresponding SQL query, and SQL result, answer the user question.Question: {question}SQL Query: {query}SQL Result: {result}Answer: `);const answerChain = answerPrompt.pipe(llm).pipe(new StringOutputParser());const chain = RunnableSequence.from([ RunnablePassthrough.assign({ query: writeQuery }).assign({ result: (i: { query: string }) => executeQuery.invoke(i.query), }), answerChain,]);console.log(await chain.invoke({ question: "How many employees are there" }));/**There are 8 employees. */ #### API Reference: * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [createSqlQueryChain](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) from `langchain/chains/sql_db` * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` * [QuerySqlTool](https://v02.api.js.langchain.com/classes/langchain_tools_sql.QuerySqlTool.html) from `langchain/tools/sql` * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` * [StringOutputParser](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers` * [RunnablePassthrough](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html) from `@langchain/core/runnables` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` tip See a LangSmith trace of the chain above [here](https://smith.langchain.com/public/d130ce1f-1fce-4192-921e-4b522884ec1a/r). ### Next steps[​](#next-steps "Direct link to Next steps") For more complex query-generation, we may want to create few-shot prompts or add query-checking steps. For advanced techniques like this and more check out: * [Prompting strategies](/v0.2/docs/how_to/sql_prompting): Advanced prompt engineering techniques. * [Query checking](/v0.2/docs/how_to/sql_query_checking): Add query validation and error handling. * [Large databases](/v0.2/docs/how_to/sql_large_db): Techniques for working with large databases. Agents[​](#agents "Direct link to Agents") ------------------------------------------ LangChain offers a number of tools and functions that allow you to create SQL Agents which can provide a more flexible way of interacting with SQL databases. The main advantages of using SQL Agents are: * It can answer questions based on the databases' schema as well as on the databases' content (like describing a specific table). * It can recover from errors by running a generated query, catching the traceback and regenerating it correctly. * It can answer questions that require multiple dependent queries. * It will save tokens by only considering the schema from relevant tables. * To initialize the agent, we use [`createOpenAIToolsAgent`](https://v02.api.js.langchain.com/functions/langchain_agents.createOpenAIToolsAgent.html) function. This agent contains the [`SqlToolkit`](https://v02.api.js.langchain.com/classes/langchain_agents_toolkits_sql.SqlToolkit.html) which contains tools to: * Create and execute queries * Check query syntax * Retrieve table descriptions * … and more * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build a Retrieval Augmented Generation (RAG) App ](/v0.2/docs/tutorials/rag)[ Next How-to guides ](/v0.2/docs/how_to/) * [⚠️ Security note ⚠️](#️-security-note-️) * [Architecture](#architecture) * [⚠️ Security note ⚠️](#️-security-note-️-1) * [Architecture](#architecture-1) * [Setup](#setup) * [Chain](#chain) * [Convert question to SQL query](#convert-question-to-sql-query) * [Execute SQL query](#execute-sql-query) * [Answer the question](#answer-the-question) * [Next steps](#next-steps) * [Agents](#agents)
null
https://js.langchain.com/v0.2/docs/how_to/sql_query_checking
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to do query validation On this page How to do query validation ========================== Prerequisites This guide assumes familiarity with the following: * [Question answering over SQL data](/v0.2/docs/tutorials/sql_qa) Perhaps the most error-prone part of any SQL chain or agent is writing valid and safe SQL queries. In this guide we'll go over some strategies for validating our queries and handling invalid queries. Setup[​](#setup "Direct link to Setup") --------------------------------------- First, get required packages and set environment variables: tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). npm install @langchain/community @langchain/openai typeorm sqlite3 export OPENAI_API_KEY="your api key"# Uncomment the below to use LangSmith. Not required.# export LANGCHAIN_API_KEY="your api key"# export LANGCHAIN_TRACING_V2=true The below example will use a SQLite connection with Chinook database. Follow these [installation steps](https://database.guide/2-sample-databases-sqlite/) to create `Chinook.db` in the same directory as this notebook: * Save [this](https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql) file as `Chinook_Sqlite.sql` * Run sqlite3 `Chinook.db` * Run `.read Chinook_Sqlite.sql` * Test `SELECT * FROM Artist LIMIT 10;` Now, `Chinhook.db` is in our directory and we can interface with it using the Typeorm-driven `SqlDatabase` class: import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});console.log(db.allTables.map((t) => t.tableName));/**[ 'Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track'] */ #### API Reference: * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` Query checker[​](#query-checker "Direct link to Query checker") --------------------------------------------------------------- Perhaps the simplest strategy is to ask the model itself to check the original query for common mistakes. Suppose we have the following SQL query chain: import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate, PromptTemplate } from "@langchain/core/prompts";import { RunnableSequence } from "@langchain/core/runnables";import { ChatOpenAI } from "@langchain/openai";import { createSqlQueryChain } from "langchain/chains/sql_db";import { SqlDatabase } from "langchain/sql_db";import { DataSource } from "typeorm";const datasource = new DataSource({ type: "sqlite", database: "../../../../Chinook.db",});const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource,});const llm = new ChatOpenAI({ model: "gpt-4", temperature: 0 });const chain = await createSqlQueryChain({ llm, db, dialect: "sqlite",});/** * And we want to validate its outputs. We can do so by extending the chain with a second prompt and model call: */const SYSTEM_PROMPT = `Double check the user's {dialect} query for common mistakes, including:- Using NOT IN with NULL values- Using UNION when UNION ALL should have been used- Using BETWEEN for exclusive ranges- Data type mismatch in predicates- Properly quoting identifiers- Using the correct number of arguments for functions- Casting to the correct data type- Using the proper columns for joinsIf there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.Output the final SQL query only.`;const prompt = await ChatPromptTemplate.fromMessages([ ["system", SYSTEM_PROMPT], ["human", "{query}"],]).partial({ dialect: "sqlite" });const validationChain = prompt.pipe(llm).pipe(new StringOutputParser());const fullChain = RunnableSequence.from([ { query: async (i: { question: string }) => chain.invoke(i), }, validationChain,]);const query = await fullChain.invoke({ question: "What's the average Invoice from an American customer whose Fax is missing since 2003 but before 2010",});console.log("query", query);/**query SELECT AVG("Total") FROM "Invoice" WHERE "CustomerId" IN (SELECT "CustomerId" FROM "Customer" WHERE "Country" = 'USA' AND "Fax" IS NULL) AND "InvoiceDate" BETWEEN '2003-01-01 00:00:00' AND '2009-12-31 23:59:59' */console.log("db query results", await db.run(query));/**db query results [{"AVG(\"Total\")":6.632999999999998}] */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/d1131395-8477-47cd-8f74-e0c5491ea956/r// -------------// The obvious downside of this approach is that we need to make two model calls instead of one to generate our query.// To get around this we can try to perform the query generation and query check in a single model invocation:const SYSTEM_PROMPT_2 = `You are a {dialect} expert. Given an input question, create a syntactically correct {dialect} query to run.Unless the user specifies in the question a specific number of examples to obtain, query for at most {top_k} results using the LIMIT clause as per {dialect}. You can order the results to return the most informative data in the database.Never query for all columns from a table. You must query only the columns that are needed to answer the question. Wrap each column name in double quotes (") to denote them as delimited identifiers.Pay attention to use only the column names you can see in the tables below. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.Pay attention to use date('now') function to get the current date, if the question involves "today".Only use the following tables:{table_info}Write an initial draft of the query. Then double check the {dialect} query for common mistakes, including:- Using NOT IN with NULL values- Using UNION when UNION ALL should have been used- Using BETWEEN for exclusive ranges- Data type mismatch in predicates- Properly quoting identifiers- Using the correct number of arguments for functions- Casting to the correct data type- Using the proper columns for joinsUse format:First draft: <<FIRST_DRAFT_QUERY>>Final answer: <<FINAL_ANSWER_QUERY>>`;const prompt2 = await PromptTemplate.fromTemplate( `System: ${SYSTEM_PROMPT_2}Human: {input}`).partial({ dialect: "sqlite" });const parseFinalAnswer = (output: string): string => output.split("Final answer: ")[1];const chain2 = ( await createSqlQueryChain({ llm, db, prompt: prompt2, dialect: "sqlite", })).pipe(parseFinalAnswer);const query2 = await chain2.invoke({ question: "What's the average Invoice from an American customer whose Fax is missing since 2003 but before 2010",});console.log("query2", query2);/**query2 SELECT AVG("Total") FROM "Invoice" WHERE "CustomerId" IN (SELECT "CustomerId" FROM "Customer" WHERE "Country" = 'USA' AND "Fax" IS NULL) AND date("InvoiceDate") BETWEEN date('2003-01-01') AND date('2009-12-31') LIMIT 5 */console.log("db query results", await db.run(query2));/**db query results [{"AVG(\"Total\")":6.632999999999998}] */// -------------// You can see a LangSmith trace of the above chain here:// https://smith.langchain.com/public/e21d6146-eca9-4de6-a078-808fd09979ea/r// ------------- #### API Reference: * [StringOutputParser](https://v02.api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers` * [ChatPromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts` * [PromptTemplate](https://v02.api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts` * [RunnableSequence](https://v02.api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables` * [ChatOpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai` * [createSqlQueryChain](https://v02.api.js.langchain.com/functions/langchain_chains_sql_db.createSqlQueryChain.html) from `langchain/chains/sql_db` * [SqlDatabase](https://v02.api.js.langchain.com/classes/langchain_sql_db.SqlDatabase.html) from `langchain/sql_db` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned about some strategies to validate generated SQL queries. Next, check out some of the other guides in this section, like [how to query over large databases](/v0.2/docs/how_to/sql_large_db). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use prompting to improve results ](/v0.2/docs/how_to/sql_prompting)[ Next How to stream agent data to the client ](/v0.2/docs/how_to/stream_agent_client) * [Setup](#setup) * [Query checker](#query-checker) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/qa_chat_history
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Conversational RAG On this page Conversational RAG ================== Prerequisites This guide assumes familiarity with the following concepts: * [Chat history](/v0.2/docs/concepts/#chat-history) * [Chat models](/v0.2/docs/concepts/#chat-models) * [Embeddings](/v0.2/docs/concepts/#embedding-models) * [Vector stores](/v0.2/docs/concepts/#vector-stores) * [Retrieval-augmented generation](/v0.2/docs/tutorials/rag/) * [Tools](/v0.2/docs/concepts/#tools) * [Agents](/v0.2/docs/concepts/#agents) In many Q&A applications we want to allow the user to have a back-and-forth conversation, meaning the application needs some sort of “memory” of past questions and answers, and some logic for incorporating those into its current thinking. In this guide we focus on **adding logic for incorporating historical messages.** Further details on chat history management is [covered here](/v0.2/docs/how_to/message_history). We will cover two approaches: 1. Chains, in which we always execute a retrieval step; 2. Agents, in which we give an LLM discretion over whether and how to execute a retrieval step (or multiple steps). For the external knowledge source, we will use the same [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) blog post by Lilian Weng from the [RAG tutorial](/v0.2/docs/tutorials/rag). Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Dependencies[​](#dependencies "Direct link to Dependencies") We’ll use an OpenAI chat model and embeddings and a Memory vector store in this walkthrough, but everything shown here works with any [ChatModel](/v0.2/docs/concepts/#chat-models) or [LLM](/v0.2/docs/concepts#llms), [Embeddings](/v0.2/docs/concepts#embedding-models), and [VectorStore](/v0.2/docs/concepts#vectorstores) or [Retriever](/v0.2/docs/concepts#retrievers). We’ll use the following packages: npm install --save langchain @langchain/openai cheerio We need to set environment variable `OPENAI_API_KEY`: export OPENAI_API_KEY=YOUR_KEY ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com/). Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=YOUR_KEY ### Initial setup[​](#initial-setup "Direct link to Initial setup") import "cheerio";import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { pull } from "langchain/hub";import { ChatPromptTemplate } from "@langchain/core/prompts";import { RunnableSequence, RunnablePassthrough,} from "@langchain/core/runnables";import { StringOutputParser } from "@langchain/core/output_parsers"; import { createStuffDocumentsChain } from "langchain/chains/combine_documents";const loader = new CheerioWebBaseLoader( "https://lilianweng.github.io/posts/2023-06-23-agent/");const docs = await loader.load();const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const splits = await textSplitter.splitDocuments(docs);const vectorStore = await MemoryVectorStore.fromDocuments( splits, new OpenAIEmbeddings());// Retrieve and generate using the relevant snippets of the blog.const retriever = vectorStore.asRetriever();const prompt = await pull<ChatPromptTemplate>("rlm/rag-prompt");const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const ragChain = await createStuffDocumentsChain({ llm, prompt, outputParser: new StringOutputParser(),}); Let’s see what this prompt actually looks like: console.log(prompt.promptMessages.map((msg) => msg.prompt.template).join("\n")); You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.Question: {question}Context: {context}Answer: await ragChain.invoke({ context: await retriever.invoke("What is Task Decomposition?"), question: "What is Task Decomposition?",}); "Task decomposition is a technique used to break down complex tasks into smaller and simpler steps. I"... 208 more characters Contextualizing the question[​](#contextualizing-the-question "Direct link to Contextualizing the question") ------------------------------------------------------------------------------------------------------------ First we’ll need to define a sub-chain that takes historical messages and the latest user question, and reformulates the question if it makes reference to any information in the historical information. We’ll use a prompt that includes a `MessagesPlaceholder` variable under the name “chat\_history”. This allows us to pass in a list of Messages to the prompt using the “chat\_history” input key, and these messages will be inserted after the system message and before the human message containing the latest question. import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";const contextualizeQSystemPrompt = `Given a chat history and the latest user questionwhich might reference context in the chat history, formulate a standalone questionwhich can be understood without the chat history. Do NOT answer the question,just reformulate it if needed and otherwise return it as is.`;const contextualizeQPrompt = ChatPromptTemplate.fromMessages([ ["system", contextualizeQSystemPrompt], new MessagesPlaceholder("chat_history"), ["human", "{question}"],]);const contextualizeQChain = contextualizeQPrompt .pipe(llm) .pipe(new StringOutputParser()); Using this chain we can ask follow-up questions that reference past messages and have them reformulated into standalone questions: import { AIMessage, HumanMessage } from "@langchain/core/messages";await contextualizeQChain.invoke({ chat_history: [ new HumanMessage("What does LLM stand for?"), new AIMessage("Large language model"), ], question: "What is meant by large",}); 'What is the definition of "large" in the context of a language model?' Chain with chat history[​](#chain-with-chat-history "Direct link to Chain with chat history") --------------------------------------------------------------------------------------------- And now we can build our full QA chain. Notice we add some routing functionality to only run the “condense question chain” when our chat history isn’t empty. Here we’re taking advantage of the fact that if a function in an LCEL chain returns another chain, that chain will itself be invoked. import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { formatDocumentsAsString } from "langchain/util/document";const qaSystemPrompt = `You are an assistant for question-answering tasks.Use the following pieces of retrieved context to answer the question.If you don't know the answer, just say that you don't know.Use three sentences maximum and keep the answer concise.{context}`;const qaPrompt = ChatPromptTemplate.fromMessages([ ["system", qaSystemPrompt], new MessagesPlaceholder("chat_history"), ["human", "{question}"],]);const contextualizedQuestion = (input: Record<string, unknown>) => { if ("chat_history" in input) { return contextualizeQChain; } return input.question;};const ragChain = RunnableSequence.from([ RunnablePassthrough.assign({ context: (input: Record<string, unknown>) => { if ("chat_history" in input) { const chain = contextualizedQuestion(input); return chain.pipe(retriever).pipe(formatDocumentsAsString); } return ""; }, }), qaPrompt, llm,]); let chat_history = [];const question = "What is task decomposition?";const aiMsg = await ragChain.invoke({ question, chat_history });console.log(aiMsg);chat_history = chat_history.concat(aiMsg);const secondQuestion = "What are common ways of doing it?";await ragChain.invoke({ question: secondQuestion, chat_history }); AIMessage { lc_serializable: true, lc_kwargs: { content: "Task decomposition is a technique used to break down complex tasks into smaller and more manageable "... 278 more characters, additional_kwargs: { function_call: undefined, tool_calls: undefined } }, lc_namespace: [ "langchain_core", "messages" ], content: "Task decomposition is a technique used to break down complex tasks into smaller and more manageable "... 278 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }} AIMessage { lc_serializable: true, lc_kwargs: { content: "Common ways of task decomposition include using prompting techniques like Chain of Thought (CoT) or "... 332 more characters, additional_kwargs: { function_call: undefined, tool_calls: undefined } }, lc_namespace: [ "langchain_core", "messages" ], content: "Common ways of task decomposition include using prompting techniques like Chain of Thought (CoT) or "... 332 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }} See the first [LastSmith trace here](https://smith.langchain.com/public/527981c6-5018-4b68-a11a-ebcde77843e7/r) and the [second trace here](https://smith.langchain.com/public/7b97994a-ab9f-4bf3-a2e4-abb609e5610a/r) Here we’ve gone over how to add application logic for incorporating historical outputs, but we’re still manually updating the chat history and inserting it into each input. In a real Q&A application we’ll want some way of persisting chat history and some way of automatically inserting and updating it. For this we can use: * [BaseChatMessageHistory](https://v02.api.js.langchain.com/classes/langchain_core_chat_history.BaseChatMessageHistory.html): Store chat history. * [RunnableWithMessageHistory](/v0.2/docs/how_to/message_history/): Wrapper for an LCEL chain and a `BaseChatMessageHistory` that handles injecting chat history into inputs and updating it after each invocation. For a detailed walkthrough of how to use these classes together to create a stateful conversational chain, head to the [How to add message history (memory)](/v0.2/docs/how_to/message_history/) LCEL page. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build a PDF ingestion and Question/Answering system ](/v0.2/docs/tutorials/pdf_qa)[ Next Build a Query Analysis System ](/v0.2/docs/tutorials/query_analysis) * [Setup](#setup) * [Dependencies](#dependencies) * [LangSmith](#langsmith) * [Initial setup](#initial-setup) * [Contextualizing the question](#contextualizing-the-question) * [Chain with chat history](#chain-with-chat-history)
null
https://js.langchain.com/v0.2/docs/tutorials/rag
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build a Retrieval Augmented Generation (RAG) App On this page Build a Retrieval Augmented Generation (RAG) App ================================================ One of the most powerful applications enabled by LLMs is sophisticated question-answering (Q&A) chatbots. These are applications that can answer questions about specific source information. These applications use a technique known as Retrieval Augmented Generation, or RAG. This tutorial will show how to build a simple Q&A application over a text data source. Along the way we’ll go over a typical Q&A architecture and highlight additional resources for more advanced Q&A techniques. We’ll also see how LangSmith can help us trace and understand our application. LangSmith will become increasingly helpful as our application grows in complexity. If you’re already familiar with basic retrieval, you might also be interested in this [high-level overview of different retrieval techinques](/v0.2/docs/concepts/#retrieval). What is RAG?[​](#what-is-rag "Direct link to What is RAG?") ----------------------------------------------------------- RAG is a technique for augmenting LLM knowledge with additional data. LLMs can reason about wide-ranging topics, but their knowledge is limited to the public data up to a specific point in time that they were trained on. If you want to build AI applications that can reason about private data or data introduced after a model’s cutoff date, you need to augment the knowledge of the model with the specific information it needs. The process of bringing the appropriate information and inserting it into the model prompt is known as Retrieval Augmented Generation (RAG). LangChain has a number of components designed to help build Q&A applications, and RAG applications more generally. **Note**: Here we focus on Q&A for unstructured data. If you are interested for RAG over structured data, check out our tutorial on doing [question/answering over SQL data](/v0.2/docs/tutorials/sql_qa). Concepts[​](#concepts "Direct link to Concepts") ------------------------------------------------ A typical RAG application has two main components: **Indexing**: a pipeline for ingesting data from a source and indexing it. _This usually happens offline._ **Retrieval and generation**: the actual RAG chain, which takes the user query at run time and retrieves the relevant data from the index, then passes that to the model. The most common full sequence from raw data to answer looks like: ### Indexing[​](#indexing "Direct link to Indexing") 1. **Load**: First we need to load our data. This is done with [Document Loaders](/v0.2/docs/concepts/#document-loaders). 2. **Split**: [Text splitters](/v0.2/docs/concepts/#text-splitters) break large `Documents` into smaller chunks. This is useful both for indexing data and for passing it in to a model, since large chunks are harder to search over and won’t fit in a model’s finite context window. 3. **Store**: We need somewhere to store and index our splits, so that they can later be searched over. This is often done using a [VectorStore](/v0.2/docs/concepts/#vectorstores) and [Embeddings](/v0.2/docs/concepts/#embedding-models) model. ![index_diagram](/v0.2/assets/images/rag_indexing-8160f90a90a33253d0154659cf7d453f.png) ### Retrieval and generation[​](#retrieval-and-generation "Direct link to Retrieval and generation") 1. **Retrieve**: Given a user input, relevant splits are retrieved from storage using a [Retriever](/v0.2/docs/concepts/#retrievers). 2. **Generate**: A [ChatModel](/v0.2/docs/concepts/#chat-models) / [LLM](/v0.2/docs/concepts/#llms) produces an answer using a prompt that includes the question and the retrieved data ![retrieval_diagram](/v0.2/assets/images/rag_retrieval_generation-1046a4668d6bb08786ef73c56d4f228a.png) Setup[​](#setup "Direct link to Setup") --------------------------------------- ### Installation[​](#installation "Direct link to Installation") To install LangChain run: `bash npm2yarn npm i langchain` For more details, see our [Installation guide](/v0.2/docs/how_to/installation). ### LangSmith[​](#langsmith "Direct link to LangSmith") Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com). After you sign up at the link above, make sure to set your environment variables to start logging traces: export LANGCHAIN_TRACING_V2="true"export LANGCHAIN_API_KEY="..." ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); Preview[​](#preview "Direct link to Preview") --------------------------------------------- In this guide we’ll build a QA app over the [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) blog post by Lilian Weng, which allows us to ask questions about the contents of the post. We can create a simple indexing pipeline and RAG chain to do this in only a few lines of code: import "cheerio";import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { pull } from "langchain/hub";import { ChatPromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers"; import { createStuffDocumentsChain } from "langchain/chains/combine_documents";const loader = new CheerioWebBaseLoader( "https://lilianweng.github.io/posts/2023-06-23-agent/");const docs = await loader.load();const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const splits = await textSplitter.splitDocuments(docs);const vectorStore = await MemoryVectorStore.fromDocuments( splits, new OpenAIEmbeddings());// Retrieve and generate using the relevant snippets of the blog.const retriever = vectorStore.asRetriever();const prompt = await pull<ChatPromptTemplate>("rlm/rag-prompt");const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const ragChain = await createStuffDocumentsChain({ llm, prompt, outputParser: new StringOutputParser(),});const retrievedDocs = await retriever.invoke("what is task decomposition"); Let’s see what this prompt actually looks like: console.log(prompt.promptMessages.map((msg) => msg.prompt.template).join("\n")); You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.Question: {question}Context: {context}Answer: await ragChain.invoke({ question: "What is task decomposition?", context: retrievedDocs,}); "Task decomposition is a technique used to break down complex tasks into smaller and simpler steps. I"... 259 more characters Checkout [this LangSmith trace](https://smith.langchain.com/public/54cffec3-5c26-477d-b56d-ebb66a254c8e/r) of the chain above. You can also construct the RAG chain above in a more declarative way using a `RunnableSequence`. `createStuffDocumentsChain` is basically a wrapper around `RunnableSequence`, so for more complex chains and customizability, you can use `RunnableSequence` directly. import { formatDocumentsAsString } from "langchain/util/document";import { RunnableSequence, RunnablePassthrough,} from "@langchain/core/runnables";const declarativeRagChain = RunnableSequence.from([ { context: retriever.pipe(formatDocumentsAsString), question: new RunnablePassthrough(), }, prompt, llm, new StringOutputParser(),]); await declarativeRagChain.invoke("What is task decomposition?"); "Task decomposition is a technique used to break down complex tasks into smaller and simpler steps. I"... 208 more characters LangSmith [trace](https://smith.langchain.com/public/c48e186c-c9da-4694-adf2-3a7c94362ec2/r). Detailed walkthrough[​](#detailed-walkthrough "Direct link to Detailed walkthrough") ------------------------------------------------------------------------------------ Let’s go through the above code step-by-step to really understand what’s going on. 1\. Indexing: Load[​](#indexing-load "Direct link to 1. Indexing: Load") ------------------------------------------------------------------------ We need to first load the blog post contents. We can use [DocumentLoaders](/v0.2/docs/concepts#document-loaders) for this, which are objects that load in data from a source and return a list of [Documents](https://v02.api.js.langchain.com/classes/langchain_core_documents.Document.html). A Document is an object with some pageContent (`string`) and metadata (`Record<string, any>`). In this case we’ll use the [CheerioWebBaseLoader](https://v02.api.js.langchain.com/classes/langchain_document_loaders_web_cheerio.CheerioWebBaseLoader.html), which uses cheerio to load HTML form web URLs and parse it to text. We can pass custom selectors to the constructor to only parse specific elements: const pTagSelector = "p";const loader = new CheerioWebBaseLoader( "https://lilianweng.github.io/posts/2023-06-23-agent/", { selector: pTagSelector, });const docs = await loader.load();console.log(docs[0].pageContent.length); 22054 console.log(docs[0].pageContent); Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.In a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:A complicated task usually involves many steps. An agent needs to know what they are and plan ahead.Chain of thought (CoT; Wei et al. 2022) has become a standard prompting technique for enhancing model performance on complex tasks. The model is instructed to “think step by step” to utilize more test-time computation to decompose hard tasks into smaller and simpler steps. CoT transforms big tasks into multiple manageable tasks and shed lights into an interpretation of the model’s thinking process.Tree of Thoughts (Yao et al. 2023) extends CoT by exploring multiple reasoning possibilities at each step. It first decomposes the problem into multiple thought steps and generates multiple thoughts per step, creating a tree structure. The search process can be BFS (breadth-first search) or DFS (depth-first search) with each state evaluated by a classifier (via a prompt) or majority vote.Task decomposition can be done (1) by LLM with simple prompting like "Steps for XYZ.\n1.", "What are the subgoals for achieving XYZ?", (2) by using task-specific instructions; e.g. "Write a story outline." for writing a novel, or (3) with human inputs.Another quite distinct approach, LLM+P (Liu et al. 2023), involves relying on an external classical planner to do long-horizon planning. This approach utilizes the Planning Domain Definition Language (PDDL) as an intermediate interface to describe the planning problem. In this process, LLM (1) translates the problem into “Problem PDDL”, then (2) requests a classical planner to generate a PDDL plan based on an existing “Domain PDDL”, and finally (3) translates the PDDL plan back into natural language. Essentially, the planning step is outsourced to an external tool, assuming the availability of domain-specific PDDL and a suitable planner which is common in certain robotic setups but not in many other domains.Self-reflection is a vital aspect that allows autonomous agents to improve iteratively by refining past action decisions and correcting previous mistakes. It plays a crucial role in real-world tasks where trial and error are inevitable.ReAct (Yao et al. 2023) integrates reasoning and acting within LLM by extending the action space to be a combination of task-specific discrete actions and the language space. The former enables LLM to interact with the environment (e.g. use Wikipedia search API), while the latter prompting LLM to generate reasoning traces in natural language.The ReAct prompt template incorporates explicit steps for LLM to think, roughly formatted as:In both experiments on knowledge-intensive tasks and decision-making tasks, ReAct works better than the Act-only baseline where Thought: … step is removed.Reflexion (Shinn & Labash 2023) is a framework to equips agents with dynamic memory and self-reflection capabilities to improve reasoning skills. Reflexion has a standard RL setup, in which the reward model provides a simple binary reward and the action space follows the setup in ReAct where the task-specific action space is augmented with language to enable complex reasoning steps. After each action $a_t$, the agent computes a heuristic $h_t$ and optionally may decide to reset the environment to start a new trial depending on the self-reflection results.The heuristic function determines when the trajectory is inefficient or contains hallucination and should be stopped. Inefficient planning refers to trajectories that take too long without success. Hallucination is defined as encountering a sequence of consecutive identical actions that lead to the same observation in the environment.Self-reflection is created by showing two-shot examples to LLM and each example is a pair of (failed trajectory, ideal reflection for guiding future changes in the plan). Then reflections are added into the agent’s working memory, up to three, to be used as context for querying LLM.Chain of Hindsight (CoH; Liu et al. 2023) encourages the model to improve on its own outputs by explicitly presenting it with a sequence of past outputs, each annotated with feedback. Human feedback data is a collection of $D_h = \{(x, y_i , r_i , z_i)\}_{i=1}^n$, where $x$ is the prompt, each $y_i$ is a model completion, $r_i$ is the human rating of $y_i$, and $z_i$ is the corresponding human-provided hindsight feedback. Assume the feedback tuples are ranked by reward, $r_n \geq r_{n-1} \geq \dots \geq r_1$ The process is supervised fine-tuning where the data is a sequence in the form of $\tau_h = (x, z_i, y_i, z_j, y_j, \dots, z_n, y_n)$, where $\leq i \leq j \leq n$. The model is finetuned to only predict $y_n$ where conditioned on the sequence prefix, such that the model can self-reflect to produce better output based on the feedback sequence. The model can optionally receive multiple rounds of instructions with human annotators at test time.To avoid overfitting, CoH adds a regularization term to maximize the log-likelihood of the pre-training dataset. To avoid shortcutting and copying (because there are many common words in feedback sequences), they randomly mask 0% - 5% of past tokens during training.The training dataset in their experiments is a combination of WebGPT comparisons, summarization from human feedback and human preference dataset.The idea of CoH is to present a history of sequentially improved outputs in context and train the model to take on the trend to produce better outputs. Algorithm Distillation (AD; Laskin et al. 2023) applies the same idea to cross-episode trajectories in reinforcement learning tasks, where an algorithm is encapsulated in a long history-conditioned policy. Considering that an agent interacts with the environment many times and in each episode the agent gets a little better, AD concatenates this learning history and feeds that into the model. Hence we should expect the next predicted action to lead to better performance than previous trials. The goal is to learn the process of RL instead of training a task-specific policy itself.The paper hypothesizes that any algorithm that generates a set of learning histories can be distilled into a neural network by performing behavioral cloning over actions. The history data is generated by a set of source policies, each trained for a specific task. At the training stage, during each RL run, a random task is sampled and a subsequence of multi-episode history is used for training, such that the learned policy is task-agnostic.In reality, the model has limited context window length, so episodes should be short enough to construct multi-episode history. Multi-episodic contexts of 2-4 episodes are necessary to learn a near-optimal in-context RL algorithm. The emergence of in-context RL requires long enough context.In comparison with three baselines, including ED (expert distillation, behavior cloning with expert trajectories instead of learning history), source policy (used for generating trajectories for distillation by UCB), RL^2 (Duan et al. 2017; used as upper bound since it needs online RL), AD demonstrates in-context RL with performance getting close to RL^2 despite only using offline RL and learns much faster than other baselines. When conditioned on partial training history of the source policy, AD also improves much faster than ED baseline.(Big thank you to ChatGPT for helping me draft this section. I’ve learned a lot about the human brain and data structure for fast MIPS in my conversations with ChatGPT.)Memory can be defined as the processes used to acquire, store, retain, and later retrieve information. There are several types of memory in human brains.Sensory Memory: This is the earliest stage of memory, providing the ability to retain impressions of sensory information (visual, auditory, etc) after the original stimuli have ended. Sensory memory typically only lasts for up to a few seconds. Subcategories include iconic memory (visual), echoic memory (auditory), and haptic memory (touch).Short-Term Memory (STM) or Working Memory: It stores information that we are currently aware of and needed to carry out complex cognitive tasks such as learning and reasoning. Short-term memory is believed to have the capacity of about 7 items (Miller 1956) and lasts for 20-30 seconds.Long-Term Memory (LTM): Long-term memory can store information for a remarkably long time, ranging from a few days to decades, with an essentially unlimited storage capacity. There are two subtypes of LTM:We can roughly consider the following mappings:The external memory can alleviate the restriction of finite attention span. A standard practice is to save the embedding representation of information into a vector store database that can support fast maximum inner-product search (MIPS). To optimize the retrieval speed, the common choice is the approximate nearest neighbors (ANN)​ algorithm to return approximately top k nearest neighbors to trade off a little accuracy lost for a huge speedup.A couple common choices of ANN algorithms for fast MIPS:Check more MIPS algorithms and performance comparison in ann-benchmarks.com.Tool use is a remarkable and distinguishing characteristic of human beings. We create, modify and utilize external objects to do things that go beyond our physical and cognitive limits. Equipping LLMs with external tools can significantly extend the model capabilities.MRKL (Karpas et al. 2022), short for “Modular Reasoning, Knowledge and Language”, is a neuro-symbolic architecture for autonomous agents. A MRKL system is proposed to contain a collection of “expert” modules and the general-purpose LLM works as a router to route inquiries to the best suitable expert module. These modules can be neural (e.g. deep learning models) or symbolic (e.g. math calculator, currency converter, weather API).They did an experiment on fine-tuning LLM to call a calculator, using arithmetic as a test case. Their experiments showed that it was harder to solve verbal math problems than explicitly stated math problems because LLMs (7B Jurassic1-large model) failed to extract the right arguments for the basic arithmetic reliably. The results highlight when the external symbolic tools can work reliably, knowing when to and how to use the tools are crucial, determined by the LLM capability.Both TALM (Tool Augmented Language Models; Parisi et al. 2022) and Toolformer (Schick et al. 2023) fine-tune a LM to learn to use external tool APIs. The dataset is expanded based on whether a newly added API call annotation can improve the quality of model outputs. See more details in the “External APIs” section of Prompt Engineering.ChatGPT Plugins and OpenAI API function calling are good examples of LLMs augmented with tool use capability working in practice. The collection of tool APIs can be provided by other developers (as in Plugins) or self-defined (as in function calls).HuggingGPT (Shen et al. 2023) is a framework to use ChatGPT as the task planner to select models available in HuggingFace platform according to the model descriptions and summarize the response based on the execution results.The system comprises of 4 stages:(1) Task planning: LLM works as the brain and parses the user requests into multiple tasks. There are four attributes associated with each task: task type, ID, dependencies, and arguments. They use few-shot examples to guide LLM to do task parsing and planning.Instruction:(2) Model selection: LLM distributes the tasks to expert models, where the request is framed as a multiple-choice question. LLM is presented with a list of models to choose from. Due to the limited context length, task type based filtration is needed.Instruction:(3) Task execution: Expert models execute on the specific tasks and log results.Instruction:(4) Response generation: LLM receives the execution results and provides summarized results to users.To put HuggingGPT into real world usage, a couple challenges need to solve: (1) Efficiency improvement is needed as both LLM inference rounds and interactions with other models slow down the process; (2) It relies on a long context window to communicate over complicated task content; (3) Stability improvement of LLM outputs and external model services.API-Bank (Li et al. 2023) is a benchmark for evaluating the performance of tool-augmented LLMs. It contains 53 commonly used API tools, a complete tool-augmented LLM workflow, and 264 annotated dialogues that involve 568 API calls. The selection of APIs is quite diverse, including search engines, calculator, calendar queries, smart home control, schedule management, health data management, account authentication workflow and more. Because there are a large number of APIs, LLM first has access to API search engine to find the right API to call and then uses the corresponding documentation to make a call.In the API-Bank workflow, LLMs need to make a couple of decisions and at each step we can evaluate how accurate that decision is. Decisions include:This benchmark evaluates the agent’s tool use capabilities at three levels:ChemCrow (Bran et al. 2023) is a domain-specific example in which LLM is augmented with 13 expert-designed tools to accomplish tasks across organic synthesis, drug discovery, and materials design. The workflow, implemented in LangChain, reflects what was previously described in the ReAct and MRKLs and combines CoT reasoning with tools relevant to the tasks:One interesting observation is that while the LLM-based evaluation concluded that GPT-4 and ChemCrow perform nearly equivalently, human evaluations with experts oriented towards the completion and chemical correctness of the solutions showed that ChemCrow outperforms GPT-4 by a large margin. This indicates a potential problem with using LLM to evaluate its own performance on domains that requires deep expertise. The lack of expertise may cause LLMs not knowing its flaws and thus cannot well judge the correctness of task results.Boiko et al. (2023) also looked into LLM-empowered agents for scientific discovery, to handle autonomous design, planning, and performance of complex scientific experiments. This agent can use tools to browse the Internet, read documentation, execute code, call robotics experimentation APIs and leverage other LLMs.For example, when requested to "develop a novel anticancer drug", the model came up with the following reasoning steps:They also discussed the risks, especially with illicit drugs and bioweapons. They developed a test set containing a list of known chemical weapon agents and asked the agent to synthesize them. 4 out of 11 requests (36%) were accepted to obtain a synthesis solution and the agent attempted to consult documentation to execute the procedure. 7 out of 11 were rejected and among these 7 rejected cases, 5 happened after a Web search while 2 were rejected based on prompt only.Generative Agents (Park, et al. 2023) is super fun experiment where 25 virtual characters, each controlled by a LLM-powered agent, are living and interacting in a sandbox environment, inspired by The Sims. Generative agents create believable simulacra of human behavior for interactive applications.The design of generative agents combines LLM with memory, planning and reflection mechanisms to enable agents to behave conditioned on past experience, as well as to interact with other agents.This fun simulation results in emergent social behavior, such as information diffusion, relationship memory (e.g. two agents continuing the conversation topic) and coordination of social events (e.g. host a party and invite many others).AutoGPT has drawn a lot of attention into the possibility of setting up autonomous agents with LLM as the main controller. It has quite a lot of reliability issues given the natural language interface, but nevertheless a cool proof-of-concept demo. A lot of code in AutoGPT is about format parsing.Here is the system message used by AutoGPT, where {{...}} are user inputs:GPT-Engineer is another project to create a whole repository of code given a task specified in natural language. The GPT-Engineer is instructed to think over a list of smaller components to build and ask for user input to clarify questions as needed.Here are a sample conversation for task clarification sent to OpenAI ChatCompletion endpoint used by GPT-Engineer. The user inputs are wrapped in {{user input text}}.Then after these clarification, the agent moved into the code writing mode with a different system message.System message:Think step by step and reason yourself to the right decisions to make sure we get it right.You will first lay out the names of the core classes, functions, methods that will be necessary, as well as a quick comment on their purpose.Then you will output the content of each file including ALL code.Each file must strictly follow a markdown code block format, where the following tokens must be replaced such thatFILENAME is the lowercase file name including the file extension,LANG is the markup code block language for the code’s language, and CODE is the code:FILENAMEYou will start with the “entrypoint” file, then go to the ones that are imported by that file, and so on.Please note that the code should be fully functional. No placeholders.Follow a language and framework appropriate best practice file naming convention.Make sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other.Ensure to implement all code, if you are unsure, write a plausible implementation.Include module dependency or package manager dependency definition file.Before you finish, double check that all parts of the architecture is present in the files.Useful to know:You almost always put different classes in different files.For Python, you always create an appropriate requirements.txt file.For NodeJS, you always create an appropriate package.json file.You always add a comment briefly describing the purpose of the function definition.You try to add comments explaining very complex bits of logic.You always follow the best practices for the requested languages in terms of describing the code written as a definedpackage/project.Python toolbelt preferences:Conversatin samples:After going through key ideas and demos of building LLM-centered agents, I start to see a couple common limitations:Finite context length: The restricted context capacity limits the inclusion of historical information, detailed instructions, API call context, and responses. The design of the system has to work with this limited communication bandwidth, while mechanisms like self-reflection to learn from past mistakes would benefit a lot from long or infinite context windows. Although vector stores and retrieval can provide access to a larger knowledge pool, their representation power is not as powerful as full attention.Challenges in long-term planning and task decomposition: Planning over a lengthy history and effectively exploring the solution space remain challenging. LLMs struggle to adjust plans when faced with unexpected errors, making them less robust compared to humans who learn from trial and error.Reliability of natural language interface: Current agent system relies on natural language as an interface between LLMs and external components such as memory and tools. However, the reliability of model outputs is questionable, as LLMs may make formatting errors and occasionally exhibit rebellious behavior (e.g. refuse to follow an instruction). Consequently, much of the agent demo code focuses on parsing model output.Cited as:Weng, Lilian. (Jun 2023). LLM-powered Autonomous Agents". Lil’Log. https://lilianweng.github.io/posts/2023-06-23-agent/.Or[1] Wei et al. “Chain of thought prompting elicits reasoning in large language models.” NeurIPS 2022[2] Yao et al. “Tree of Thoughts: Dliberate Problem Solving with Large Language Models.” arXiv preprint arXiv:2305.10601 (2023).[3] Liu et al. “Chain of Hindsight Aligns Language Models with Feedback“ arXiv preprint arXiv:2302.02676 (2023).[4] Liu et al. “LLM+P: Empowering Large Language Models with Optimal Planning Proficiency” arXiv preprint arXiv:2304.11477 (2023).[5] Yao et al. “ReAct: Synergizing reasoning and acting in language models.” ICLR 2023.[6] Google Blog. “Announcing ScaNN: Efficient Vector Similarity Search” July 28, 2020.[7] https://chat.openai.com/share/46ff149e-a4c7-4dd7-a800-fc4a642ea389[8] Shinn & Labash. “Reflexion: an autonomous agent with dynamic memory and self-reflection” arXiv preprint arXiv:2303.11366 (2023).[9] Laskin et al. “In-context Reinforcement Learning with Algorithm Distillation” ICLR 2023.[10] Karpas et al. “MRKL Systems A modular, neuro-symbolic architecture that combines large language models, external knowledge sources and discrete reasoning.” arXiv preprint arXiv:2205.00445 (2022).[11] Weaviate Blog. Why is Vector Search so fast? Sep 13, 2022.[12] Li et al. “API-Bank: A Benchmark for Tool-Augmented LLMs” arXiv preprint arXiv:2304.08244 (2023).[13] Shen et al. “HuggingGPT: Solving AI Tasks with ChatGPT and its Friends in HuggingFace” arXiv preprint arXiv:2303.17580 (2023).[14] Bran et al. “ChemCrow: Augmenting large-language models with chemistry tools.” arXiv preprint arXiv:2304.05376 (2023).[15] Boiko et al. “Emergent autonomous scientific research capabilities of large language models.” arXiv preprint arXiv:2304.05332 (2023).[16] Joon Sung Park, et al. “Generative Agents: Interactive Simulacra of Human Behavior.” arXiv preprint arXiv:2304.03442 (2023).[17] AutoGPT. https://github.com/Significant-Gravitas/Auto-GPT[18] GPT-Engineer. https://github.com/AntonOsika/gpt-engineer ### Go deeper[​](#go-deeper "Direct link to Go deeper") `DocumentLoader`: Class that loads data from a source as list of Documents. - [Docs](/v0.2/docs/concepts#document-loaders): Detailed documentation on how to use `DocumentLoaders`. - [Integrations](/v0.2/docs/integrations/document_loaders/) - [Interface](https://v02.api.js.langchain.com/classes/langchain_document_loaders_base.BaseDocumentLoader.html): API reference for the base interface. 2\. Indexing: Split[​](#indexing-split "Direct link to 2. Indexing: Split") --------------------------------------------------------------------------- Our loaded document is over 42k characters long. This is too long to fit in the context window of many models. Even for those models that could fit the full post in their context window, models can struggle to find information in very long inputs. To handle this we’ll split the `Document` into chunks for embedding and vector storage. This should help us retrieve only the most relevant bits of the blog post at run time. In this case we’ll split our documents into chunks of 1000 characters with 200 characters of overlap between chunks. The overlap helps mitigate the possibility of separating a statement from important context related to it. We use the [RecursiveCharacterTextSplitter](/v0.2/docs/how_to/recursive_text_splitter/), which will recursively split the document using common separators like new lines until each chunk is the appropriate size. This is the recommended text splitter for generic text use cases. const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200,});const allSplits = await textSplitter.splitDocuments(docs); console.log(allSplits.length); 28 console.log(allSplits[0].pageContent.length); 996 allSplits[10].metadata; { source: "https://lilianweng.github.io/posts/2023-06-23-agent/", loc: { lines: { from: 1, to: 1 } }} ### Go deeper[​](#go-deeper-1 "Direct link to Go deeper") `TextSplitter`: Object that splits a list of `Document`s into smaller chunks. Subclass of `DocumentTransformers`. - Explore `Context-aware splitters`, which keep the location (“context”) of each split in the original `Document`: - [Markdown files](/v0.2/docs/how_to/code_splitter/#markdown) - [Code](/v0.2/docs/how_to/code_splitter/) (15+ langs) - [Interface](https://v02.api.js.langchain.com/classes/langchain_textsplitters.TextSplitter.html): API reference for the base interface. `DocumentTransformer`: Object that performs a transformation on a list of `Document`s. - Docs: Detailed documentation on how to use `DocumentTransformer`s - [Integrations](/v0.2/docs/integrations/document_transformers) - [Interface](https://v02.api.js.langchain.com/classes/langchain_core_documents.BaseDocumentTransformer.html): API reference for the base interface. 3\. Indexing: Store[​](#indexing-store "Direct link to 3. Indexing: Store") --------------------------------------------------------------------------- Now we need to index our 28 text chunks so that we can search over them at runtime. The most common way to do this is to embed the contents of each document split and insert these embeddings into a vector database (or vector store). When we want to search over our splits, we take a text search query, embed it, and perform some sort of “similarity” search to identify the stored splits with the most similar embeddings to our query embedding. The simplest similarity measure is cosine similarity — we measure the cosine of the angle between each pair of embeddings (which are high dimensional vectors). We can embed and store all of our document splits in a single command using the [Memory](/v0.2/docs/integrations/vectorstores/memory) vector store and [OpenAIEmbeddings](/v0.2/docs/integrations/text_embedding/openai) model. import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings } from "@langchain/openai";const vectorStore = await MemoryVectorStore.fromDocuments( allSplits, new OpenAIEmbeddings()); ### Go deeper[​](#go-deeper-2 "Direct link to Go deeper") `Embeddings`: Wrapper around a text embedding model, used for converting text to embeddings. - [Docs](/v0.2/docs/concepts#embedding-models): Detailed documentation on how to use embeddings. - [Integrations](/v0.2/docs/integrations/text_embedding): 30+ integrations to choose from. - [Interface](https://v02.api.js.langchain.com/classes/langchain_core_embeddings.Embeddings.html): API reference for the base interface. `VectorStore`: Wrapper around a vector database, used for storing and querying embeddings. - [Docs](/v0.2/docs/concepts#vectorstores): Detailed documentation on how to use vector stores. - [Integrations](/v0.2/docs/integrations/vectorstores): 40+ integrations to choose from. - [Interface](https://v02.api.js.langchain.com/classes/langchain_core_vectorstores.VectorStore.html): API reference for the base interface. This completes the **Indexing** portion of the pipeline. At this point we have a query-able vector store containing the chunked contents of our blog post. Given a user question, we should ideally be able to return the snippets of the blog post that answer the question. 4\. Retrieval and Generation: Retrieve[​](#retrieval-and-generation-retrieve "Direct link to 4. Retrieval and Generation: Retrieve") ------------------------------------------------------------------------------------------------------------------------------------ Now let’s write the actual application logic. We want to create a simple application that takes a user question, searches for documents relevant to that question, passes the retrieved documents and initial question to a model, and returns an answer. First we need to define our logic for searching over documents. LangChain defines a [Retriever](/v0.2/docs/concepts#retrievers) interface which wraps an index that can return relevant `Document`s given a string query. The most common type of Retriever is the [VectorStoreRetriever](https://v02.api.js.langchain.com/classes/langchain_core_vectorstores.VectorStoreRetriever.html), which uses the similarity search capabilities of a vector store to facilitate retrieval. Any `VectorStore` can easily be turned into a `Retriever` with `VectorStore.asRetriever()`: const retriever = vectorStore.asRetriever({ k: 6, searchType: "similarity" }); const retrievedDocs = await retriever.invoke( "What are the approaches to task decomposition?"); console.log(retrievedDocs.length); 6 console.log(retrievedDocs[0].pageContent); hard tasks into smaller and simpler steps. CoT transforms big tasks into multiple manageable tasks and shed lights into an interpretation of the model’s thinking process.Tree of Thoughts (Yao et al. 2023) extends CoT by exploring multiple reasoning possibilities at each step. It first decomposes the problem into multiple thought steps and generates multiple thoughts per step, creating a tree structure. The search process can be BFS (breadth-first search) or DFS (depth-first search) with each state evaluated by a classifier (via a prompt) or majority vote.Task decomposition can be done (1) by LLM with simple prompting like "Steps for XYZ.\n1.", "What are the subgoals for achieving XYZ?", (2) by using task-specific instructions; e.g. "Write a story outline." for writing a novel, or (3) with human inputs.Another quite distinct approach, LLM+P (Liu et al. 2023), involves relying on an external classical planner to do long-horizon planning. This approach utilizes the Planning Domain ### Go deeper[​](#go-deeper-3 "Direct link to Go deeper") Vector stores are commonly used for retrieval, but there are other ways to do retrieval, too. `Retriever`: An object that returns `Document`s given a text query - [Docs](/v0.2/docs/concepts#retrievers): Further documentation on the interface and built-in retrieval techniques. Some of which include: - `MultiQueryRetriever` [generates variants of the input question](/v0.2/docs/how_to/multiple_queries/) to improve retrieval hit rate. - `MultiVectorRetriever` (diagram below) instead generates variants of the embeddings, also in order to improve retrieval hit rate. - Max marginal relevance selects for relevance and diversity among the retrieved documents to avoid passing in duplicate context. - Documents can be filtered during vector store retrieval using metadata filters. - Integrations: Integrations with retrieval services. - Interface: API reference for the base interface. 5\. Retrieval and Generation: Generate[​](#retrieval-and-generation-generate "Direct link to 5. Retrieval and Generation: Generate") ------------------------------------------------------------------------------------------------------------------------------------ Let’s put it all together into a chain that takes a question, retrieves relevant documents, constructs a prompt, passes that to a model, and parses the output. ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); We’ll use a prompt for RAG that is checked into the LangChain prompt hub ([here](https://smith.langchain.com/hub/rlm/rag-prompt?organizationId=9213bdc8-a184-442b-901a-cd86ebf8ca6f)). import { ChatPromptTemplate } from "@langchain/core/prompts";import { pull } from "langchain/hub";const prompt = await pull<ChatPromptTemplate>("rlm/rag-prompt"); const exampleMessages = await prompt.invoke({ context: "filler context", question: "filler question",});exampleMessages; ChatPromptValue { lc_serializable: true, lc_kwargs: { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "You are an assistant for question-answering tasks. Use the following pieces of retrieved context to "... 197 more characters, additional_kwargs: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "You are an assistant for question-answering tasks. Use the following pieces of retrieved context to "... 197 more characters, name: undefined, additional_kwargs: {} } ] }, lc_namespace: [ "langchain_core", "prompt_values" ], messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "You are an assistant for question-answering tasks. Use the following pieces of retrieved context to "... 197 more characters, additional_kwargs: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "You are an assistant for question-answering tasks. Use the following pieces of retrieved context to "... 197 more characters, name: undefined, additional_kwargs: {} } ]} console.log(exampleMessages.messages[0].content); You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.Question: filler questionContext: filler contextAnswer: We’ll use the [LCEL Runnable](/v0.2/docs/how_to/#langchain-expression-language-lcel) protocol to define the chain, allowing us to - pipe together components and functions in a transparent way - automatically trace our chain in LangSmith - get streaming, async, and batched calling out of the box import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import { formatDocumentsAsString } from "langchain/util/document";const ragChain = RunnableSequence.from([ { context: retriever.pipe(formatDocumentsAsString), question: new RunnablePassthrough(), }, prompt, llm, new StringOutputParser(),]); for await (const chunk of await ragChain.stream( "What is task decomposition?")) { console.log(chunk);} Task decomposition is the process of breaking down a complex task into smaller and simpler steps. It allows for easier management and interpretation of the model's thinking process. Different approaches, such as Chain of Thought (CoT) and Tree of Thoughts, can be used to decompose tasks and explore multiple reasoning possibilities at each step. Checkout the LangSmith trace [here](https://smith.langchain.com/public/6f89b333-de55-4ac2-9d93-ea32d41c9e71/r) ### Go deeper[​](#go-deeper-4 "Direct link to Go deeper") #### Choosing a model[​](#choosing-a-model "Direct link to Choosing a model") `ChatModel`: An LLM-backed chat model. Takes in a sequence of messages and returns a message. - [Docs](/v0.2/docs/concepts/#chat-models): Detailed documentation on - [Integrations](/v0.2/docs/integrations/chat/): 25+ integrations to choose from. - [Interface](https://v02.api.js.langchain.com/classes/langchain_core_language_models_chat_models.BaseChatModel.html): API reference for the base interface. `LLM`: A text-in-text-out LLM. Takes in a string and returns a string. - [Docs](/v0.2/docs/concepts#llms) - [Integrations](/v0.2/docs/integrations/llms/): 75+ integrations to choose from. - [Interface](https://v02.api.js.langchain.com/classes/langchain_core_language_models_llms.BaseLLM.html): API reference for the base interface. See a guide on RAG with locally-running models [here](/v0.2/docs/tutorials/local_rag/). #### Customizing the prompt[​](#customizing-the-prompt "Direct link to Customizing the prompt") As shown above, we can load prompts (e.g., [this RAG prompt](https://smith.langchain.com/hub/rlm/rag-prompt?organizationId=9213bdc8-a184-442b-901a-cd86ebf8ca6f)) from the prompt hub. The prompt can also be easily customized: import { PromptTemplate } from "@langchain/core/prompts";import { createStuffDocumentsChain } from "langchain/chains/combine_documents";const template = `Use the following pieces of context to answer the question at the end.If you don't know the answer, just say that you don't know, don't try to make up an answer.Use three sentences maximum and keep the answer as concise as possible.Always say "thanks for asking!" at the end of the answer.{context}Question: {question}Helpful Answer:`;const customRagPrompt = PromptTemplate.fromTemplate(template);const ragChain = await createStuffDocumentsChain({ llm, prompt: customRagPrompt, outputParser: new StringOutputParser(),});const context = await retriever.invoke("what is task decomposition");await ragChain.invoke({ question: "What is Task Decomposition?", context,}); "Task decomposition is a technique used to break down complex tasks into smaller and simpler steps. I"... 336 more characters Checkout the LangSmith trace [here](https://smith.langchain.com/public/47ef2e53-acec-4b74-acdc-e0ea64088279/r) Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ That’s a lot of content we’ve covered in a short amount of time. There’s plenty of features, integrations, and extensions to explore in each of the above sections. Along from the Go deeper sources mentioned above, good next steps include: * [Return sources](/v0.2/docs/how_to/qa_sources/): Learn how to return source documents * [Streaming](/v0.2/docs/how_to/qa_streaming/): Learn how to stream outputs and intermediate steps * [Add chat history](/v0.2/docs/how_to/qa_chat_history_how_to/): Learn how to add chat history to your app * [Retrieval conceptual guide](/v0.2/docs/concepts/#retrieval): A high-level overview of specific retrieval techniques * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build a Query Analysis System ](/v0.2/docs/tutorials/query_analysis)[ Next Build a Question/Answering system over SQL data ](/v0.2/docs/tutorials/sql_qa) * [What is RAG?](#what-is-rag) * [Concepts](#concepts) * [Indexing](#indexing) * [Retrieval and generation](#retrieval-and-generation) * [Setup](#setup) * [Installation](#installation) * [LangSmith](#langsmith) * [Preview](#preview) * [Detailed walkthrough](#detailed-walkthrough) * [1\. Indexing: Load](#indexing-load) * [Go deeper](#go-deeper) * [2\. Indexing: Split](#indexing-split) * [Go deeper](#go-deeper-1) * [3\. Indexing: Store](#indexing-store) * [Go deeper](#go-deeper-2) * [4\. Retrieval and Generation: Retrieve](#retrieval-and-generation-retrieve) * [Go deeper](#go-deeper-3) * [5\. Retrieval and Generation: Generate](#retrieval-and-generation-generate) * [Go deeper](#go-deeper-4) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/tutorials/query_analysis
* [](/v0.2/) * [Tutorials](/v0.2/docs/tutorials/) * Build a Query Analysis System On this page Build a Query Analysis System ============================= Prerequisites This guide assumes familiarity with the following concepts: * [Document loaders](/v0.2/docs/concepts/#document-loaders) * [Chat models](/v0.2/docs/concepts/#chat-models) * [Embeddings](/v0.2/docs/concepts/#embedding-models) * [Vector stores](/v0.2/docs/concepts/#vector-stores) * [Retrieval](/v0.2/docs/concepts/#retrieval) This page will show how to use query analysis in a basic end-to-end example. This will cover creating a simple search engine, showing a failure mode that occurs when passing a raw user question to that search, and then an example of how query analysis can help address that issue. There are MANY different query analysis techniques and this end-to-end example will not show all of them. For the purpose of this example, we will do retrieval over the LangChain YouTube videos. Setup[​](#setup "Direct link to Setup") --------------------------------------- #### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * yarn * pnpm npm i langchain @langchain/community @langchain/openai youtubei.js chromadb youtube-transcript yarn add langchain @langchain/community @langchain/openai youtubei.js chromadb youtube-transcript pnpm add langchain @langchain/community @langchain/openai youtubei.js chromadb youtube-transcript #### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") We’ll use OpenAI in this example: OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true ### Load documents[​](#load-documents "Direct link to Load documents") We can use the `YouTubeLoader` to load transcripts of a few LangChain videos: import { DocumentInterface } from "@langchain/core/documents";import { YoutubeLoader } from "@langchain/community/document_loaders/web/youtube";import { getYear } from "date-fns";const urls = [ "https://www.youtube.com/watch?v=HAn9vnJy6S4", "https://www.youtube.com/watch?v=dA1cHGACXCo", "https://www.youtube.com/watch?v=ZcEMLz27sL4", "https://www.youtube.com/watch?v=hvAPnpSfSGo", "https://www.youtube.com/watch?v=EhlPDL4QrWY", "https://www.youtube.com/watch?v=mmBo8nlu2j0", "https://www.youtube.com/watch?v=rQdibOsL1ps", "https://www.youtube.com/watch?v=28lC4fqukoc", "https://www.youtube.com/watch?v=es-9MgxB-uc", "https://www.youtube.com/watch?v=wLRHwKuKvOE", "https://www.youtube.com/watch?v=ObIltMaRJvY", "https://www.youtube.com/watch?v=DjuXACWYkkU", "https://www.youtube.com/watch?v=o7C9ld6Ln-M",];let docs: Array<DocumentInterface> = [];for await (const url of urls) { const doc = await YoutubeLoader.createFromUrl(url, { language: "en", addVideoInfo: true, }).load(); docs = docs.concat(doc);}console.log(docs.length);/*13 */// Add some additional metadata: what year the video was published// The JS API does not provide publish date, so we can use a// hardcoded array with the dates instead.const dates = [ new Date("Jan 31, 2024"), new Date("Jan 26, 2024"), new Date("Jan 24, 2024"), new Date("Jan 23, 2024"), new Date("Jan 16, 2024"), new Date("Jan 5, 2024"), new Date("Jan 2, 2024"), new Date("Dec 20, 2023"), new Date("Dec 19, 2023"), new Date("Nov 27, 2023"), new Date("Nov 22, 2023"), new Date("Nov 16, 2023"), new Date("Nov 2, 2023"),];docs.forEach((doc, idx) => { // eslint-disable-next-line no-param-reassign doc.metadata.publish_year = getYear(dates[idx]); // eslint-disable-next-line no-param-reassign doc.metadata.publish_date = dates[idx];});// Here are the titles of the videos we've loaded:console.log(docs.map((doc) => doc.metadata.title));/*[ 'OpenGPTs', 'Building a web RAG chatbot: using LangChain, Exa (prev. Metaphor), LangSmith, and Hosted Langserve', 'Streaming Events: Introducing a new `stream_events` method', 'LangGraph: Multi-Agent Workflows', 'Build and Deploy a RAG app with Pinecone Serverless', 'Auto-Prompt Builder (with Hosted LangServe)', 'Build a Full Stack RAG App With TypeScript', 'Getting Started with Multi-Modal LLMs', 'SQL Research Assistant', 'Skeleton-of-Thought: Building a New Template from Scratch', 'Benchmarking RAG over LangChain Docs', 'Building a Research Assistant from Scratch', 'LangServe and LangChain Templates Webinar'] */ #### API Reference: * [DocumentInterface](https://v02.api.js.langchain.com/interfaces/langchain_core_documents.DocumentInterface.html) from `@langchain/core/documents` * [YoutubeLoader](https://v02.api.js.langchain.com/classes/langchain_community_document_loaders_web_youtube.YoutubeLoader.html) from `@langchain/community/document_loaders/web/youtube` Here’s the metadata associated with each video. We can see that each document also has a title, view count, publication date, and length: import { getDocs } from "./docs.js";const docs = await getDocs();console.log(docs[0].metadata);/**{ source: 'HAn9vnJy6S4', description: 'OpenGPTs is an open-source platform aimed at recreating an experience like the GPT Store - but with any model, any tools, and that you can self-host.\n' + '\n' + 'This video covers both how to use it as well as how to build it.\n' + '\n' + 'GitHub: https://github.com/langchain-ai/opengpts', title: 'OpenGPTs', view_count: 7262, author: 'LangChain'} */// And here's a sample from a document's contents:console.log(docs[0].pageContent.slice(0, 500));/*hello today I want to talk about open gpts open gpts is a project that we built here at linkchain uh that replicates the GPT store in a few ways so it creates uh end user-facing friendly interface to create different Bots and these Bots can have access to different tools and they can uh be given files to retrieve things over and basically it's a way to create a variety of bots and expose the configuration of these Bots to end users it's all open source um it can be used with open AI it can be us */ #### API Reference: ### Indexing documents[​](#indexing-documents "Direct link to Indexing documents") Whenever we perform retrieval we need to create an index of documents that we can query. We’ll use a vector store to index our documents, and we’ll chunk them first to make our retrievals more concise and precise: import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { OpenAIEmbeddings } from "@langchain/openai";import { Chroma } from "@langchain/community/vectorstores/chroma";import { getDocs } from "./docs.js";const docs = await getDocs();const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 2000 });const chunkedDocs = await textSplitter.splitDocuments(docs);const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small",});const vectorStore = await Chroma.fromDocuments(chunkedDocs, embeddings, { collectionName: "yt-videos",}); #### API Reference: * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [Chroma](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_chroma.Chroma.html) from `@langchain/community/vectorstores/chroma` Then later, you can retrieve the index without having to re-query and embed: import "chromadb";import { OpenAIEmbeddings } from "@langchain/openai";import { Chroma } from "@langchain/community/vectorstores/chroma";const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small",});const vectorStore = await Chroma.fromExistingCollection(embeddings, { collectionName: "yt-videos",}); [Module: null prototype] { AdminClient: [class AdminClient], ChromaClient: [class ChromaClient], CloudClient: [class CloudClient extends ChromaClient], CohereEmbeddingFunction: [class CohereEmbeddingFunction], Collection: [class Collection], DefaultEmbeddingFunction: [class _DefaultEmbeddingFunction], GoogleGenerativeAiEmbeddingFunction: [class _GoogleGenerativeAiEmbeddingFunction], HuggingFaceEmbeddingServerFunction: [class HuggingFaceEmbeddingServerFunction], IncludeEnum: { Documents: "documents", Embeddings: "embeddings", Metadatas: "metadatas", Distances: "distances" }, JinaEmbeddingFunction: [class JinaEmbeddingFunction], OpenAIEmbeddingFunction: [class _OpenAIEmbeddingFunction], TransformersEmbeddingFunction: [class _TransformersEmbeddingFunction]} Retrieval without query analysis[​](#retrieval-without-query-analysis "Direct link to Retrieval without query analysis") ------------------------------------------------------------------------------------------------------------------------ We can perform similarity search on a user question directly to find chunks relevant to the question: const searchResults = await vectorStore.similaritySearch( "how do I build a RAG agent");console.log(searchResults[0].metadata.title);console.log(searchResults[0].pageContent.slice(0, 500)); OpenGPTshardcoded that it will always do a retrieval step here the assistant decides whether to do a retrieval step or not sometimes this is good sometimes this is bad sometimes it you don't need to do a retrieval step when I said hi it didn't need to call it tool um but other times you know the the llm might mess up and not realize that it needs to do a retrieval step and so the rag bot will always do a retrieval step so it's more focused there because this is also a simpler architecture so it's always This works pretty okay! Our first result is somewhat relevant to the question. What if we wanted to search for results from a specific time period? const searchResults = await vectorStore.similaritySearch( "videos on RAG published in 2023");console.log(searchResults[0].metadata.title);console.log(searchResults[0].metadata.publish_year);console.log(searchResults[0].pageContent.slice(0, 500)); OpenGPTs2024hardcoded that it will always do a retrieval step here the assistant decides whether to do a retrieval step or not sometimes this is good sometimes this is bad sometimes it you don't need to do a retrieval step when I said hi it didn't need to call it tool um but other times you know the the llm might mess up and not realize that it needs to do a retrieval step and so the rag bot will always do a retrieval step so it's more focused there because this is also a simpler architecture so it's always Our first result is from 2024, and not very relevant to the input. Since we’re just searching against document contents, there’s no way for the results to be filtered on any document attributes. This is just one failure mode that can arise. Let’s now take a look at how a basic form of query analysis can fix it! Query analysis[​](#query-analysis "Direct link to Query analysis") ------------------------------------------------------------------ To handle these failure modes we’ll do some query structuring. This will involve defining a **query schema** that contains some date filters and use a function-calling model to convert a user question into a structured queries. ### Query schema[​](#query-schema "Direct link to Query schema") In this case we’ll have explicit min and max attributes for publication date so that it can be filtered on. import { z } from "zod";const searchSchema = z .object({ query: z .string() .describe("Similarity search query applied to video transcripts."), publish_year: z.number().optional().describe("Year of video publication."), }) .describe( "Search over a database of tutorial videos about a software library." ); ### Query generation[​](#query-generation "Direct link to Query generation") To convert user questions to structured queries we’ll make use of OpenAI’s function-calling API. Specifically we’ll use the new [ChatModel.withStructuredOutput()](https://v02.api.js.langchain.com/classes/langchain_core_language_models_base.BaseLanguageModel.html#withStructuredOutput) constructor to handle passing the schema to the model and parsing the output. import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatOpenAI } from "@langchain/openai";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";const system = `You are an expert at converting user questions into database queries.You have access to a database of tutorial videos about a software library for building LLM-powered applications.Given a question, return a list of database queries optimized to retrieve the most relevant results.If there are acronyms or words you are not familiar with, do not try to rephrase them.`;const prompt = ChatPromptTemplate.fromMessages([ ["system", system], ["human", "{question}"],]);const llm = new ChatOpenAI({ model: "gpt-3.5-turbo-0125", temperature: 0,});const structuredLLM = llm.withStructuredOutput(searchSchema, { name: "search",});const queryAnalyzer = RunnableSequence.from([ { question: new RunnablePassthrough(), }, prompt, structuredLLM,]); Let’s see what queries our analyzer generates for the questions we searched earlier: console.log(await queryAnalyzer.invoke("How do I build a rag agent")); { query: "build a rag agent" } console.log(await queryAnalyzer.invoke("videos on RAG published in 2023")); { query: "RAG", publish_year: 2023 } Retrieval with query analysis[​](#retrieval-with-query-analysis "Direct link to Retrieval with query analysis") --------------------------------------------------------------------------------------------------------------- Our query analysis looks pretty good; now let’s try using our generated queries to actually perform retrieval. **Note:** in our example, we specified `tool_choice: "Search"`. This will force the LLM to call one - and only one - function, meaning that we will always have one optimized query to look up. Note that this is not always the case - see other guides for how to deal with situations when no - or multiple - optimized queries are returned. import { DocumentInterface } from "@langchain/core/documents";const retrieval = async (input: { query: string; publish_year?: number;}): Promise<DocumentInterface[]> => { let _filter: Record<string, any> = {}; if (input.publish_year) { // This syntax is specific to Chroma // the vector database we are using. _filter = { publish_year: { $eq: input.publish_year, }, }; } return vectorStore.similaritySearch(input.query, undefined, _filter);}; import { RunnableLambda } from "@langchain/core/runnables";const retrievalChain = queryAnalyzer.pipe( new RunnableLambda({ func: async (input) => retrieval(input as unknown as { query: string; publish_year?: number }), })); We can now run this chain on the problematic input from before, and see that it yields only results from that year! const results = await retrievalChain.invoke("RAG tutorial published in 2023"); console.log( results.map((doc) => ({ title: doc.metadata.title, year: doc.metadata.publish_date, }))); [ { title: "Getting Started with Multi-Modal LLMs", year: "2023-12-20T08:00:00.000Z" }, { title: "LangServe and LangChain Templates Webinar", year: "2023-11-02T07:00:00.000Z" }, { title: "Getting Started with Multi-Modal LLMs", year: "2023-12-20T08:00:00.000Z" }, { title: "Building a Research Assistant from Scratch", year: "2023-11-16T08:00:00.000Z" }] * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Conversational RAG ](/v0.2/docs/tutorials/qa_chat_history)[ Next Build a Retrieval Augmented Generation (RAG) App ](/v0.2/docs/tutorials/rag) * [Setup](#setup) * [Load documents](#load-documents) * [Indexing documents](#indexing-documents) * [Retrieval without query analysis](#retrieval-without-query-analysis) * [Query analysis](#query-analysis) * [Query schema](#query-schema) * [Query generation](#query-generation) * [Retrieval with query analysis](#retrieval-with-query-analysis)
null
https://js.langchain.com/v0.2/docs/how_to/character_text_splitter
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to split by character On this page How to split by character ========================= Prerequisites This guide assumes familiarity with the following concepts: * [Text splitters](/v0.2/docs/concepts#text-splitters) This is the simplest method for splitting text. This splits based on a given character sequence, which defaults to `"\n\n"`. Chunk length is measured by number of characters. 1. How the text is split: by single character separator. 2. How the chunk size is measured: by number of characters. To obtain the string content directly, use `.splitText()`. To create LangChain [Document](https://v02.api.js.langchain.com/classes/langchain_core_documents.Document.html) objects (e.g., for use in downstream tasks), use `.createDocuments()`. import { CharacterTextSplitter } from "@langchain/textsplitters";import * as fs from "node:fs";// Load an example documentconst rawData = await fs.readFileSync( "../../../../examples/state_of_the_union.txt");const stateOfTheUnion = rawData.toString();const textSplitter = new CharacterTextSplitter({ separator: "\n\n", chunkSize: 1000, chunkOverlap: 200,});const texts = await textSplitter.createDocuments([stateOfTheUnion]);console.log(texts[0]); Document { pageContent: "Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and th"... 839 more characters, metadata: { loc: { lines: { from: 1, to: 17 } } }} You can also propagate metadata associated with each document to the output chunks: const metadatas = [{ document: 1 }, { document: 2 }];const documents = await textSplitter.createDocuments( [stateOfTheUnion, stateOfTheUnion], metadatas);console.log(documents[0]); Document { pageContent: "Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and th"... 839 more characters, metadata: { document: 1, loc: { lines: { from: 1, to: 17 } } }} To obtain the string content directly, use `.splitText()`: const chunks = await textSplitter.splitText(stateOfTheUnion);chunks[0]; "Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and th"... 839 more characters Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned a method for splitting text by character. Next, check out a [more advanced way of splitting by character](/v0.2/docs/how_to/recursive_text_splitter), or the [full tutorial on retrieval-augmented generation](/v0.2/docs/tutorials/rag). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to pass callbacks in at runtime ](/v0.2/docs/how_to/callbacks_runtime)[ Next How to manage memory ](/v0.2/docs/how_to/chatbots_memory) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/chatbots_memory
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to manage memory On this page How to manage memory ==================== Prerequisites This guide assumes familiarity with the following: * [Chatbots](/v0.2/docs/tutorials/chatbot) A key feature of chatbots is their ability to use content of previous conversation turns as context. This state management can take several forms, including: * Simply stuffing previous messages into a chat model prompt. * The above, but trimming old messages to reduce the amount of distracting information the model has to deal with. * More complex modifications like synthesizing summaries for long running conversations. We’ll go into more detail on a few techniques below! Setup[​](#setup "Direct link to Setup") --------------------------------------- You’ll need to install a few packages, and set any LLM API keys: Let’s also set up a chat model that we’ll use for the below examples: ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); Message passing[​](#message-passing "Direct link to Message passing") --------------------------------------------------------------------- The simplest form of memory is simply passing chat history messages into a chain. Here’s an example: import { HumanMessage, AIMessage } from "@langchain/core/messages";import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";const prompt = ChatPromptTemplate.fromMessages([ [ "system", "You are a helpful assistant. Answer all questions to the best of your ability.", ], new MessagesPlaceholder("messages"),]);const chain = prompt.pipe(llm);await chain.invoke({ messages: [ new HumanMessage( "Translate this sentence from English to French: I love programming." ), new AIMessage("J'adore la programmation."), new HumanMessage("What did you just say?"), ],}); AIMessage { lc_serializable: true, lc_kwargs: { content: `I said "J'adore la programmation," which means "I love programming" in French.`, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: `I said "J'adore la programmation," which means "I love programming" in French.`, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 21, promptTokens: 61, totalTokens: 82 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} We can see that by passing the previous conversation into a chain, it can use it as context to answer questions. This is the basic concept underpinning chatbot memory - the rest of the guide will demonstrate convenient techniques for passing or reformatting messages. Chat history[​](#chat-history "Direct link to Chat history") ------------------------------------------------------------ It’s perfectly fine to store and pass messages directly as an array, but we can use LangChain’s built-in message history class to store and load messages as well. Instances of this class are responsible for storing and loading chat messages from persistent storage. LangChain integrates with many providers but for this demo we will use an ephemeral demo class. Here’s an example of the API: import { ChatMessageHistory } from "langchain/stores/message/in_memory";const demoEphemeralChatMessageHistory = new ChatMessageHistory();await demoEphemeralChatMessageHistory.addMessage( new HumanMessage( "Translate this sentence from English to French: I love programming." ));await demoEphemeralChatMessageHistory.addMessage( new AIMessage("J'adore la programmation."));await demoEphemeralChatMessageHistory.getMessages(); [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "Translate this sentence from English to French: I love programming.", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Translate this sentence from English to French: I love programming.", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "J'adore la programmation.", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "J'adore la programmation.", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }] We can use it directly to store conversation turns for our chain: await demoEphemeralChatMessageHistory.clear();const input1 = "Translate this sentence from English to French: I love programming.";await demoEphemeralChatMessageHistory.addMessage(new HumanMessage(input1));const response = await chain.invoke({ messages: await demoEphemeralChatMessageHistory.getMessages(),});await demoEphemeralChatMessageHistory.addMessage(response);const input2 = "What did I just ask you?";await demoEphemeralChatMessageHistory.addMessage(new HumanMessage(input2));await chain.invoke({ messages: await demoEphemeralChatMessageHistory.getMessages(),}); AIMessage { lc_serializable: true, lc_kwargs: { content: 'You just asked me to translate the sentence "I love programming" from English to French.', tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: 'You just asked me to translate the sentence "I love programming" from English to French.', name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 18, promptTokens: 73, totalTokens: 91 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} Automatic history management[​](#automatic-history-management "Direct link to Automatic history management") ------------------------------------------------------------------------------------------------------------ The previous examples pass messages to the chain explicitly. This is a completely acceptable approach, but it does require external management of new messages. LangChain also includes an wrapper for LCEL chains that can handle this process automatically called `RunnableWithMessageHistory`. To show how it works, let’s slightly modify the above prompt to take a final `input` variable that populates a `HumanMessage` template after the chat history. This means that we will expect a `chat_history` parameter that contains all messages BEFORE the current messages instead of all messages: const runnableWithMessageHistoryPrompt = ChatPromptTemplate.fromMessages([ [ "system", "You are a helpful assistant. Answer all questions to the best of your ability.", ], new MessagesPlaceholder("chat_history"), ["human", "{input}"],]);const chain2 = runnableWithMessageHistoryPrompt.pipe(llm); We’ll pass the latest input to the conversation here and let the `RunnableWithMessageHistory` class wrap our chain and do the work of appending that `input` variable to the chat history. Next, let’s declare our wrapped chain: import { RunnableWithMessageHistory } from "@langchain/core/runnables";const demoEphemeralChatMessageHistoryForChain = new ChatMessageHistory();const chainWithMessageHistory = new RunnableWithMessageHistory({ runnable: chain2, getMessageHistory: (_sessionId) => demoEphemeralChatMessageHistoryForChain, inputMessagesKey: "input", historyMessagesKey: "chat_history",}); This class takes a few parameters in addition to the chain that we want to wrap: * A factory function that returns a message history for a given session id. This allows your chain to handle multiple users at once by loading different messages for different conversations. * An `inputMessagesKey` that specifies which part of the input should be tracked and stored in the chat history. In this example, we want to track the string passed in as input. * A `historyMessagesKey` that specifies what the previous messages should be injected into the prompt as. Our prompt has a `MessagesPlaceholder` named `chat_history`, so we specify this property to match. (For chains with multiple outputs) an `outputMessagesKey` which specifies which output to store as history. This is the inverse of `inputMessagesKey`. We can invoke this new chain as normal, with an additional `configurable` field that specifies the particular `sessionId` to pass to the factory function. This is unused for the demo, but in real-world chains, you’ll want to return a chat history corresponding to the passed session: await chainWithMessageHistory.invoke( { input: "Translate this sentence from English to French: I love programming.", }, { configurable: { sessionId: "unused" } }); AIMessage { lc_serializable: true, lc_kwargs: { content: `The translation of "I love programming" in French is "J'adore la programmation."`, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: `The translation of "I love programming" in French is "J'adore la programmation."`, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 20, promptTokens: 39, totalTokens: 59 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} await chainWithMessageHistory.invoke( { input: "What did I just ask you?", }, { configurable: { sessionId: "unused" } }); AIMessage { lc_serializable: true, lc_kwargs: { content: 'You just asked for the translation of the sentence "I love programming" from English to French.', tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: 'You just asked for the translation of the sentence "I love programming" from English to French.', name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 19, promptTokens: 74, totalTokens: 93 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} Modifying chat history[​](#modifying-chat-history "Direct link to Modifying chat history") ------------------------------------------------------------------------------------------ Modifying stored chat messages can help your chatbot handle a variety of situations. Here are some examples: ### Trimming messages[​](#trimming-messages "Direct link to Trimming messages") LLMs and chat models have limited context windows, and even if you’re not directly hitting limits, you may want to limit the amount of distraction the model has to deal with. One solution is to only load and store the most recent `n` messages. Let’s use an example history with some preloaded messages: await demoEphemeralChatMessageHistory.clear();await demoEphemeralChatMessageHistory.addMessage( new HumanMessage("Hey there! I'm Nemo."));await demoEphemeralChatMessageHistory.addMessage(new AIMessage("Hello!"));await demoEphemeralChatMessageHistory.addMessage( new HumanMessage("How are you today?"));await demoEphemeralChatMessageHistory.addMessage(new AIMessage("Fine thanks!"));await demoEphemeralChatMessageHistory.getMessages(); [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "Hey there! I'm Nemo.", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hey there! I'm Nemo.", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Hello!", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello!", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "How are you today?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "How are you today?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Fine thanks!", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Fine thanks!", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }] Let’s use this message history with the `RunnableWithMessageHistory` chain we declared above: const chainWithMessageHistory2 = new RunnableWithMessageHistory({ runnable: chain2, getMessageHistory: (_sessionId) => demoEphemeralChatMessageHistory, inputMessagesKey: "input", historyMessagesKey: "chat_history",});await chainWithMessageHistory2.invoke( { input: "What's my name?", }, { configurable: { sessionId: "unused" } }); AIMessage { lc_serializable: true, lc_kwargs: { content: "Your name is Nemo!", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Your name is Nemo!", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 6, promptTokens: 66, totalTokens: 72 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} We can see the chain remembers the preloaded name. But let’s say we have a very small context window, and we want to trim the number of messages passed to the chain to only the 2 most recent ones. We can use the `clear` method to remove messages and re-add them to the history. We don’t have to, but let’s put this method at the front of our chain to ensure it’s always called: import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";const trimMessages = async (_chainInput: Record<string, any>) => { const storedMessages = await demoEphemeralChatMessageHistory.getMessages(); if (storedMessages.length <= 2) { return false; } await demoEphemeralChatMessageHistory.clear(); for (const message of storedMessages.slice(-2)) { demoEphemeralChatMessageHistory.addMessage(message); } return true;};const chainWithTrimming = RunnableSequence.from([ RunnablePassthrough.assign({ messages_trimmed: trimMessages }), chainWithMessageHistory2,]); Let’s call this new chain and check the messages afterwards: await chainWithTrimming.invoke( { input: "Where does P. Sherman live?", }, { configurable: { sessionId: "unused" } }); AIMessage { lc_serializable: true, lc_kwargs: { content: 'P. Sherman is a fictional character who lives at 42 Wallaby Way, Sydney, from the movie "Finding Nem'... 3 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: 'P. Sherman is a fictional character who lives at 42 Wallaby Way, Sydney, from the movie "Finding Nem'... 3 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 26, promptTokens: 53, totalTokens: 79 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} await demoEphemeralChatMessageHistory.getMessages(); [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "What's my name?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "What's my name?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Your name is Nemo!", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Your name is Nemo!", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 6, promptTokens: 66, totalTokens: 72 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "Where does P. Sherman live?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Where does P. Sherman live?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: 'P. Sherman is a fictional character who lives at 42 Wallaby Way, Sydney, from the movie "Finding Nem'... 3 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: 'P. Sherman is a fictional character who lives at 42 Wallaby Way, Sydney, from the movie "Finding Nem'... 3 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 26, promptTokens: 53, totalTokens: 79 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: [] }] And we can see that our history has removed the two oldest messages while still adding the most recent conversation at the end. The next time the chain is called, `trimMessages` will be called again, and only the two most recent messages will be passed to the model. In this case, this means that the model will forget the name we gave it the next time we invoke it: await chainWithTrimming.invoke( { input: "What is my name?", }, { configurable: { sessionId: "unused" } }); AIMessage { lc_serializable: true, lc_kwargs: { content: "I'm sorry, I don't have access to your personal information. Can I help you with anything else?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "I'm sorry, I don't have access to your personal information. Can I help you with anything else?", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 22, promptTokens: 73, totalTokens: 95 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} await demoEphemeralChatMessageHistory.getMessages(); [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "Where does P. Sherman live?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Where does P. Sherman live?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: 'P. Sherman is a fictional character who lives at 42 Wallaby Way, Sydney, from the movie "Finding Nem'... 3 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: 'P. Sherman is a fictional character who lives at 42 Wallaby Way, Sydney, from the movie "Finding Nem'... 3 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 26, promptTokens: 53, totalTokens: 79 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "What is my name?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "What is my name?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "I'm sorry, I don't have access to your personal information. Can I help you with anything else?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "I'm sorry, I don't have access to your personal information. Can I help you with anything else?", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 22, promptTokens: 73, totalTokens: 95 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: [] }] ### Summary memory[​](#summary-memory "Direct link to Summary memory") We can use this same pattern in other ways too. For example, we could use an additional LLM call to generate a summary of the conversation before calling our chain. Let’s recreate our chat history and chatbot chain: await demoEphemeralChatMessageHistory.clear();await demoEphemeralChatMessageHistory.addMessage( new HumanMessage("Hey there! I'm Nemo."));await demoEphemeralChatMessageHistory.addMessage(new AIMessage("Hello!"));await demoEphemeralChatMessageHistory.addMessage( new HumanMessage("How are you today?"));await demoEphemeralChatMessageHistory.addMessage(new AIMessage("Fine thanks!")); const runnableWithSummaryMemoryPrompt = ChatPromptTemplate.fromMessages([ [ "system", "You are a helpful assistant. Answer all questions to the best of your ability. The provided chat history includes facts about the user you are speaking with.", ], new MessagesPlaceholder("chat_history"), ["human", "{input}"],]);const summaryMemoryChain = runnableWithSummaryMemoryPrompt.pipe(llm);const chainWithMessageHistory3 = new RunnableWithMessageHistory({ runnable: summaryMemoryChain, getMessageHistory: (_sessionId) => demoEphemeralChatMessageHistory, inputMessagesKey: "input", historyMessagesKey: "chat_history",}); And now, let’s create a function that will distill previous interactions into a summary. We can add this one to the front of the chain too: const summarizeMessages = async (_chainInput: Record<string, any>) => { const storedMessages = await demoEphemeralChatMessageHistory.getMessages(); if (storedMessages.length === 0) { return false; } const summarizationPrompt = ChatPromptTemplate.fromMessages([ new MessagesPlaceholder("chat_history"), [ "user", "Distill the above chat messages into a single summary message. Include as many specific details as you can.", ], ]); const summarizationChain = summarizationPrompt.pipe(llm); const summaryMessage = await summarizationChain.invoke({ chat_history: storedMessages, }); await demoEphemeralChatMessageHistory.clear(); demoEphemeralChatMessageHistory.addMessage(summaryMessage); return true;};const chainWithSummarization = RunnableSequence.from([ RunnablePassthrough.assign({ messages_summarized: summarizeMessages, }), chainWithMessageHistory3,]); Let’s see if it remembers the name we gave it: await chainWithSummarization.invoke( { input: "What did I say my name was?", }, { configurable: { sessionId: "unused" }, }); AIMessage { lc_serializable: true, lc_kwargs: { content: 'You introduced yourself as "Nemo."', tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: 'You introduced yourself as "Nemo."', name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 8, promptTokens: 87, totalTokens: 95 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} await demoEphemeralChatMessageHistory.getMessages(); [ AIMessage { lc_serializable: true, lc_kwargs: { content: "The conversation consists of a greeting from someone named Nemo and a general inquiry about their we"... 86 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "The conversation consists of a greeting from someone named Nemo and a general inquiry about their we"... 86 more characters, name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 34, promptTokens: 62, totalTokens: 96 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "What did I say my name was?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "What did I say my name was?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: 'You introduced yourself as "Nemo."', tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: 'You introduced yourself as "Nemo."', name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 8, promptTokens: 87, totalTokens: 95 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: [] }] Note that invoking the chain again will generate another summary generated from the initial summary plus new messages and so on. You could also design a hybrid approach where a certain number of messages are retained in chat history while others are summarized. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to manage memory in your chatbots Next, check out some of the other guides in this section, such as [how to add retrieval to your chatbot](/v0.2/docs/how_to/chatbots_retrieval). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to split by character ](/v0.2/docs/how_to/character_text_splitter)[ Next How to do retrieval ](/v0.2/docs/how_to/chatbots_retrieval) * [Setup](#setup) * [Message passing](#message-passing) * [Chat history](#chat-history) * [Automatic history management](#automatic-history-management) * [Modifying chat history](#modifying-chat-history) * [Trimming messages](#trimming-messages) * [Summary memory](#summary-memory) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/
* [](/v0.2/) * How-to guides On this page How-to guides ============= Here you'll find answers to “How do I….?” types of questions. These guides are _goal-oriented_ and _concrete_; they're meant to help you complete a specific task. For conceptual explanations see [Conceptual Guides](/v0.2/docs/concepts/). For end-to-end walkthroughs see [Tutorials](/v0.2/docs/tutorials). For comprehensive descriptions of every class and function see [API Reference](https://v2.v02.api.js.langchain.com/). Installation[​](#installation "Direct link to Installation") ------------------------------------------------------------ * [How to: install LangChain packages](/v0.2/docs/how_to/installation/) Key features[​](#key-features "Direct link to Key features") ------------------------------------------------------------ This highlights functionality that is core to using LangChain. * [How to: return structured data from an LLM](/v0.2/docs/how_to/structured_output/) * [How to: use a chat model to call tools](/v0.2/docs/how_to/tool_calling/) * [How to: stream runnables](/v0.2/docs/how_to/streaming) * [How to: debug your LLM apps](/v0.2/docs/how_to/debugging/) LangChain Expression Language (LCEL)[​](#langchain-expression-language-lcel "Direct link to LangChain Expression Language (LCEL)") ---------------------------------------------------------------------------------------------------------------------------------- LangChain Expression Language is a way to create arbitrary custom chains. It is built on the [`Runnable`](https://api.js.langchain.com/classes/langchain_core_runnables.Runnable.html) protocol. [**LCEL cheatsheet**](/v0.2/docs/how_to/lcel_cheatsheet/): For a quick overview of how to use the main LCEL primitives. * [How to: chain runnables](/v0.2/docs/how_to/sequence) * [How to: stream runnables](/v0.2/docs/how_to/streaming) * [How to: invoke runnables in parallel](/v0.2/docs/how_to/parallel/) * [How to: attach runtime arguments to a runnable](/v0.2/docs/how_to/binding/) * [How to: run custom functions](/v0.2/docs/how_to/functions) * [How to: pass through arguments from one step to the next](/v0.2/docs/how_to/passthrough) * [How to: add values to a chain's state](/v0.2/docs/how_to/assign) * [How to: add message history](/v0.2/docs/how_to/message_history) * [How to: route execution within a chain](/v0.2/docs/how_to/routing) * [How to: add fallbacks](/v0.2/docs/how_to/fallbacks) Components[​](#components "Direct link to Components") ------------------------------------------------------ These are the core building blocks you can use when building applications. ### Prompt templates[​](#prompt-templates "Direct link to Prompt templates") [Prompt Templates](/v0.2/docs/concepts/#prompt-templates) are responsible for formatting user input into a format that can be passed to a language model. * [How to: use few shot examples](/v0.2/docs/how_to/few_shot_examples) * [How to: use few shot examples in chat models](/v0.2/docs/how_to/few_shot_examples_chat/) * [How to: partially format prompt templates](/v0.2/docs/how_to/prompts_partial) * [How to: compose prompts together](/v0.2/docs/how_to/prompts_composition) ### Example selectors[​](#example-selectors "Direct link to Example selectors") [Example Selectors](/v0.2/docs/concepts/#example-selectors) are responsible for selecting the correct few shot examples to pass to the prompt. * [How to: use example selectors](/v0.2/docs/how_to/example_selectors) * [How to: select examples by length](/v0.2/docs/how_to/example_selectors_length_based) * [How to: select examples by semantic similarity](/v0.2/docs/how_to/example_selectors_similarity) ### Chat models[​](#chat-models "Direct link to Chat models") [Chat Models](/v0.2/docs/concepts/#chat-models) are newer forms of language models that take messages in and output a message. * [How to: do function/tool calling](/v0.2/docs/how_to/tool_calling) * [How to: get models to return structured output](/v0.2/docs/how_to/structured_output) * [How to: cache model responses](/v0.2/docs/how_to/chat_model_caching) * [How to: create a custom chat model class](/v0.2/docs/how_to/custom_chat) * [How to: get log probabilities](/v0.2/docs/how_to/logprobs) * [How to: stream a response back](/v0.2/docs/how_to/chat_streaming) * [How to: track token usage](/v0.2/docs/how_to/chat_token_usage_tracking) ### Messages[​](#messages "Direct link to Messages") [Messages](/v0.2/docs/concepts/##message-types) are the input and output of chat models. They have some `content` and a `role`, which describes the source of the message. * [How to: trim messages](/v0.2/docs/how_to/trim_messages/) * [How to: filter messages](/v0.2/docs/how_to/filter_messages/) * [How to: merge consecutive messages of the same type](/v0.2/docs/how_to/merge_message_runs/) ### LLMs[​](#llms "Direct link to LLMs") What LangChain calls [LLMs](/v0.2/docs/concepts/#llms) are older forms of language models that take a string in and output a string. * [How to: cache model responses](/v0.2/docs/how_to/llm_caching) * [How to: create a custom LLM class](/v0.2/docs/how_to/custom_llm) * [How to: stream a response back](/v0.2/docs/how_to/streaming_llm) * [How to: track token usage](/v0.2/docs/how_to/llm_token_usage_tracking) ### Output parsers[​](#output-parsers "Direct link to Output parsers") [Output Parsers](/v0.2/docs/concepts/#output-parsers) are responsible for taking the output of an LLM and parsing into more structured format. * [How to: use output parsers to parse an LLM response into structured format](/v0.2/docs/how_to/output_parser_structured) * [How to: parse JSON output](/v0.2/docs/how_to/output_parser_json) * [How to: parse XML output](/v0.2/docs/how_to/output_parser_xml) * [How to: try to fix errors in output parsing](/v0.2/docs/how_to/output_parser_fixing/) ### Document loaders[​](#document-loaders "Direct link to Document loaders") [Document Loaders](/v0.2/docs/concepts/#document-loaders) are responsible for loading documents from a variety of sources. * [How to: load CSV data](/v0.2/docs/how_to/document_loader_csv) * [How to: load data from a directory](/v0.2/docs/how_to/document_loader_directory) * [How to: load PDF files](/v0.2/docs/how_to/document_loader_pdf) * [How to: write a custom document loader](/v0.2/docs/how_to/document_loader_custom) * [How to: load HTML data](/v0.2/docs/how_to/document_loader_html) * [How to: load Markdown data](/v0.2/docs/how_to/document_loader_markdown) ### Text splitters[​](#text-splitters "Direct link to Text splitters") [Text Splitters](/v0.2/docs/concepts/#text-splitters) take a document and split into chunks that can be used for retrieval. * [How to: recursively split text](/v0.2/docs/how_to/recursive_text_splitter) * [How to: split by character](/v0.2/docs/how_to/character_text_splitter) * [How to: split code](/v0.2/docs/how_to/code_splitter) * [How to: split by tokens](/v0.2/docs/how_to/split_by_token) ### Embedding models[​](#embedding-models "Direct link to Embedding models") [Embedding Models](/v0.2/docs/concepts/#embedding-models) take a piece of text and create a numerical representation of it. * [How to: embed text data](/v0.2/docs/how_to/embed_text) * [How to: cache embedding results](/v0.2/docs/how_to/caching_embeddings) ### Vector stores[​](#vector-stores "Direct link to Vector stores") [Vector stores](/v0.2/docs/concepts/#vectorstores) are databases that can efficiently store and retrieve embeddings. * [How to: create and query vector stores](/v0.2/docs/how_to/vectorstores) ### Retrievers[​](#retrievers "Direct link to Retrievers") [Retrievers](/v0.2/docs/concepts/#retrievers) are responsible for taking a query and returning relevant documents. * [How to: use a vector store to retrieve data](/v0.2/docs/how_to/vectorstore_retriever) * [How to: generate multiple queries to retrieve data for](/v0.2/docs/how_to/multiple_queries) * [How to: use contextual compression to compress the data retrieved](/v0.2/docs/how_to/contextual_compression) * [How to: write a custom retriever class](/v0.2/docs/how_to/custom_retriever) * [How to: combine the results from multiple retrievers](/v0.2/docs/how_to/ensemble_retriever) * [How to: generate multiple embeddings per document](/v0.2/docs/how_to/multi_vector) * [How to: retrieve the whole document for a chunk](/v0.2/docs/how_to/parent_document_retriever) * [How to: generate metadata filters](/v0.2/docs/how_to/self_query) * [How to: create a time-weighted retriever](/v0.2/docs/how_to/time_weighted_vectorstore) * [How to: reduce retrieval latency](/v0.2/docs/how_to/reduce_retrieval_latency) ### Indexing[​](#indexing "Direct link to Indexing") Indexing is the process of keeping your vectorstore in-sync with the underlying data source. * [How to: reindex data to keep your vectorstore in-sync with the underlying data source](/v0.2/docs/how_to/indexing) ### Tools[​](#tools "Direct link to Tools") LangChain [Tools](/v0.2/docs/concepts/#tools) contain a description of the tool (to pass to the language model) as well as the implementation of the function to call. * [How to: create custom tools](/v0.2/docs/how_to/custom_tools) * [How to: use built-in tools and built-in toolkits](/v0.2/docs/how_to/tools_builtin) * [How to: use a chat model to call tools](/v0.2/docs/how_to/tool_calling/) * [How to: add ad-hoc tool calling capability to LLMs and Chat Models](/v0.2/docs/how_to/tools_prompting) ### Agents[​](#agents "Direct link to Agents") note For in depth how-to guides for agents, please check out [LangGraph](https://langchain-ai.github.io/langgraphjs/) documentation. * [How to: use legacy LangChain Agents (AgentExecutor)](/v0.2/docs/how_to/agent_executor) * [How to: migrate from legacy LangChain agents to LangGraph](/v0.2/docs/how_to/migrate_agent) ### Callbacks[​](#callbacks "Direct link to Callbacks") [Callbacks](/v0.2/docs/concepts/#callbacks) allow you to hook into the various stages of your LLM application's execution. * [How to: pass in callbacks at runtime](/v0.2/docs/how_to/callbacks_runtime) * [How to: attach callbacks to a module](/v0.2/docs/how_to/callbacks_attach) * [How to: pass callbacks into a module constructor](/v0.2/docs/how_to/callbacks_constructor) * [How to: create custom callback handlers](/v0.2/docs/how_to/custom_callbacks) * [How to: make callbacks run in the background](/v0.2/docs/how_to/callbacks_backgrounding) ### Custom[​](#custom "Direct link to Custom") All of LangChain components can easily be extended to support your own versions. * [How to: create a custom chat model class](/v0.2/docs/how_to/custom_chat) * [How to: create a custom LLM class](/v0.2/docs/how_to/custom_llm) * [How to: write a custom retriever class](/v0.2/docs/how_to/custom_retriever) * [How to: write a custom document loader](/v0.2/docs/how_to/document_loader_custom) * [How to: define a custom tool](/v0.2/docs/how_to/custom_tools) * [How to: create custom callback handlers](/v0.2/docs/how_to/custom_callbacks) ### Generative UI[​](#generative-ui "Direct link to Generative UI") * [How to: build an LLM generated UI](/v0.2/docs/how_to/generative_ui) * [How to: stream agentic data to the client](/v0.2/docs/how_to/stream_agent_client) * [How to: stream structured output to the client](/v0.2/docs/how_to/stream_tool_client) ### Multimodal[​](#multimodal "Direct link to Multimodal") * [How to: pass multimodal data directly to models](/v0.2/docs/how_to/multimodal_inputs/) * [How to: use multimodal prompts](/v0.2/docs/how_to/multimodal_prompts/) * [How to: call tools with multimodal data](/v0.2/docs/how_to/tool_calls_multimodal/) Use cases[​](#use-cases "Direct link to Use cases") --------------------------------------------------- These guides cover use-case specific details. ### Q&A with RAG[​](#qa-with-rag "Direct link to Q&A with RAG") Retrieval Augmented Generation (RAG) is a way to connect LLMs to external sources of data. For a high-level tutorial on RAG, check out [this guide](/v0.2/docs/tutorials/rag/). * [How to: add chat history](/v0.2/docs/how_to/qa_chat_history_how_to/) * [How to: stream](/v0.2/docs/how_to/qa_streaming/) * [How to: return sources](/v0.2/docs/how_to/qa_sources/) * [How to: return citations](/v0.2/docs/how_to/qa_citations/) * [How to: do per-user retrieval](/v0.2/docs/how_to/qa_per_user/) ### Extraction[​](#extraction "Direct link to Extraction") Extraction is when you use LLMs to extract structured information from unstructured text. For a high level tutorial on extraction, check out [this guide](/v0.2/docs/tutorials/extraction/). * [How to: use reference examples](/v0.2/docs/how_to/extraction_examples/) * [How to: handle long text](/v0.2/docs/how_to/extraction_long_text/) * [How to: do extraction without using function calling](/v0.2/docs/how_to/extraction_parse) ### Chatbots[​](#chatbots "Direct link to Chatbots") Chatbots involve using an LLM to have a conversation. For a high-level tutorial on building chatbots, check out [this guide](/v0.2/docs/tutorials/chatbot/). * [How to: manage memory](/v0.2/docs/how_to/chatbots_memory) * [How to: do retrieval](/v0.2/docs/how_to/chatbots_retrieval) * [How to: use tools](/v0.2/docs/how_to/chatbots_tools) ### Query analysis[​](#query-analysis "Direct link to Query analysis") Query Analysis is the task of using an LLM to generate a query to send to a retriever. For a high-level tutorial on query analysis, check out [this guide](/v0.2/docs/tutorials/query_analysis/). * [How to: add examples to the prompt](/v0.2/docs/how_to/query_few_shot) * [How to: handle cases where no queries are generated](/v0.2/docs/how_to/query_no_queries) * [How to: handle multiple queries](/v0.2/docs/how_to/query_multiple_queries) * [How to: handle multiple retrievers](/v0.2/docs/how_to/query_multiple_retrievers) * [How to: construct filters](/v0.2/docs/how_to/query_constructing_filters) * [How to: deal with high cardinality categorical variables](/v0.2/docs/how_to/query_high_cardinality) ### Q&A over SQL + CSV[​](#qa-over-sql--csv "Direct link to Q&A over SQL + CSV") You can use LLMs to do question answering over tabular data. For a high-level tutorial, check out [this guide](/v0.2/docs/tutorials/sql_qa/). * [How to: use prompting to improve results](/v0.2/docs/how_to/sql_prompting) * [How to: do query validation](/v0.2/docs/how_to/sql_query_checking) * [How to: deal with large databases](/v0.2/docs/how_to/sql_large_db) ### Q&A over graph databases[​](#qa-over-graph-databases "Direct link to Q&A over graph databases") You can use an LLM to do question answering over graph databases. For a high-level tutorial, check out [this guide](/v0.2/docs/tutorials/graph/). * [How to: map values to a database](/v0.2/docs/how_to/graph_mapping) * [How to: add a semantic layer over the database](/v0.2/docs/how_to/graph_semantic) * [How to: improve results with prompting](/v0.2/docs/how_to/graph_prompting) * [How to: construct knowledge graphs](/v0.2/docs/how_to/graph_constructing) [LangGraph.js](https://langchain-ai.github.io/langgraphjs)[​](#langgraphjs "Direct link to langgraphjs") -------------------------------------------------------------------------------------------------------- LangGraph.js is an extension of LangChain aimed at building robust and stateful multi-actor applications with LLMs by modeling steps as edges and nodes in a graph. LangGraph.js documentation is currently hosted on a separate site. You can peruse [LangGraph.js how-to guides here](https://langchain-ai.github.io/langgraphjs/how-tos/). [LangSmith](https://docs.smith.langchain.com/)[​](#langsmith "Direct link to langsmith") ---------------------------------------------------------------------------------------- LangSmith allows you to closely trace, monitor and evaluate your LLM application. It seamlessly integrates with LangChain and LangGraph.js, and you can use it to inspect and debug individual steps of your chains as you build. LangSmith documentation is hosted on a separate site. You can peruse [LangSmith how-to guides here](https://docs.smith.langchain.com/how_to_guides/). ### Evaluation[​](#evaluation "Direct link to Evaluation") Evaluating performance is a vital part of building LLM-powered applications. LangSmith helps with every step of the process from creating a dataset to defining metrics to running evaluators. To learn more, check out the [LangSmith evaluation how-to guides](https://docs.smith.langchain.com/how_to_guides#evaluation). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous Build a Question/Answering system over SQL data ](/v0.2/docs/tutorials/sql_qa)[ Next How-to guides ](/v0.2/docs/how_to/) * [Installation](#installation) * [Key features](#key-features) * [LangChain Expression Language (LCEL)](#langchain-expression-language-lcel) * [Components](#components) * [Prompt templates](#prompt-templates) * [Example selectors](#example-selectors) * [Chat models](#chat-models) * [Messages](#messages) * [LLMs](#llms) * [Output parsers](#output-parsers) * [Document loaders](#document-loaders) * [Text splitters](#text-splitters) * [Embedding models](#embedding-models) * [Vector stores](#vector-stores) * [Retrievers](#retrievers) * [Indexing](#indexing) * [Tools](#tools) * [Agents](#agents) * [Callbacks](#callbacks) * [Custom](#custom) * [Generative UI](#generative-ui) * [Multimodal](#multimodal) * [Use cases](#use-cases) * [Q&A with RAG](#qa-with-rag) * [Extraction](#extraction) * [Chatbots](#chatbots) * [Query analysis](#query-analysis) * [Q&A over SQL + CSV](#qa-over-sql--csv) * [Q&A over graph databases](#qa-over-graph-databases) * [LangGraph.js](#langgraphjs) * [LangSmith](#langsmith) * [Evaluation](#evaluation)
null
https://js.langchain.com/v0.2/docs/how_to/stream_tool_client
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to stream structured output to the client On this page How to stream structured output to the client ============================================= This guide will walk you through how we stream agent data to the client using [React Server Components](https://react.dev/reference/rsc/server-components) inside this directory. The code in this doc is taken from the `page.tsx` and `action.ts` files in this directory. To view the full, uninterrupted code, click [here for the actions file](https://github.com/langchain-ai/langchain-nextjs-template/blob/main/app/ai_sdk/tools/action.ts) and [here for the client file](https://github.com/langchain-ai/langchain-nextjs-template/blob/main/app/ai_sdk/tools/page.tsx). Prerequisites This guide assumes familiarity with the following concepts: > * [LangChain Expression Language](/v0.2/docs/concepts#langchain-expression-language) > * [Chat models](/v0.2/docs/concepts#chat-models) > * [Tool calling](/v0.2/docs/concepts#functiontool-calling) Setup[​](#setup "Direct link to Setup") --------------------------------------- First, install the necessary LangChain & AI SDK packages: * npm * Yarn * pnpm npm install @langchain/openai @langchain/core ai zod zod-to-json-schema yarn add @langchain/openai @langchain/core ai zod zod-to-json-schema pnpm add @langchain/openai @langchain/core ai zod zod-to-json-schema Next, we'll create our server file. This will contain all the logic for making tool calls and sending the data back to the client. Start by adding the necessary imports & the `"use server"` directive: "use server";import { ChatOpenAI } from "@langchain/openai";import { ChatPromptTemplate } from "@langchain/core/prompts";import { createStreamableValue } from "ai/rsc";import { z } from "zod";import { zodToJsonSchema } from "zod-to-json-schema";import { JsonOutputKeyToolsParser } from "@langchain/core/output_parsers/openai_tools"; After that, we'll define our tool schema. For this example we'll use a simple demo weather schema: const Weather = z .object({ city: z.string().describe("City to search for weather"), state: z.string().describe("State abbreviation to search for weather"), }) .describe("Weather search parameters"); Once our schema is defined, we can implement our `executeTool` function. This function takes in a single input of `string`, and contains all the logic for our tool and streaming data back to the client: export async function executeTool( input: string,) { "use server"; const stream = createStreamableValue(); The `createStreamableValue` function is important as this is what we'll use for actually streaming all the data back to the client. For the main logic, we'll wrap it in an async function. Start by defining our prompt and chat model: (async () => { const prompt = ChatPromptTemplate.fromMessages([ [ "system", `You are a helpful assistant. Use the tools provided to best assist the user.`, ], ["human", "{input}"], ]); const llm = new ChatOpenAI({ model: "gpt-4o-2024-05-13", temperature: 0, }); After defining our chat model, we'll define our runnable chain using LCEL. We start binding our `weather` tool we defined earlier to the model: const modelWithTools = llm.bind({ tools: [ { type: "function" as const, function: { name: "get_weather", description: Weather.description, parameters: zodToJsonSchema(Weather), }, }, ],}); Next, we'll use LCEL to pipe each component together, starting with the prompt, then the model with tools, and finally the output parser: const chain = prompt.pipe(modelWithTools).pipe( new JsonOutputKeyToolsParser<z.infer<typeof Weather>>({ keyName: "get_weather", zodSchema: Weather, })); Finally, we'll call `.stream` on our chain, and similarly to the [streaming agent](/v0.2/docs/how_to/stream_agent_client) example, we'll iterate over the stream and stringify + parse the data before updating the stream value: const streamResult = await chain.stream({ input, }); for await (const item of streamResult) { stream.update(JSON.parse(JSON.stringify(item, null, 2))); } stream.done(); })(); return { streamData: stream.value };} * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to stream agent data to the client ](/v0.2/docs/how_to/stream_agent_client)[ Next How to stream ](/v0.2/docs/how_to/streaming) * [Setup](#setup)
null
https://js.langchain.com/v0.2/docs/how_to/stream_agent_client
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to stream agent data to the client On this page How to stream agent data to the client ====================================== This guide will walk you through how we stream agent data to the client using [React Server Components](https://react.dev/reference/rsc/server-components) inside this directory. The code in this doc is taken from the `page.tsx` and `action.ts` files in this directory. To view the full, uninterrupted code, click [here for the actions file](https://github.com/langchain-ai/langchain-nextjs-template/blob/main/app/ai_sdk/agent/action.ts) and [here for the client file](https://github.com/langchain-ai/langchain-nextjs-template/blob/main/app/ai_sdk/agent/page.tsx). Prerequisites This guide assumes familiarity with the following concepts: * [LangChain Expression Language](/v0.2/docs/concepts#langchain-expression-language) * [Chat models](/v0.2/docs/concepts#chat-models) * [Tool calling](/v0.2/docs/concepts#functiontool-calling) * [Agents](/v0.2/docs/concepts#agents) Setup[​](#setup "Direct link to Setup") --------------------------------------- First, install the necessary LangChain & AI SDK packages: * npm * Yarn * pnpm npm install langchain @langchain/core @langchain/community ai yarn add langchain @langchain/core @langchain/community ai pnpm add langchain @langchain/core @langchain/community ai In this demo we'll be using the `TavilySearchResults` tool, which requires an API key. You can get one [here](https://app.tavily.com/), or you can swap it out for another tool of your choice, like [`WikipediaQueryRun`](/v0.2/docs/integrations/tools/wikipedia) which doesn't require an API key. If you choose to use `TavilySearchResults`, set your API key like so: export TAVILY_API_KEY=your_api_key Get started[​](#get-started "Direct link to Get started") --------------------------------------------------------- The first step is to create a new RSC file, and add the imports which we'll use for running our agent. In this demo, we'll name it `action.ts`: "use server";import { ChatOpenAI } from "@langchain/openai";import { ChatPromptTemplate } from "@langchain/core/prompts";import { TavilySearchResults } from "@langchain/community/tools/tavily_search";import { AgentExecutor, createToolCallingAgent } from "langchain/agents";import { pull } from "langchain/hub";import { createStreamableValue } from "ai/rsc"; Next, we'll define a `runAgent` function. This function takes in a single input of `string`, and contains all the logic for our agent and streaming data back to the client: export async function runAgent(input: string) { "use server";} Next, inside our function we'll define our chat model of choice: const llm = new ChatOpenAI({ model: "gpt-4o-2024-05-13", temperature: 0,}); Next, we'll use the `createStreamableValue` helper function provided by the `ai` package to create a streamable value: const stream = createStreamableValue(); This will be very important later on when we start streaming data back to the client. Next, lets define our async function inside which contains the agent logic: (async () => { const tools = [new TavilySearchResults({ maxResults: 1 })]; const prompt = await pull<ChatPromptTemplate>( "hwchase17/openai-tools-agent", ); const agent = createToolCallingAgent({ llm, tools, prompt, }); const agentExecutor = new AgentExecutor({ agent, tools, }); Here you can see we're doing a few things: The first is we're defining our list of tools (in this case we're only using a single tool) and pulling in our prompt from the LangChain prompt hub. After that, we're passing our LLM, tools and prompt to the `createToolCallingAgent` function, which will construct and return a runnable agent. This is then passed into the `AgentExecutor` class, which will handle the execution & streaming of our agent. Finally, we'll call `.streamEvents` and pass our streamed data back to the `stream` variable we defined above, const streamingEvents = agentExecutor.streamEvents( { input }, { version: "v1" }, ); for await (const item of streamingEvents) { stream.update(JSON.parse(JSON.stringify(item, null, 2))); } stream.done(); })(); As you can see above, we're doing something a little wacky by stringifying and parsing our data. This is due to a bug in the RSC streaming code, however if you stringify and parse like we are above, you shouldn't experience this. Finally, at the bottom of the function return the stream value: return { streamData: stream.value }; Once we've implemented our server action, we can add a couple lines of code in our client function to request and stream this data: First, add the necessary imports: "use client";import { useState } from "react";import { readStreamableValue } from "ai/rsc";import { runAgent } from "./action"; Then inside our `Page` function, calling the `runAgent` function is straightforward: export default function Page() { const [input, setInput] = useState(""); const [data, setData] = useState<StreamEvent[]>([]); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); const { streamData } = await runAgent(input); for await (const item of readStreamableValue(streamData)) { setData((prev) => [...prev, item]); } }} That's it! You've successfully built an agent that streams data back to the client. You can now run your application and see the data streaming in real-time. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to do query validation ](/v0.2/docs/how_to/sql_query_checking)[ Next How to stream structured output to the client ](/v0.2/docs/how_to/stream_tool_client) * [Setup](#setup) * [Get started](#get-started)
null
https://js.langchain.com/v0.2/docs/how_to/example_selectors
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use example selectors On this page How to use example selectors ============================ Prerequisites This guide assumes familiarity with the following concepts: * [Prompt templates](/v0.2/docs/concepts/#prompt-templates) * [Few-shot examples](/v0.2/docs/how_to/few_shot_examples) If you have a large number of examples, you may need to select which ones to include in the prompt. The Example Selector is the class responsible for doing so. The base interface is defined as below: class BaseExampleSelector { addExample(example: Example): Promise<void | string>; selectExamples(input_variables: Example): Promise<Example[]>;} The only method it needs to define is a `selectExamples` method. This takes in the input variables and then returns a list of examples. It is up to each specific implementation as to how those examples are selected. LangChain has a few different types of example selectors. For an overview of all these types, see the below table. In this guide, we will walk through creating a custom example selector. Examples[​](#examples "Direct link to Examples") ------------------------------------------------ In order to use an example selector, we need to create a list of examples. These should generally be example inputs and outputs. For this demo purpose, let’s imagine we are selecting examples of how to translate English to Italian. const examples = [ { input: "hi", output: "ciao" }, { input: "bye", output: "arrivaderci" }, { input: "soccer", output: "calcio" },]; Custom Example Selector[​](#custom-example-selector "Direct link to Custom Example Selector") --------------------------------------------------------------------------------------------- Let’s write an example selector that chooses what example to pick based on the length of the word. import { BaseExampleSelector } from "@langchain/core/example_selectors";import { Example } from "@langchain/core/prompts";class CustomExampleSelector extends BaseExampleSelector { private examples: Example[]; constructor(examples: Example[]) { super(); this.examples = examples; } async addExample(example: Example): Promise<void | string> { this.examples.push(example); return; } async selectExamples(inputVariables: Example): Promise<Example[]> { // This assumes knowledge that part of the input will be a 'text' key const newWord = inputVariables.input; const newWordLength = newWord.length; // Initialize variables to store the best match and its length difference let bestMatch: Example | null = null; let smallestDiff = Infinity; // Iterate through each example for (const example of this.examples) { // Calculate the length difference with the first word of the example const currentDiff = Math.abs(example.input.length - newWordLength); // Update the best match if the current one is closer in length if (currentDiff < smallestDiff) { smallestDiff = currentDiff; bestMatch = example; } } return bestMatch ? [bestMatch] : []; }} const exampleSelector = new CustomExampleSelector(examples); await exampleSelector.selectExamples({ input: "okay" }); [ { input: "bye", output: "arrivaderci" } ] await exampleSelector.addExample({ input: "hand", output: "mano" }); await exampleSelector.selectExamples({ input: "okay" }); [ { input: "hand", output: "mano" } ] Use in a Prompt[​](#use-in-a-prompt "Direct link to Use in a Prompt") --------------------------------------------------------------------- We can now use this example selector in a prompt import { PromptTemplate, FewShotPromptTemplate } from "@langchain/core/prompts";const examplePrompt = PromptTemplate.fromTemplate( "Input: {input} -> Output: {output}"); const prompt = new FewShotPromptTemplate({ exampleSelector, examplePrompt, suffix: "Input: {input} -> Output:", prefix: "Translate the following words from English to Italain:", inputVariables: ["input"],});console.log(await prompt.format({ input: "word" })); Translate the following words from English to Italain:Input: hand -> Output: manoInput: word -> Output: Example Selector Types[​](#example-selector-types "Direct link to Example Selector Types") ------------------------------------------------------------------------------------------ Name Description Similarity Uses semantic similarity between inputs and examples to decide which examples to choose. Length Selects examples based on how many can fit within a certain length Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned a bit about using example selectors to few shot LLMs. Next, check out some guides on some other techniques for selecting examples: * [How to select examples by length](/v0.2/docs/how_to/example_selectors_length_based) * [How to select examples by similarity](/v0.2/docs/how_to/example_selectors_similarity) * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How-to guides ](/v0.2/docs/how_to/)[ Next Installation ](/v0.2/docs/how_to/installation) * [Examples](#examples) * [Custom Example Selector](#custom-example-selector) * [Use in a Prompt](#use-in-a-prompt) * [Example Selector Types](#example-selector-types) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/time_weighted_vectorstore
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to create a time-weighted retriever On this page How to create a time-weighted retriever ======================================= Prerequisites This guide assumes familiarity with the following concepts: * [Retrievers](/v0.2/docs/concepts/#retrievers) * [Vector stores](/v0.2/docs/concepts/#vectorstores) * [Retrieval-augmented generation (RAG)](/v0.2/docs/tutorials/rag) This guide covers the [`TimeWeightedVectorStoreRetriever`](https://v02.api.js.langchain.com/classes/langchain_retrievers_time_weighted.TimeWeightedVectorStoreRetriever.html), which uses a combination of semantic similarity and a time decay. The algorithm for scoring them is: semantic_similarity + (1.0 - decay_rate) ^ hours_passed Notably, `hours_passed` refers to the hours passed since the object in the retriever **was last accessed**, not since it was created. This means that frequently accessed objects remain "fresh." let score = (1.0 - this.decayRate) ** hoursPassed + vectorRelevance; `this.decayRate` is a configurable decimal number between 0 and 1. A lower number means that documents will be "remembered" for longer, while a higher number strongly weights more recently accessed documents. Note that setting a decay rate of exactly 0 or 1 makes `hoursPassed` irrelevant and makes this retriever equivalent to a standard vector lookup. It is important to note that due to required metadata, all documents must be added to the backing vector store using the `addDocuments` method on the **retriever**, not the vector store itself. tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { TimeWeightedVectorStoreRetriever } from "langchain/retrievers/time_weighted";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings } from "@langchain/openai";const vectorStore = new MemoryVectorStore(new OpenAIEmbeddings());const retriever = new TimeWeightedVectorStoreRetriever({ vectorStore, memoryStream: [], searchKwargs: 2,});const documents = [ "My name is John.", "My name is Bob.", "My favourite food is pizza.", "My favourite food is pasta.", "My favourite food is sushi.",].map((pageContent) => ({ pageContent, metadata: {} }));// All documents must be added using this method on the retriever (not the vector store!)// so that the correct access history metadata is populatedawait retriever.addDocuments(documents);const results1 = await retriever.invoke("What is my favourite food?");console.log(results1);/*[ Document { pageContent: 'My favourite food is pasta.', metadata: {} }] */const results2 = await retriever.invoke("What is my favourite food?");console.log(results2);/*[ Document { pageContent: 'My favourite food is pasta.', metadata: {} }] */ #### API Reference: * [TimeWeightedVectorStoreRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_time_weighted.TimeWeightedVectorStoreRetriever.html) from `langchain/retrievers/time_weighted` * [MemoryVectorStore](https://v02.api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned how to use time as a factor when performing retrieval. Next, check out the [broader tutorial on RAG](/v0.2/docs/tutorials/rag), or this section to learn how to [create your own custom retriever over any data source](/v0.2/docs/how_to/custom_retriever/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to stream ](/v0.2/docs/how_to/streaming)[ Next How to use a chat model to call tools ](/v0.2/docs/how_to/tool_calling) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/installation
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * Installation On this page Installation ============ Supported Environments[​](#supported-environments "Direct link to Supported Environments") ------------------------------------------------------------------------------------------ LangChain is written in TypeScript and can be used in: * Node.js (ESM and CommonJS) - 18.x, 19.x, 20.x * Cloudflare Workers * Vercel / Next.js (Browser, Serverless and Edge functions) * Supabase Edge Functions * Browser * Deno * Bun However, note that individual integrations may not be supported in all environments. Installation[​](#installation-1 "Direct link to Installation") -------------------------------------------------------------- To install LangChain, run the following command: * npm * Yarn * pnpm npm install langchain yarn add langchain pnpm add langchain A lot of the value of LangChain comes when integrating it with various model providers, datastores, etc. By default, the dependencies needed to do that are NOT installed. You will need to install the dependencies for specific integrations separately. ### @langchain/community[​](#langchaincommunity "Direct link to @langchain/community") The [@langchain/community](https://www.npmjs.com/package/@langchain/community) package contains a range of third-party integrations. Install with: * npm * Yarn * pnpm npm install @langchain/community yarn add @langchain/community pnpm add @langchain/community There are also more granular packages containing LangChain integrations for individual providers. ### @langchain/core[​](#langchaincore "Direct link to @langchain/core") The [@langchain/core](https://www.npmjs.com/package/@langchain/core) package contains base abstractions that the rest of the LangChain ecosystem uses, along with the LangChain Expression Language. It is automatically installed along with `langchain`, but can also be used separately. Install with: * npm * Yarn * pnpm npm install @langchain/core yarn add @langchain/core pnpm add @langchain/core ### LangGraph[​](#langgraph "Direct link to LangGraph") `langgraph` is a library for building stateful, multi-actor applications with LLMs, built on top of (and intended to be used with) LangChain. Install with: * npm * Yarn * pnpm npm install @langchain/langgraph yarn add @langchain/langgraph pnpm add @langchain/langgraph ### LangSmith SDK[​](#langsmith-sdk "Direct link to LangSmith SDK") The LangSmith SDK is automatically installed by LangChain. If you're not using it with LangChain, install with: * npm * Yarn * pnpm npm install langsmith yarn add langsmith pnpm add langsmith tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). Installing integration packages[​](#installing-integration-packages "Direct link to Installing integration packages") --------------------------------------------------------------------------------------------------------------------- LangChain supports packages that contain module integrations with individual third-party providers. They can be as specific as [`@langchain/anthropic`](/v0.2/docs/integrations/platforms/anthropic/), which contains integrations just for Anthropic models, or as broad as [`@langchain/community`](https://www.npmjs.com/package/@langchain/community), which contains broader variety of community contributed integrations. These packages, as well as the main LangChain package, all depend on [`@langchain/core`](https://www.npmjs.com/package/@langchain/core), which contains the base abstractions that these integration packages extend. To ensure that all integrations and their types interact with each other properly, it is important that they all use the same version of `@langchain/core`. The best way to guarantee this is to add a `"resolutions"` or `"overrides"` field like the following in your project's `package.json`. The name will depend on your package manager: tip The `resolutions` or `pnpm.overrides` fields for `yarn` or `pnpm` must be set in the root `package.json` file. If you are using `yarn`: yarn package.json { "name": "your-project", "version": "0.0.0", "private": true, "engines": { "node": ">=18" }, "dependencies": { "@langchain/anthropic": "^0.0.2", "langchain": "0.0.207" }, "resolutions": { "@langchain/core": "0.1.5" }} Or for `npm`: npm package.json { "name": "your-project", "version": "0.0.0", "private": true, "engines": { "node": ">=18" }, "dependencies": { "@langchain/anthropic": "^0.0.2", "langchain": "0.0.207" }, "overrides": { "@langchain/core": "0.1.5" }} Or for `pnpm`: pnpm package.json { "name": "your-project", "version": "0.0.0", "private": true, "engines": { "node": ">=18" }, "dependencies": { "@langchain/anthropic": "^0.0.2", "langchain": "0.0.207" }, "pnpm": { "overrides": { "@langchain/core": "0.1.5" } }} Loading the library[​](#loading-the-library "Direct link to Loading the library") --------------------------------------------------------------------------------- ### TypeScript[​](#typescript "Direct link to TypeScript") LangChain is written in TypeScript and provides type definitions for all of its public APIs. ### ESM[​](#esm "Direct link to ESM") LangChain provides an ESM build targeting Node.js environments. You can import it using the following syntax: * npm * Yarn * pnpm npm install @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai import { OpenAI } from "@langchain/openai"; If you are using TypeScript in an ESM project we suggest updating your `tsconfig.json` to include the following: tsconfig.json { "compilerOptions": { ... "target": "ES2020", // or higher "module": "nodenext", }} ### CommonJS[​](#commonjs "Direct link to CommonJS") LangChain provides a CommonJS build targeting Node.js environments. You can import it using the following syntax: const { OpenAI } = require("@langchain/openai"); ### Cloudflare Workers[​](#cloudflare-workers "Direct link to Cloudflare Workers") LangChain can be used in Cloudflare Workers. You can import it using the following syntax: import { OpenAI } from "@langchain/openai"; ### Vercel / Next.js[​](#vercel--nextjs "Direct link to Vercel / Next.js") LangChain can be used in Vercel / Next.js. We support using LangChain in frontend components, in Serverless functions and in Edge functions. You can import it using the following syntax: import { OpenAI } from "@langchain/openai"; ### Deno / Supabase Edge Functions[​](#deno--supabase-edge-functions "Direct link to Deno / Supabase Edge Functions") LangChain can be used in Deno / Supabase Edge Functions. You can import it using the following syntax: import { OpenAI } from "https://esm.sh/@langchain/openai"; or import { OpenAI } from "npm:@langchain/openai"; We recommend looking at our [Supabase Template](https://github.com/langchain-ai/langchain-template-supabase) for an example of how to use LangChain in Supabase Edge Functions. ### Browser[​](#browser "Direct link to Browser") LangChain can be used in the browser. In our CI we test bundling LangChain with Webpack and Vite, but other bundlers should work too. You can import it using the following syntax: import { OpenAI } from "@langchain/openai"; Unsupported: Node.js 16[​](#unsupported-nodejs-16 "Direct link to Unsupported: Node.js 16") ------------------------------------------------------------------------------------------- We do not support Node.js 16, but if you still want to run LangChain on Node.js 16, you will need to follow the instructions in this section. We do not guarantee that these instructions will continue to work in the future. You will have to make `fetch` available globally, either: * run your application with `NODE_OPTIONS='--experimental-fetch' node ...`, or * install `node-fetch` and follow the instructions [here](https://github.com/node-fetch/node-fetch#providing-global-access) You'll also need to [polyfill `ReadableStream`](https://www.npmjs.com/package/web-streams-polyfill) by installing: * npm * Yarn * pnpm npm i web-streams-polyfill yarn add web-streams-polyfill pnpm add web-streams-polyfill And then adding it to the global namespace in your main entrypoint: import "web-streams-polyfill/es6"; Additionally you'll have to polyfill `structuredClone`, eg. by installing `core-js` and following the instructions [here](https://github.com/zloirock/core-js). If you are running Node.js 18+, you do not need to do anything. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use example selectors ](/v0.2/docs/how_to/example_selectors)[ Next How to stream responses from an LLM ](/v0.2/docs/how_to/streaming_llm) * [Supported Environments](#supported-environments) * [Installation](#installation-1) * [@langchain/community](#langchaincommunity) * [@langchain/core](#langchaincore) * [LangGraph](#langgraph) * [LangSmith SDK](#langsmith-sdk) * [Installing integration packages](#installing-integration-packages) * [Loading the library](#loading-the-library) * [TypeScript](#typescript) * [ESM](#esm) * [CommonJS](#commonjs) * [Cloudflare Workers](#cloudflare-workers) * [Vercel / Next.js](#vercel--nextjs) * [Deno / Supabase Edge Functions](#deno--supabase-edge-functions) * [Browser](#browser) * [Unsupported: Node.js 16](#unsupported-nodejs-16)
null
https://js.langchain.com/v0.2/docs/how_to/tool_calling
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use a chat model to call tools On this page How to use a chat model to call tools ===================================== Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) * [LangChain Tools](/v0.2/docs/concepts/#tools) info We use the term tool calling interchangeably with function calling. Although function calling is sometimes meant to refer to invocations of a single function, we treat all models as though they can return multiple tool or function calls in each message. Tool calling allows a chat model to respond to a given prompt by “calling a tool”. While the name implies that the model is performing some action, this is actually not the case! The model generates the arguments to a tool, and actually running the tool (or not) is up to the user. For example, if you want to [extract output matching some schema](/v0.2/docs/how_to/structured_output/) from unstructured text, you could give the model an “extraction” tool that takes parameters matching the desired schema, then treat the generated output as your final result. However, tool calling goes beyond [structured output](/v0.2/docs/how_to/structured_output/) since you can pass responses to caled tools back to the model to create longer interactions. For instance, given a search engine tool, an LLM might handle a query by first issuing a call to the search engine with arguments. The system calling the LLM can receive the tool call, execute it, and return the output to the LLM to inform its response. LangChain includes a suite of [built-in tools](/v0.2/docs/integrations/tools/) and supports several methods for defining your own [custom tools](/v0.2/docs/how_to/custom_tools). Tool calling is not universal, but many popular LLM providers, including [Anthropic](https://www.anthropic.com/), [Cohere](https://cohere.com/), [Google](https://cloud.google.com/vertex-ai), [Mistral](https://mistral.ai/), [OpenAI](https://openai.com/), and others, support variants of a tool calling feature. LangChain implements standard interfaces for defining tools, passing them to LLMs, and representing tool calls. This guide will show you how to use them. Passing tools to LLMs[​](#passing-tools-to-llms "Direct link to Passing tools to LLMs") --------------------------------------------------------------------------------------- Chat models that support tool calling features implement a [`.bindTools()`](https://v02.api.js.langchain.com/classes/langchain_core_language_models_chat_models.BaseChatModel.html#bindTools) method, which receives a list of LangChain [tool objects](https://v02.api.js.langchain.com/classes/langchain_core_tools.StructuredTool.html) and binds them to the chat model in its expected format. Subsequent invocations of the chat model will include tool schemas in its calls to the LLM. note As of `@langchain/core` version `0.2.9`, all chat models with tool calling capabilities now support [OpenAI-formatted tools](https://api.js.langchain.com/interfaces/langchain_core_language_models_base.ToolDefinition.html). Let’s walk through a few examples: ### Pick your chat model: * Anthropic * OpenAI * MistralAI * FireworksAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic @langchain/core yarn add @langchain/anthropic @langchain/core pnpm add @langchain/anthropic @langchain/core #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai @langchain/core yarn add @langchain/openai @langchain/core pnpm add @langchain/openai @langchain/core #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai @langchain/core yarn add @langchain/mistralai @langchain/core pnpm add @langchain/mistralai @langchain/core #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community @langchain/core yarn add @langchain/community @langchain/core pnpm add @langchain/community @langchain/core #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); We can use the `.bindTools()` method to handle the conversion from LangChain tool to our model provider’s specific format and bind it to the model (i.e., passing it in each time the model is invoked). A number of models implement helper methods that will take care of formatting and binding different function-like objects to the model. Let’s create a new tool implementing a Zod schema, then bind it to the model: The `tool` function is available in `@langchain/core` version 0.2.7 and above. If you are on an older version of core, you should use instantiate and use [`DynamicStructuredTool`](https://api.js.langchain.com/classes/langchain_core_tools.DynamicStructuredTool.html) instead. import { tool } from "@langchain/core/tools";import { z } from "zod";/** * Note that the descriptions here are crucial, as they will be passed along * to the model along with the class name. */const calculatorSchema = z.object({ operation: z .enum(["add", "subtract", "multiply", "divide"]) .describe("The type of operation to execute."), number1: z.number().describe("The first number to operate on."), number2: z.number().describe("The second number to operate on."),});const calculatorTool = tool( async ({ operation, number1, number2 }) => { // Functions must return strings if (operation === "add") { return `${number1 + number2}`; } else if (operation === "subtract") { return `${number1 - number2}`; } else if (operation === "multiply") { return `${number1 * number2}`; } else if (operation === "divide") { return `${number1 / number2}`; } else { throw new Error("Invalid operation."); } }, { name: "calculator", description: "Can perform mathematical operations.", schema: calculatorSchema, });const llmWithTools = llm.bindTools([calculatorTool]); Now, let’s invoke it! We expect the model to use the calculator to answer the question: const res = await llmWithTools.invoke("What is 3 * 12");console.log(res.tool_calls); [ { name: 'calculator', args: { operation: 'multiply', number1: 3, number2: 12 }, id: 'call_5KWEQgV40XVoY1rqDhwyDmli' }] tip See a LangSmith trace for the above [here](https://smith.langchain.com/public/b2222205-7da9-4a5a-8efe-6bc62347705d/r). We can see that the response message contains a `tool_calls` field when the model decides to call the tool. This will be in LangChain’s standardized format. The `.tool_calls` attribute should contain valid tool calls. Note that on occasion, model providers may output malformed tool calls (e.g., arguments that are not valid JSON). When parsing fails in these cases, the message will contain instances of of [InvalidToolCall](https://v02.api.js.langchain.com/types/langchain_core_messages_tool.InvalidToolCall.html) objects in the `.invalid_tool_calls` attribute. An `InvalidToolCall` can have a name, string arguments, identifier, and error message. ### Streaming[​](#streaming "Direct link to Streaming") When tools are called in a streaming context, [message chunks](https://v02.api.js.langchain.com/classes/langchain_core_messages.BaseMessageChunk.html) will be populated with [tool call chunk](https://v02.api.js.langchain.com/types/langchain_core_messages_tool.ToolCallChunk.html) objects in a list via the `.tool_call_chunks` attribute. A `ToolCallChunk` includes optional string fields for the tool `name`, `args`, and `id`, and includes an optional integer field `index` that can be used to join chunks together. Fields are optional because portions of a tool call may be streamed across different chunks (e.g., a chunk that includes a substring of the arguments may have null values for the tool name and id). Because message chunks inherit from their parent message class, an [AIMessageChunk](https://v02.api.js.langchain.com/classes/langchain_core_messages.AIMessageChunk.html) with tool call chunks will also include `.tool_calls` and `.invalid_tool_calls` fields. These fields are parsed best-effort from the message’s tool call chunks. Note that not all providers currently support streaming for tool calls. If this is the case for your specific provider, the model will yield a single chunk with the entire call when you call `.stream()`. const stream = await llmWithTools.stream("What is 308 / 29");for await (const chunk of stream) { console.log(chunk.tool_call_chunks);} [ { name: "calculator", args: "", id: "call_rGqPR1ivppYUeBb0iSAF8HGP", index: 0 }][ { name: undefined, args: '{"', id: undefined, index: 0 } ][ { name: undefined, args: "operation", id: undefined, index: 0 } ][ { name: undefined, args: '":"', id: undefined, index: 0 } ][ { name: undefined, args: "divide", id: undefined, index: 0 } ][ { name: undefined, args: '","', id: undefined, index: 0 } ][ { name: undefined, args: "number", id: undefined, index: 0 } ][ { name: undefined, args: "1", id: undefined, index: 0 } ][ { name: undefined, args: '":', id: undefined, index: 0 } ][ { name: undefined, args: "308", id: undefined, index: 0 } ][ { name: undefined, args: ',"', id: undefined, index: 0 } ][ { name: undefined, args: "number", id: undefined, index: 0 } ][ { name: undefined, args: "2", id: undefined, index: 0 } ][ { name: undefined, args: '":', id: undefined, index: 0 } ][ { name: undefined, args: "29", id: undefined, index: 0 } ][ { name: undefined, args: "}", id: undefined, index: 0 } ][] Note that using the `concat` method on message chunks will merge their corresponding tool call chunks. This is the principle by which LangChain’s various [tool output parsers](/v0.2/docs/how_to/output_parser_structured/) support streaming. For example, below we accumulate tool call chunks: const streamWithAccumulation = await llmWithTools.stream( "What is 32993 - 2339");let final;for await (const chunk of streamWithAccumulation) { if (!final) { final = chunk; } else { final = final.concat(chunk); }}console.log(final.tool_calls); [ { name: "calculator", args: { operation: "subtract", number1: 32993, number2: 2339 }, id: "call_WMhL5X0fMBBZPNeyUZY53Xuw" }] Few shotting with tools[​](#few-shotting-with-tools "Direct link to Few shotting with tools") --------------------------------------------------------------------------------------------- You can give the model examples of how you would like tools to be called in order to guide generation by inputting manufactured tool call turns. For example, given the above calculator tool, we could define a new operator, `🦜`. Let’s see what happens when we use it naively: const res = await llmWithTools.invoke("What is 3 🦜 12");console.log(res.content);console.log(res.tool_calls); It seems like you've used an emoji (🦜) in your expression, which I'm not familiar with in a mathematical context. Could you clarify what operation you meant by using the parrot emoji? For example, did you mean addition, subtraction, multiplication, or division?[] It doesn’t quite know how to interpret `🦜` as an operation. Now, let’s try giving it an example in the form of a manufactured messages to steer it towards `divide`: import { HumanMessage, AIMessage, ToolMessage } from "@langchain/core/messages";const res = await llmWithTools.invoke([ new HumanMessage("What is 333382 🦜 1932?"), new AIMessage({ content: "", tool_calls: [ { id: "12345", name: "calulator", args: { number1: 333382, number2: 1932, operation: "divide", }, }, ], }), new ToolMessage({ tool_call_id: "12345", content: "The answer is 172.558.", }), new AIMessage("The answer is 172.558."), new HumanMessage("What is 3 🦜 12"),]);console.log(res.tool_calls); [ { name: "calculator", args: { operation: "divide", number1: 3, number2: 12 }, id: "call_BDuJv8QkDZ7N7Wsd6v5VDeVa" }] Binding model-specific formats (advanced)[​](#binding-model-specific-formats-advanced "Direct link to Binding model-specific formats (advanced)") ------------------------------------------------------------------------------------------------------------------------------------------------- Providers adopt different conventions for formatting tool schemas. For instance, OpenAI uses a format like this: * `type`: The type of the tool. At the time of writing, this is always “function”. * `function`: An object containing tool parameters. * `function.name`: The name of the schema to output. * `function.description`: A high level description of the schema to output. * `function.parameters`: The nested details of the schema you want to extract, formatted as a [JSON schema](https://json-schema.org/) object. We can bind this model-specific format directly to the model if needed. Here’s an example: import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-4o" });const modelWithTools = model.bind({ tools: [ { type: "function", function: { name: "calculator", description: "Can perform mathematical operations.", parameters: { type: "object", properties: { operation: { type: "string", description: "The type of operation to execute.", enum: ["add", "subtract", "multiply", "divide"], }, number1: { type: "number", description: "First integer" }, number2: { type: "number", description: "Second integer" }, }, required: ["number1", "number2"], }, }, }, ],});await modelWithTools.invoke(`Whats 119 times 8?`); AIMessage { lc_serializable: true, lc_kwargs: { content: "", tool_calls: [ { name: "calculator", args: { operation: "multiply", number1: 119, number2: 8 }, id: "call_pBlKOPNMRN4AAMkPaOKLLcyj" } ], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: [ { id: "call_pBlKOPNMRN4AAMkPaOKLLcyj", type: "function", function: [Object] } ] }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "", name: undefined, additional_kwargs: { function_call: undefined, tool_calls: [ { id: "call_pBlKOPNMRN4AAMkPaOKLLcyj", type: "function", function: { name: "calculator", arguments: '{"operation":"multiply","number1":119,"number2":8}' } } ] }, response_metadata: { tokenUsage: { completionTokens: 24, promptTokens: 85, totalTokens: 109 }, finish_reason: "tool_calls" }, tool_calls: [ { name: "calculator", args: { operation: "multiply", number1: 119, number2: 8 }, id: "call_pBlKOPNMRN4AAMkPaOKLLcyj" } ], invalid_tool_calls: []} This is functionally equivalent to the `bind_tools()` calls above. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ Now you’ve learned how to bind tool schemas to a chat model and to call those tools. Next, check out some more specific uses of tool calling: * [Building tool-using chains and agents](/v0.2/docs/how_to/#tools) * [Getting structured outputs from models](/v0.2/docs/how_to/structured_output/) * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to create a time-weighted retriever ](/v0.2/docs/how_to/time_weighted_vectorstore)[ Next How to call tools with multimodal data ](/v0.2/docs/how_to/tool_calls_multimodal) * [Passing tools to LLMs](#passing-tools-to-llms) * [Streaming](#streaming) * [Few shotting with tools](#few-shotting-with-tools) * [Binding model-specific formats (advanced)](#binding-model-specific-formats-advanced) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/code_splitter
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to split code On this page How to split code ================= Prerequisites This guide assumes familiarity with the following concepts: * [Text splitters](/v0.2/docs/concepts#text-splitters) * [Recursively splitting text by character](/v0.2/docs/how_to/recursive_text_splitter) [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) includes pre-built lists of separators that are useful for splitting text in a specific programming language. Supported languages include: "html" | "cpp" | "go" | "java" | "js" | "php" | "proto" | "python" | "rst" | "ruby" | "rust" | "scala" | "swift" | "markdown" | "latex" | "sol" To view the list of separators for a given language, pass one of the values from the list above into the `getSeparatorsForLanguage()` static method import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";RecursiveCharacterTextSplitter.getSeparatorsForLanguage("js"); [ "\nfunction ", "\nconst ", "\nlet ", "\nvar ", "\nclass ", "\nif ", "\nfor ", "\nwhile ", "\nswitch ", "\ncase ", "\ndefault ", "\n\n", "\n", " ", ""] JS[​](#js "Direct link to JS") ------------------------------ Here’s an example using the JS text splitter: const JS_CODE = `function helloWorld() { console.log("Hello, World!");}// Call the functionhelloWorld();`;const jsSplitter = RecursiveCharacterTextSplitter.fromLanguage("js", { chunkSize: 60, chunkOverlap: 0,});const jsDocs = await jsSplitter.createDocuments([JS_CODE]);jsDocs; [ Document { pageContent: 'function helloWorld() {\n console.log("Hello, World!");\n}', metadata: { loc: { lines: { from: 2, to: 4 } } } }, Document { pageContent: "// Call the function\nhelloWorld();", metadata: { loc: { lines: { from: 6, to: 7 } } } }] Python[​](#python "Direct link to Python") ------------------------------------------ Here’s an example for Python: const PYTHON_CODE = `def hello_world(): print("Hello, World!")# Call the functionhello_world()`;const pythonSplitter = RecursiveCharacterTextSplitter.fromLanguage("python", { chunkSize: 50, chunkOverlap: 0,});const pythonDocs = await pythonSplitter.createDocuments([PYTHON_CODE]);pythonDocs; [ Document { pageContent: 'def hello_world():\n print("Hello, World!")', metadata: { loc: { lines: { from: 2, to: 3 } } } }, Document { pageContent: "# Call the function\nhello_world()", metadata: { loc: { lines: { from: 5, to: 6 } } } }] Markdown[​](#markdown "Direct link to Markdown") ------------------------------------------------ Here’s an example of splitting on markdown separators: const markdownText = `# 🦜️🔗 LangChain⚡ Building applications with LLMs through composability ⚡## Quick Install\`\`\`bash# Hopefully this code block isn't splitpip install langchain\`\`\`As an open-source project in a rapidly developing field, we are extremely open to contributions.`;const mdSplitter = RecursiveCharacterTextSplitter.fromLanguage("markdown", { chunkSize: 60, chunkOverlap: 0,});const mdDocs = await mdSplitter.createDocuments([markdownText]);mdDocs; [ Document { pageContent: "# 🦜️🔗 LangChain", metadata: { loc: { lines: { from: 2, to: 2 } } } }, Document { pageContent: "⚡ Building applications with LLMs through composability ⚡", metadata: { loc: { lines: { from: 4, to: 4 } } } }, Document { pageContent: "## Quick Install", metadata: { loc: { lines: { from: 6, to: 6 } } } }, Document { pageContent: "```bash\n# Hopefully this code block isn't split", metadata: { loc: { lines: { from: 8, to: 9 } } } }, Document { pageContent: "pip install langchain", metadata: { loc: { lines: { from: 10, to: 10 } } } }, Document { pageContent: "```", metadata: { loc: { lines: { from: 11, to: 11 } } } }, Document { pageContent: "As an open-source project in a rapidly developing field, we", metadata: { loc: { lines: { from: 13, to: 13 } } } }, Document { pageContent: "are extremely open to contributions.", metadata: { loc: { lines: { from: 13, to: 13 } } } }] Latex[​](#latex "Direct link to Latex") --------------------------------------- Here’s an example on Latex text: const latexText = `\documentclass{article}\begin{document}\maketitle\section{Introduction}Large language models (LLMs) are a type of machine learning model that can be trained on vast amounts of text data to generate human-like language. In recent years, LLMs have made significant advances in a variety of natural language processing tasks, including language translation, text generation, and sentiment analysis.\subsection{History of LLMs}The earliest LLMs were developed in the 1980s and 1990s, but they were limited by the amount of data that could be processed and the computational power available at the time. In the past decade, however, advances in hardware and software have made it possible to train LLMs on massive datasets, leading to significant improvements in performance.\subsection{Applications of LLMs}LLMs have many applications in industry, including chatbots, content creation, and virtual assistants. They can also be used in academia for research in linguistics, psychology, and computational linguistics.\end{document}`;const latexSplitter = RecursiveCharacterTextSplitter.fromLanguage("latex", { chunkSize: 60, chunkOverlap: 0,});const latexDocs = await latexSplitter.createDocuments([latexText]);latexDocs; [ Document { pageContent: "documentclass{article}\n\n\begin{document}\n\nmaketitle", metadata: { loc: { lines: { from: 2, to: 6 } } } }, Document { pageContent: "section{Introduction}", metadata: { loc: { lines: { from: 8, to: 8 } } } }, Document { pageContent: "Large language models (LLMs) are a type of machine learning", metadata: { loc: { lines: { from: 9, to: 9 } } } }, Document { pageContent: "model that can be trained on vast amounts of text data to", metadata: { loc: { lines: { from: 9, to: 9 } } } }, Document { pageContent: "generate human-like language. In recent years, LLMs have", metadata: { loc: { lines: { from: 9, to: 9 } } } }, Document { pageContent: "made significant advances in a variety of natural language", metadata: { loc: { lines: { from: 9, to: 9 } } } }, Document { pageContent: "processing tasks, including language translation, text", metadata: { loc: { lines: { from: 9, to: 9 } } } }, Document { pageContent: "generation, and sentiment analysis.", metadata: { loc: { lines: { from: 9, to: 9 } } } }, Document { pageContent: "subsection{History of LLMs}", metadata: { loc: { lines: { from: 11, to: 11 } } } }, Document { pageContent: "The earliest LLMs were developed in the 1980s and 1990s,", metadata: { loc: { lines: { from: 12, to: 12 } } } }, Document { pageContent: "but they were limited by the amount of data that could be", metadata: { loc: { lines: { from: 12, to: 12 } } } }, Document { pageContent: "processed and the computational power available at the", metadata: { loc: { lines: { from: 12, to: 12 } } } }, Document { pageContent: "time. In the past decade, however, advances in hardware and", metadata: { loc: { lines: { from: 12, to: 12 } } } }, Document { pageContent: "software have made it possible to train LLMs on massive", metadata: { loc: { lines: { from: 12, to: 12 } } } }, Document { pageContent: "datasets, leading to significant improvements in", metadata: { loc: { lines: { from: 12, to: 12 } } } }, Document { pageContent: "performance.", metadata: { loc: { lines: { from: 12, to: 12 } } } }, Document { pageContent: "subsection{Applications of LLMs}", metadata: { loc: { lines: { from: 14, to: 14 } } } }, Document { pageContent: "LLMs have many applications in industry, including", metadata: { loc: { lines: { from: 15, to: 15 } } } }, Document { pageContent: "chatbots, content creation, and virtual assistants. They", metadata: { loc: { lines: { from: 15, to: 15 } } } }, Document { pageContent: "can also be used in academia for research in linguistics,", metadata: { loc: { lines: { from: 15, to: 15 } } } }, Document { pageContent: "psychology, and computational linguistics.", metadata: { loc: { lines: { from: 15, to: 15 } } } }, Document { pageContent: "end{document}", metadata: { loc: { lines: { from: 17, to: 17 } } } }] HTML[​](#html "Direct link to HTML") ------------------------------------ Here’s an example using an HTML text splitter: const htmlText = `<!DOCTYPE html><html> <head> <title>🦜️🔗 LangChain</title> <style> body { font-family: Arial, sans-serif; } h1 { color: darkblue; } </style> </head> <body> <div> <h1>🦜️🔗 LangChain</h1> <p>⚡ Building applications with LLMs through composability ⚡</p> </div> <div> As an open-source project in a rapidly developing field, we are extremely open to contributions. </div> </body></html>`;const htmlSplitter = RecursiveCharacterTextSplitter.fromLanguage("html", { chunkSize: 60, chunkOverlap: 0,});const htmlDocs = await htmlSplitter.createDocuments([htmlText]);htmlDocs; [ Document { pageContent: "<!DOCTYPE html>\n<html>", metadata: { loc: { lines: { from: 2, to: 3 } } } }, Document { pageContent: "<head>\n <title>🦜️🔗 LangChain</title>", metadata: { loc: { lines: { from: 4, to: 5 } } } }, Document { pageContent: "<style>\n body {\n font-family:", metadata: { loc: { lines: { from: 6, to: 8 } } } }, Document { pageContent: "Arial, sans-serif;\n }\n h1 {", metadata: { loc: { lines: { from: 8, to: 10 } } } }, Document { pageContent: "color: darkblue;\n }\n </style>", metadata: { loc: { lines: { from: 11, to: 13 } } } }, Document { pageContent: "</head>", metadata: { loc: { lines: { from: 14, to: 14 } } } }, Document { pageContent: "<body>", metadata: { loc: { lines: { from: 15, to: 15 } } } }, Document { pageContent: "<div>\n <h1>🦜️🔗 LangChain</h1>", metadata: { loc: { lines: { from: 16, to: 17 } } } }, Document { pageContent: "<p>⚡ Building applications with LLMs through composability", metadata: { loc: { lines: { from: 18, to: 18 } } } }, Document { pageContent: "⚡</p>\n </div>", metadata: { loc: { lines: { from: 18, to: 19 } } } }, Document { pageContent: "<div>\n As an open-source project in a rapidly", metadata: { loc: { lines: { from: 20, to: 21 } } } }, Document { pageContent: "developing field, we are extremely open to contributions.", metadata: { loc: { lines: { from: 21, to: 21 } } } }, Document { pageContent: "</div>\n </body>\n</html>", metadata: { loc: { lines: { from: 22, to: 24 } } } }] Solidity[​](#solidity "Direct link to Solidity") ------------------------------------------------ Here’s an example using of splitting on [Solidity](https://soliditylang.org/) code: const SOL_CODE = `pragma solidity ^0.8.20;contract HelloWorld { function add(uint a, uint b) pure public returns(uint) { return a + b; }}`;const solSplitter = RecursiveCharacterTextSplitter.fromLanguage("sol", { chunkSize: 128, chunkOverlap: 0,});const solDocs = await solSplitter.createDocuments([SOL_CODE]);solDocs; [ Document { pageContent: "pragma solidity ^0.8.20;", metadata: { loc: { lines: { from: 2, to: 2 } } } }, Document { pageContent: "contract HelloWorld {\n" + " function add(uint a, uint b) pure public returns(uint) {\n" + " return a + "... 9 more characters, metadata: { loc: { lines: { from: 3, to: 7 } } } }] PHP[​](#php "Direct link to PHP") --------------------------------- Here’s an example of splitting on PHP code: const PHP_CODE = `<?phpnamespace foo;class Hello { public function __construct() { }}function hello() { echo "Hello World!";}interface Human { public function breath();}trait Foo { }enum Color{ case Red; case Blue;}`;const phpSplitter = RecursiveCharacterTextSplitter.fromLanguage("php", { chunkSize: 50, chunkOverlap: 0,});const phpDocs = await phpSplitter.createDocuments([PHP_CODE]);phpDocs; [ Document { pageContent: "<?php\nnamespace foo;", metadata: { loc: { lines: { from: 1, to: 2 } } } }, Document { pageContent: "class Hello {", metadata: { loc: { lines: { from: 3, to: 3 } } } }, Document { pageContent: "public function __construct() { }\n}", metadata: { loc: { lines: { from: 4, to: 5 } } } }, Document { pageContent: 'function hello() {\n echo "Hello World!";\n}', metadata: { loc: { lines: { from: 6, to: 8 } } } }, Document { pageContent: "interface Human {\n public function breath();\n}", metadata: { loc: { lines: { from: 9, to: 11 } } } }, Document { pageContent: "trait Foo { }\nenum Color\n{\n case Red;", metadata: { loc: { lines: { from: 12, to: 15 } } } }, Document { pageContent: "case Blue;\n}", metadata: { loc: { lines: { from: 16, to: 17 } } } }] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned a method for splitting text on code-specific separators. Next, check out the [full tutorial on retrieval-augmented generation](/v0.2/docs/tutorials/rag). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use tools ](/v0.2/docs/how_to/chatbots_tools)[ Next How to do retrieval with contextual compression ](/v0.2/docs/how_to/contextual_compression) * [JS](#js) * [Python](#python) * [Markdown](#markdown) * [Latex](#latex) * [HTML](#html) * [Solidity](#solidity) * [PHP](#php) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/chatbots_retrieval
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to do retrieval On this page How to do retrieval =================== Prerequisites This guide assumes familiarity with the following: * [Chatbots](/v0.2/docs/tutorials/chatbot) * [Retrieval-augmented generation](/v0.2/docs/tutorials/rag) Retrieval is a common technique chatbots use to augment their responses with data outside a chat model’s training data. This section will cover how to implement retrieval in the context of chatbots, but it’s worth noting that retrieval is a very subtle and deep topic. Setup[​](#setup "Direct link to Setup") --------------------------------------- You’ll need to install a few packages, and set any LLM API keys: * npm * yarn * pnpm npm i @langchain/openai cheerio yarn add @langchain/openai cheerio pnpm add @langchain/openai cheerio Let’s also set up a chat model that we’ll use for the below examples. ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); Creating a retriever[​](#creating-a-retriever "Direct link to Creating a retriever") ------------------------------------------------------------------------------------ We’ll use [the LangSmith documentation](https://docs.smith.langchain.com) as source material and store the content in a vectorstore for later retrieval. Note that this example will gloss over some of the specifics around parsing and storing a data source - you can see more [in-depth documentation on creating retrieval systems here](/v0.2/docs/how_to/#qa-with-rag). Let’s use a document loader to pull text from the docs: import "cheerio";import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";const loader = new CheerioWebBaseLoader( "https://docs.smith.langchain.com/user_guide");const rawDocs = await loader.load();rawDocs[0].pageContent.length; 36687 Next, we split it into smaller chunks that the LLM’s context window can handle and store it in a vector database: import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 500, chunkOverlap: 0,});const allSplits = await textSplitter.splitDocuments(rawDocs); Then we embed and store those chunks in a vector database: import { OpenAIEmbeddings } from "@langchain/openai";import { MemoryVectorStore } from "langchain/vectorstores/memory";const vectorstore = await MemoryVectorStore.fromDocuments( allSplits, new OpenAIEmbeddings()); And finally, let’s create a retriever from our initialized vectorstore: const retriever = vectorstore.asRetriever(4);const docs = await retriever.invoke("how can langsmith help with testing?");console.log(docs); [ Document { pageContent: "These test cases can be uploaded in bulk, created on the fly, or exported from application traces. L"... 294 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: { from: 7, to: 7 } } } }, Document { pageContent: "We provide native rendering of chat messages, functions, and retrieve documents.Initial Test Set​Whi"... 347 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: { from: 6, to: 6 } } } }, Document { pageContent: "will help in curation of test cases that can help track regressions/improvements and development of "... 393 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: { from: 11, to: 11 } } } }, Document { pageContent: "that time period — this is especially handy for debugging production issues.LangSmith also allows fo"... 396 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: { from: 11, to: 11 } } } }] We can see that invoking the retriever above results in some parts of the LangSmith docs that contain information about testing that our chatbot can use as context when answering questions. And now we’ve got a retriever that can return related data from the LangSmith docs! Document chains[​](#document-chains "Direct link to Document chains") --------------------------------------------------------------------- Now that we have a retriever that can return LangChain docs, let’s create a chain that can use them as context to answer questions. We’ll use a `createStuffDocumentsChain` helper function to “stuff” all of the input documents into the prompt. It will also handle formatting the docs as strings. In addition to a chat model, the function also expects a prompt that has a `context` variable, as well as a placeholder for chat history messages named `messages`. We’ll create an appropriate prompt and pass it as shown below: import { createStuffDocumentsChain } from "langchain/chains/combine_documents";import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";const SYSTEM_TEMPLATE = `Answer the user's questions based on the below context. If the context doesn't contain any relevant information to the question, don't make something up and just say "I don't know":<context>{context}</context>`;const questionAnsweringPrompt = ChatPromptTemplate.fromMessages([ ["system", SYSTEM_TEMPLATE], new MessagesPlaceholder("messages"),]);const documentChain = await createStuffDocumentsChain({ llm, prompt: questionAnsweringPrompt,}); We can invoke this `documentChain` by itself to answer questions. Let’s use the docs we retrieved above and the same question, `how can langsmith help with testing?`: import { HumanMessage, AIMessage } from "@langchain/core/messages";await documentChain.invoke({ messages: [new HumanMessage("Can LangSmith help test my LLM applications?")], context: docs,}); "Yes, LangSmith can help test your LLM applications. It allows developers to create datasets, which a"... 229 more characters Looks good! For comparison, we can try it with no context docs and compare the result: await documentChain.invoke({ messages: [new HumanMessage("Can LangSmith help test my LLM applications?")], context: [],}); "I don't know." We can see that the LLM does not return any results. Retrieval chains[​](#retrieval-chains "Direct link to Retrieval chains") ------------------------------------------------------------------------ Let’s combine this document chain with the retriever. Here’s one way this can look: import type { BaseMessage } from "@langchain/core/messages";import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";const parseRetrieverInput = (params: { messages: BaseMessage[] }) => { return params.messages[params.messages.length - 1].content;};const retrievalChain = RunnablePassthrough.assign({ context: RunnableSequence.from([parseRetrieverInput, retriever]),}).assign({ answer: documentChain,}); Given a list of input messages, we extract the content of the last message in the list and pass that to the retriever to fetch some documents. Then, we pass those documents as context to our document chain to generate a final response. Invoking this chain combines both steps outlined above: await retrievalChain.invoke({ messages: [new HumanMessage("Can LangSmith help test my LLM applications?")],}); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "Can LangSmith help test my LLM applications?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Can LangSmith help test my LLM applications?", name: undefined, additional_kwargs: {}, response_metadata: {} } ], context: [ Document { pageContent: "These test cases can be uploaded in bulk, created on the fly, or exported from application traces. L"... 294 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each s"... 343 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "We provide native rendering of chat messages, functions, and retrieve documents.Initial Test Set​Whi"... 347 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "The ability to rapidly understand how the model is performing — and debug where it is failing — is i"... 138 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } } ], answer: "Yes, LangSmith can help test your LLM applications. It allows developers to create datasets, which a"... 297 more characters} Looks good! Query transformation[​](#query-transformation "Direct link to Query transformation") ------------------------------------------------------------------------------------ Our retrieval chain is capable of answering questions about LangSmith, but there’s a problem - chatbots interact with users conversationally, and therefore have to deal with followup questions. The chain in its current form will struggle with this. Consider a followup question to our original question like `Tell me more!`. If we invoke our retriever with that query directly, we get documents irrelevant to LLM application testing: await retriever.invoke("Tell me more!"); [ Document { pageContent: "Oftentimes, changes in the prompt, retrieval strategy, or model choice can have huge implications in"... 40 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: { from: 8, to: 8 } } } }, Document { pageContent: "This allows you to quickly test out different prompts and models. You can open the playground from a"... 37 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: { from: 10, to: 10 } } } }, Document { pageContent: "We provide native rendering of chat messages, functions, and retrieve documents.Initial Test Set​Whi"... 347 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: { from: 6, to: 6 } } } }, Document { pageContent: "together, making it easier to track the performance of and annotate your application across multiple"... 244 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: { from: 11, to: 11 } } } }] This is because the retriever has no innate concept of state, and will only pull documents most similar to the query given. To solve this, we can transform the query into a standalone query without any external references an LLM. Here’s an example: const queryTransformPrompt = ChatPromptTemplate.fromMessages([ new MessagesPlaceholder("messages"), [ "user", "Given the above conversation, generate a search query to look up in order to get information relevant to the conversation. Only respond with the query, nothing else.", ],]);const queryTransformationChain = queryTransformPrompt.pipe(llm);await queryTransformationChain.invoke({ messages: [ new HumanMessage("Can LangSmith help test my LLM applications?"), new AIMessage( "Yes, LangSmith can help test and evaluate your LLM applications. It allows you to quickly edit examples and add them to datasets to expand the surface area of your evaluation sets or to fine-tune a model for improved quality or reduced costs. Additionally, LangSmith can be used to monitor your application, log all traces, visualize latency and token usage statistics, and troubleshoot specific issues as they arise." ), new HumanMessage("Tell me more!"), ],}); AIMessage { lc_serializable: true, lc_kwargs: { content: '"LangSmith LLM application testing and evaluation features"', tool_calls: [], invalid_tool_calls: [], additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: '"LangSmith LLM application testing and evaluation features"', name: undefined, additional_kwargs: { function_call: undefined, tool_calls: undefined }, response_metadata: { tokenUsage: { completionTokens: 11, promptTokens: 144, totalTokens: 155 }, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: []} Awesome! That transformed query would pull up context documents related to LLM application testing. Let’s add this to our retrieval chain. We can wrap our retriever as follows: import { RunnableBranch } from "@langchain/core/runnables";import { StringOutputParser } from "@langchain/core/output_parsers";const queryTransformingRetrieverChain = RunnableBranch.from([ [ (params: { messages: BaseMessage[] }) => params.messages.length === 1, RunnableSequence.from([parseRetrieverInput, retriever]), ], queryTransformPrompt.pipe(llm).pipe(new StringOutputParser()).pipe(retriever),]).withConfig({ runName: "chat_retriever_chain" }); Then, we can use this query transformation chain to make our retrieval chain better able to handle such followup questions: const conversationalRetrievalChain = RunnablePassthrough.assign({ context: queryTransformingRetrieverChain,}).assign({ answer: documentChain,}); Awesome! Let’s invoke this new chain with the same inputs as earlier: await conversationalRetrievalChain.invoke({ messages: [new HumanMessage("Can LangSmith help test my LLM applications?")],}); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "Can LangSmith help test my LLM applications?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Can LangSmith help test my LLM applications?", name: undefined, additional_kwargs: {}, response_metadata: {} } ], context: [ Document { pageContent: "These test cases can be uploaded in bulk, created on the fly, or exported from application traces. L"... 294 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each s"... 343 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "We provide native rendering of chat messages, functions, and retrieve documents.Initial Test Set​Whi"... 347 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "The ability to rapidly understand how the model is performing — and debug where it is failing — is i"... 138 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } } ], answer: "Yes, LangSmith can help test your LLM applications. It allows developers to create datasets, which a"... 297 more characters} await conversationalRetrievalChain.invoke({ messages: [ new HumanMessage("Can LangSmith help test my LLM applications?"), new AIMessage( "Yes, LangSmith can help test and evaluate your LLM applications. It allows you to quickly edit examples and add them to datasets to expand the surface area of your evaluation sets or to fine-tune a model for improved quality or reduced costs. Additionally, LangSmith can be used to monitor your application, log all traces, visualize latency and token usage statistics, and troubleshoot specific issues as they arise." ), new HumanMessage("Tell me more!"), ],}); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "Can LangSmith help test my LLM applications?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Can LangSmith help test my LLM applications?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Yes, LangSmith can help test and evaluate your LLM applications. It allows you to quickly edit examp"... 317 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Yes, LangSmith can help test and evaluate your LLM applications. It allows you to quickly edit examp"... 317 more characters, name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "Tell me more!", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Tell me more!", name: undefined, additional_kwargs: {}, response_metadata: {} } ], context: [ Document { pageContent: "These test cases can be uploaded in bulk, created on the fly, or exported from application traces. L"... 294 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "We provide native rendering of chat messages, functions, and retrieve documents.Initial Test Set​Whi"... 347 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each s"... 343 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "will help in curation of test cases that can help track regressions/improvements and development of "... 393 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } } ], answer: "LangSmith supports a variety of workflows to aid in the development of your applications, from creat"... 607 more characters} You can check out [this LangSmith trace](https://smith.langchain.com/public/dc4d6bd4-fea5-45df-be94-06ad18882ae9/r) to see the internal query transformation step for yourself. Streaming[​](#streaming "Direct link to Streaming") --------------------------------------------------- Because this chain is constructed with LCEL, you can use familiar methods like `.stream()` with it: const stream = await conversationalRetrievalChain.stream({ messages: [ new HumanMessage("Can LangSmith help test my LLM applications?"), new AIMessage( "Yes, LangSmith can help test and evaluate your LLM applications. It allows you to quickly edit examples and add them to datasets to expand the surface area of your evaluation sets or to fine-tune a model for improved quality or reduced costs. Additionally, LangSmith can be used to monitor your application, log all traces, visualize latency and token usage statistics, and troubleshoot specific issues as they arise." ), new HumanMessage("Tell me more!"), ],});for await (const chunk of stream) { console.log(chunk);} { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "Can LangSmith help test my LLM applications?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Can LangSmith help test my LLM applications?", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Yes, LangSmith can help test and evaluate your LLM applications. It allows you to quickly edit examp"... 317 more characters, tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Yes, LangSmith can help test and evaluate your LLM applications. It allows you to quickly edit examp"... 317 more characters, name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [] }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "Tell me more!", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Tell me more!", name: undefined, additional_kwargs: {}, response_metadata: {} } ]}{ context: [ Document { pageContent: "These test cases can be uploaded in bulk, created on the fly, or exported from application traces. L"... 294 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "We provide native rendering of chat messages, functions, and retrieve documents.Initial Test Set​Whi"... 347 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each s"... 343 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } }, Document { pageContent: "will help in curation of test cases that can help track regressions/improvements and development of "... 393 more characters, metadata: { source: "https://docs.smith.langchain.com/user_guide", loc: { lines: [Object] } } } ]}{ answer: "" }{ answer: "Lang" }{ answer: "Smith" }{ answer: " offers" }{ answer: " a" }{ answer: " comprehensive" }{ answer: " suite" }{ answer: " of" }{ answer: " tools" }{ answer: " and" }{ answer: " workflows" }{ answer: " to" }{ answer: " support" }{ answer: " the" }{ answer: " development" }{ answer: " and" }{ answer: " testing" }{ answer: " of" }{ answer: " L" }{ answer: "LM" }{ answer: " applications" }{ answer: "." }{ answer: " Here" }{ answer: " are" }{ answer: " some" }{ answer: " key" }{ answer: " features" }{ answer: " and" }{ answer: " functionalities" }{ answer: ":\n\n" }{ answer: "1" }{ answer: "." }{ answer: " **" }{ answer: "Test" }{ answer: " Case" }{ answer: " Management" }{ answer: "**" }{ answer: ":\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "Bulk" }{ answer: " Upload" }{ answer: " and" }{ answer: " Creation" }{ answer: "**" }{ answer: ":" }{ answer: " You" }{ answer: " can" }{ answer: " upload" }{ answer: " test" }{ answer: " cases" }{ answer: " in" }{ answer: " bulk" }{ answer: "," }{ answer: " create" }{ answer: " them" }{ answer: " on" }{ answer: " the" }{ answer: " fly" }{ answer: "," }{ answer: " or" }{ answer: " export" }{ answer: " them" }{ answer: " from" }{ answer: " application" }{ answer: " traces" }{ answer: ".\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "Datas" }{ answer: "ets" }{ answer: "**" }{ answer: ":" }{ answer: " Lang" }{ answer: "Smith" }{ answer: " allows" }{ answer: " you" }{ answer: " to" }{ answer: " create" }{ answer: " datasets" }{ answer: "," }{ answer: " which" }{ answer: " are" }{ answer: " collections" }{ answer: " of" }{ answer: " inputs" }{ answer: " and" }{ answer: " reference" }{ answer: " outputs" }{ answer: "." }{ answer: " These" }{ answer: " datasets" }{ answer: " can" }{ answer: " be" }{ answer: " used" }{ answer: " to" }{ answer: " run" }{ answer: " tests" }{ answer: " on" }{ answer: " your" }{ answer: " L" }{ answer: "LM" }{ answer: " applications" }{ answer: ".\n\n" }{ answer: "2" }{ answer: "." }{ answer: " **" }{ answer: "Custom" }{ answer: " Evalu" }{ answer: "ations" }{ answer: "**" }{ answer: ":\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "LL" }{ answer: "M" }{ answer: " and" }{ answer: " He" }{ answer: "uristic" }{ answer: " Based" }{ answer: "**" }{ answer: ":" }{ answer: " You" }{ answer: " can" }{ answer: " run" }{ answer: " custom" }{ answer: " evaluations" }{ answer: " using" }{ answer: " both" }{ answer: " L" }{ answer: "LM" }{ answer: "-based" }{ answer: " and" }{ answer: " heuristic" }{ answer: "-based" }{ answer: " methods" }{ answer: " to" }{ answer: " score" }{ answer: " test" }{ answer: " results" }{ answer: ".\n\n" }{ answer: "3" }{ answer: "." }{ answer: " **" }{ answer: "Comparison" }{ answer: " View" }{ answer: "**" }{ answer: ":\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "Pro" }{ answer: "tot" }{ answer: "yp" }{ answer: "ing" }{ answer: " and" }{ answer: " Regression" }{ answer: " Tracking" }{ answer: "**" }{ answer: ":" }{ answer: " When" }{ answer: " prot" }{ answer: "otyping" }{ answer: " different" }{ answer: " versions" }{ answer: " of" }{ answer: " your" }{ answer: " applications" }{ answer: "," }{ answer: " Lang" }{ answer: "Smith" }{ answer: " provides" }{ answer: " a" }{ answer: " comparison" }{ answer: " view" }{ answer: " to" }{ answer: " see" }{ answer: " if" }{ answer: " there" }{ answer: " have" }{ answer: " been" }{ answer: " any" }{ answer: " regress" }{ answer: "ions" }{ answer: " with" }{ answer: " respect" }{ answer: " to" }{ answer: " your" }{ answer: " initial" }{ answer: " test" }{ answer: " cases" }{ answer: ".\n\n" }{ answer: "4" }{ answer: "." }{ answer: " **" }{ answer: "Native" }{ answer: " Rendering" }{ answer: "**" }{ answer: ":\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "Chat" }{ answer: " Messages" }{ answer: "," }{ answer: " Functions" }{ answer: "," }{ answer: " and" }{ answer: " Documents" }{ answer: "**" }{ answer: ":" }{ answer: " Lang" }{ answer: "Smith" }{ answer: " provides" }{ answer: " native" }{ answer: " rendering" }{ answer: " of" }{ answer: " chat" }{ answer: " messages" }{ answer: "," }{ answer: " functions" }{ answer: "," }{ answer: " and" }{ answer: " retrieved" }{ answer: " documents" }{ answer: "," }{ answer: " making" }{ answer: " it" }{ answer: " easier" }{ answer: " to" }{ answer: " visualize" }{ answer: " and" }{ answer: " understand" }{ answer: " the" }{ answer: " outputs" }{ answer: ".\n\n" }{ answer: "5" }{ answer: "." }{ answer: " **" }{ answer: "Pro" }{ answer: "tot" }{ answer: "yp" }{ answer: "ing" }{ answer: " Support" }{ answer: "**" }{ answer: ":\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "Quick" }{ answer: " Experiment" }{ answer: "ation" }{ answer: "**" }{ answer: ":" }{ answer: " The" }{ answer: " platform" }{ answer: " supports" }{ answer: " quick" }{ answer: " experimentation" }{ answer: " with" }{ answer: " different" }{ answer: " prompts" }{ answer: "," }{ answer: " model" }{ answer: " types" }{ answer: "," }{ answer: " retrieval" }{ answer: " strategies" }{ answer: "," }{ answer: " and" }{ answer: " other" }{ answer: " parameters" }{ answer: ".\n\n" }{ answer: "6" }{ answer: "." }{ answer: " **" }{ answer: "Feedback" }{ answer: " Capture" }{ answer: "**" }{ answer: ":\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "Human" }{ answer: " Feedback" }{ answer: "**" }{ answer: ":" }{ answer: " When" }{ answer: " launching" }{ answer: " your" }{ answer: " application" }{ answer: " to" }{ answer: " an" }{ answer: " initial" }{ answer: " set" }{ answer: " of" }{ answer: " users" }{ answer: "," }{ answer: " Lang" }{ answer: "Smith" }{ answer: " allows" }{ answer: " you" }{ answer: " to" }{ answer: " gather" }{ answer: " human" }{ answer: " feedback" }{ answer: " on" }{ answer: " the" }{ answer: " responses" }{ answer: "." }{ answer: " This" }{ answer: " helps" }{ answer: " identify" }{ answer: " interesting" }{ answer: " runs" }{ answer: " and" }{ answer: " highlight" }{ answer: " edge" }{ answer: " cases" }{ answer: " causing" }{ answer: " problematic" }{ answer: " responses" }{ answer: ".\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "Feedback" }{ answer: " Scores" }{ answer: "**" }{ answer: ":" }{ answer: " You" }{ answer: " can" }{ answer: " attach" }{ answer: " feedback" }{ answer: " scores" }{ answer: " to" }{ answer: " logged" }{ answer: " traces" }{ answer: "," }{ answer: " often" }{ answer: " integrated" }{ answer: " into" }{ answer: " the" }{ answer: " system" }{ answer: ".\n\n" }{ answer: "7" }{ answer: "." }{ answer: " **" }{ answer: "Monitoring" }{ answer: " and" }{ answer: " Troubles" }{ answer: "hooting" }{ answer: "**" }{ answer: ":\n" }{ answer: " " }{ answer: " -" }{ answer: " **" }{ answer: "Logging" }{ answer: " and" }{ answer: " Visualization" }{ answer: "**" }{ answer: ":" }{ answer: " Lang" }{ answer: "Smith" }{ answer: " logs" }{ answer: " all" }{ answer: " traces" }{ answer: "," }{ answer: " visual" }{ answer: "izes" }{ answer: " latency" }{ answer: " and" }{ answer: " token" }{ answer: " usage" }{ answer: " statistics" }{ answer: "," }{ answer: " and" }{ answer: " helps" }{ answer: " troubleshoot" }{ answer: " specific" }{ answer: " issues" }{ answer: " as" }{ answer: " they" }{ answer: " arise" }{ answer: ".\n\n" }{ answer: "Overall" }{ answer: "," }{ answer: " Lang" }{ answer: "Smith" }{ answer: " is" }{ answer: " designed" }{ answer: " to" }{ answer: " support" }{ answer: " the" }{ answer: " entire" }{ answer: " lifecycle" }{ answer: " of" }{ answer: " L" }{ answer: "LM" }{ answer: " application" }{ answer: " development" }{ answer: "," }{ answer: " from" }{ answer: " initial" }{ answer: " prot" }{ answer: "otyping" }{ answer: " to" }{ answer: " deployment" }{ answer: " and" }{ answer: " ongoing" }{ answer: " monitoring" }{ answer: "," }{ answer: " making" }{ answer: " it" }{ answer: " a" }{ answer: " powerful" }{ answer: " tool" }{ answer: " for" }{ answer: " developers" }{ answer: " looking" }{ answer: " to" }{ answer: " build" }{ answer: " and" }{ answer: " maintain" }{ answer: " high" }{ answer: "-quality" }{ answer: " L" }{ answer: "LM" }{ answer: " applications" }{ answer: "." }{ answer: "" } Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned some techniques for adding personal data as context to your chatbots. This guide only scratches the surface of retrieval techniques. For more on different ways of ingesting, preparing, and retrieving the most relevant data, check out our [how to guides on retrieval](/v0.2/docs/how_to/#retrievers). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to manage memory ](/v0.2/docs/how_to/chatbots_memory)[ Next How to use tools ](/v0.2/docs/how_to/chatbots_tools) * [Setup](#setup) * [Creating a retriever](#creating-a-retriever) * [Document chains](#document-chains) * [Retrieval chains](#retrieval-chains) * [Query transformation](#query-transformation) * [Streaming](#streaming) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/chatbots_tools
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use tools On this page How to use tools ================ Prerequisites This guide assumes familiarity with the following concepts: * [Chatbots](/v0.2/docs/concepts/#messages) * [Agents](/v0.2/docs/tutorials/agents) * [Chat history](/v0.2/docs/concepts/#chat-history) This section will cover how to create conversational agents: chatbots that can interact with other systems and APIs using tools. Setup[​](#setup "Direct link to Setup") --------------------------------------- For this guide, we’ll be using an [tool calling agent](/v0.2/docs/how_to/agent_executor) with a single tool for searching the web. The default will be powered by [Tavily](/v0.2/docs/integrations/tools/tavily_search), but you can switch it out for any similar tool. The rest of this section will assume you’re using Tavily. You’ll need to [sign up for an account on the Tavily website](https://tavily.com), and install the following packages: * npm * yarn * pnpm npm i @langchain/core @langchain/openai langchain yarn add @langchain/core @langchain/openai langchain pnpm add @langchain/core @langchain/openai langchain import { TavilySearchResults } from "@langchain/community/tools/tavily_search";import { ChatOpenAI } from "@langchain/openai";const tools = [ new TavilySearchResults({ maxResults: 1, }),];const llm = new ChatOpenAI({ model: "gpt-3.5-turbo-1106", temperature: 0,}); To make our agent conversational, we must also choose a prompt with a placeholder for our chat history. Here’s an example: import { ChatPromptTemplate } from "@langchain/core/prompts";// Adapted from https://smith.langchain.com/hub/jacob/tool-calling-agentconst prompt = ChatPromptTemplate.fromMessages([ [ "system", "You are a helpful assistant. You may not need to use tools for every query - the user may just want to chat!", ], ["placeholder", "{messages}"], ["placeholder", "{agent_scratchpad}"],]); Great! Now let’s assemble our agent: import { AgentExecutor, createToolCallingAgent } from "langchain/agents";const agent = await createToolCallingAgent({ llm, tools, prompt,});const agentExecutor = new AgentExecutor({ agent, tools }); Running the agent[​](#running-the-agent "Direct link to Running the agent") --------------------------------------------------------------------------- Now that we’ve set up our agent, let’s try interacting with it! It can handle both trivial queries that require no lookup: import { HumanMessage } from "@langchain/core/messages";await agentExecutor.invoke({ messages: [new HumanMessage("I'm Nemo!")],}); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "I'm Nemo!", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "I'm Nemo!", name: undefined, additional_kwargs: {}, response_metadata: {} } ], output: "Hi Nemo! It's great to meet you. How can I assist you today?"} Or, it can use of the passed search tool to get up to date information if needed: await agentExecutor.invoke({ messages: [ new HumanMessage( "What is the current conservation status of the Great Barrier Reef?" ), ],}); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "What is the current conservation status of the Great Barrier Reef?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "What is the current conservation status of the Great Barrier Reef?", name: undefined, additional_kwargs: {}, response_metadata: {} } ], output: "The Great Barrier Reef has recorded its highest amount of coral cover since the Australian Institute"... 688 more characters} Conversational responses[​](#conversational-responses "Direct link to Conversational responses") ------------------------------------------------------------------------------------------------ Because our prompt contains a placeholder for chat history messages, our agent can also take previous interactions into account and respond conversationally like a standard chatbot: import { AIMessage } from "@langchain/core/messages";await agentExecutor.invoke({ messages: [ new HumanMessage("I'm Nemo!"), new AIMessage("Hello Nemo! How can I assist you today?"), new HumanMessage("What is my name?"), ],}); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "I'm Nemo!", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "I'm Nemo!", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Hello Nemo! How can I assist you today?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello Nemo! How can I assist you today?", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [], usage_metadata: undefined }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "What is my name?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "What is my name?", name: undefined, additional_kwargs: {}, response_metadata: {} } ], output: "Your name is Nemo!"} If preferred, you can also wrap the agent executor in a [`RunnableWithMessageHistory`](/v0.2/docs/how_to/message_history/) class to internally manage history messages. Let’s redeclare it this way: const agent2 = await createToolCallingAgent({ llm, tools, prompt,});const agentExecutor2 = new AgentExecutor({ agent: agent2, tools }); Then, because our agent executor has multiple outputs, we also have to set the `outputMessagesKey` property when initializing the wrapper: import { ChatMessageHistory } from "langchain/stores/message/in_memory";import { RunnableWithMessageHistory } from "@langchain/core/runnables";const demoEphemeralChatMessageHistory = new ChatMessageHistory();const conversationalAgentExecutor = new RunnableWithMessageHistory({ runnable: agentExecutor2, getMessageHistory: (_sessionId) => demoEphemeralChatMessageHistory, inputMessagesKey: "messages", outputMessagesKey: "output",});await conversationalAgentExecutor.invoke( { messages: [new HumanMessage("I'm Nemo!")] }, { configurable: { sessionId: "unused" } }); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "I'm Nemo!", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "I'm Nemo!", name: undefined, additional_kwargs: {}, response_metadata: {} } ], output: "Hi Nemo! It's great to meet you. How can I assist you today?"} await conversationalAgentExecutor.invoke( { messages: [new HumanMessage("What is my name?")] }, { configurable: { sessionId: "unused" } }); { messages: [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "I'm Nemo!", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "I'm Nemo!", name: undefined, additional_kwargs: {}, response_metadata: {} }, AIMessage { lc_serializable: true, lc_kwargs: { content: "Hi Nemo! It's great to meet you. How can I assist you today?", tool_calls: [], invalid_tool_calls: [], additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hi Nemo! It's great to meet you. How can I assist you today?", name: undefined, additional_kwargs: {}, response_metadata: {}, tool_calls: [], invalid_tool_calls: [], usage_metadata: undefined }, HumanMessage { lc_serializable: true, lc_kwargs: { content: "What is my name?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "What is my name?", name: undefined, additional_kwargs: {}, response_metadata: {} } ], output: "Your name is Nemo!"} Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to create chatbots with tool-use capabilities. For more, check out the other guides in this section, including [how to add history to your chatbots](/v0.2/docs/how_to/chatbots_memory). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to do retrieval ](/v0.2/docs/how_to/chatbots_retrieval)[ Next How to split code ](/v0.2/docs/how_to/code_splitter) * [Setup](#setup) * [Running the agent](#running-the-agent) * [Conversational responses](#conversational-responses) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/streaming
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to stream On this page How to stream ============= Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) * [LangChain Expression Language](/v0.2/docs/concepts/#langchain-expression-language-lcel) * [Output parsers](/v0.2/docs/concepts/#output-parsers) Streaming is critical in making applications based on LLMs feel responsive to end-users. Important LangChain primitives like LLMs, parsers, prompts, retrievers, and agents implement the LangChain Runnable Interface. This interface provides two general approaches to stream content: * `.stream()`: a default implementation of streaming that streams the final output from the chain. * `streamEvents()` and `streamLog()`: these provide a way to stream both intermediate steps and final output from the chain. Let’s take a look at both approaches! For a higher-level overview of streaming techniques in LangChain, see [this section of the conceptual guide](/v0.2/docs/concepts/#streaming). Using Stream ============ All `Runnable` objects implement a method called stream. These methods are designed to stream the final output in chunks, yielding each chunk as soon as it is available. Streaming is only possible if all steps in the program know how to process an **input stream**; i.e., process an input chunk one at a time, and yield a corresponding output chunk. The complexity of this processing can vary, from straightforward tasks like emitting tokens produced by an LLM, to more challenging ones like streaming parts of JSON results before the entire JSON is complete. The best place to start exploring streaming is with the single most important components in LLM apps – the models themselves! LLMs and Chat Models[​](#llms-and-chat-models "Direct link to LLMs and Chat Models") ------------------------------------------------------------------------------------ Large language models can take several seconds to generate a complete response to a query. This is far slower than the **~200-300 ms** threshold at which an application feels responsive to an end user. The key strategy to make the application feel more responsive is to show intermediate progress; e.g., to stream the output from the model token by token. import "dotenv/config"; ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const model = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const model = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const model = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const model = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); // | output: false// | echo: falseimport { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-4o",}); const stream = await model.stream("Hello! Tell me about yourself.");const chunks = [];for await (const chunk of stream) { chunks.push(chunk); console.log(`${chunk.content}|`);} |Hello|!| I'm| an| AI| language| model| created| by| Open|AI|,| designed| to| assist| with| a| wide| range| of| tasks| by| understanding| and| generating| human|-like| text| based| on| the| input| I| receive|.| I| can| help| answer| questions|,| provide| explanations|,| offer| advice|,| write| creatively|,| and| much| more|.| How| can| I| assist| you| today|?|| Let’s have a look at one of the raw chunks: chunks[0]; AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: []} We got back something called an `AIMessageChunk`. This chunk represents a part of an `AIMessage`. Message chunks are additive by design – one can simply add them up using the `.concat()` method to get the state of the response so far! let finalChunk = chunks[0];for (const chunk of chunks.slice(1, 5)) { finalChunk = finalChunk.concat(chunk);}finalChunk; AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "Hello! I'm an", additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_call_chunks: [], tool_calls: [], invalid_tool_calls: [] }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello! I'm an", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: []} Chains[​](#chains "Direct link to Chains") ------------------------------------------ Virtually all LLM applications involve more steps than just a call to a language model. Let’s build a simple chain using `LangChain Expression Language` (`LCEL`) that combines a prompt, model and a parser and verify that streaming works. We will use `StringOutputParser` to parse the output from the model. This is a simple parser that extracts the content field from an `AIMessageChunk`, giving us the `token` returned by the model. tip LCEL is a declarative way to specify a “program” by chainining together different LangChain primitives. Chains created using LCEL benefit from an automatic implementation of stream, allowing streaming of the final output. In fact, chains created with LCEL implement the entire standard Runnable interface. import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";const prompt = ChatPromptTemplate.fromTemplate("Tell me a joke about {topic}");const parser = new StringOutputParser();const chain = prompt.pipe(model).pipe(parser);const stream = await chain.stream({ topic: "parrot",});for await (const chunk of stream) { console.log(`${chunk}|`);} |Sure|!| Here's| a| par|rot| joke| for| you|:|Why| did| the| par|rot| get| a| job|?|Because| he| was| tired| of| being| "|pol|ly|-em|ployment|!"| 🎉|🦜|| note You do not have to use the `LangChain Expression Language` to use LangChain and can instead rely on a standard **imperative** programming approach by caling `invoke`, `batch` or `stream` on each component individually, assigning the results to variables and then using them downstream as you see fit. If that works for your needs, then that’s fine by us 👌! ### Working with Input Streams[​](#working-with-input-streams "Direct link to Working with Input Streams") What if you wanted to stream JSON from the output as it was being generated? If you were to rely on `JSON.parse` to parse the partial json, the parsing would fail as the partial json wouldn’t be valid json. You’d likely be at a complete loss of what to do and claim that it wasn’t possible to stream JSON. Well, turns out there is a way to do it - the parser needs to operate on the **input stream**, and attempt to “auto-complete” the partial json into a valid state. Let’s see such a parser in action to understand what this means. import { JsonOutputParser } from "@langchain/core/output_parsers";const chain = model.pipe(new JsonOutputParser());const stream = await chain.stream( `Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`);for await (const chunk of stream) { console.log(chunk);} { countries: [ { name: "France", population: 67372000 }, { name: "Spain", population: 47450795 }, { name: "Japan", population: 125960000 } ]} Now, let’s **break** streaming. We’ll use the previous example and append an extraction function at the end that extracts the country names from the finalized JSON. Since this new last step is just a function call with no defined streaming behavior, the streaming output from previous steps is aggregated, then passed as a single input to the function. danger Any steps in the chain that operate on **finalized inputs** rather than on **input streams** can break streaming functionality via `stream`. tip Later, we will discuss the `streamEvents` API which streams results from intermediate steps. This API will stream results from intermediate steps even if the chain contains steps that only operate on **finalized inputs**. // A function that operates on finalized inputs// rather than on an input_stream// A function that does not operates on input streams and breaks streaming.const extractCountryNames = (inputs: Record<string, any>) => { if (!Array.isArray(inputs.countries)) { return ""; } return JSON.stringify(inputs.countries.map((country) => country.name));};const chain = model.pipe(new JsonOutputParser()).pipe(extractCountryNames);const stream = await chain.stream( `output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`);for await (const chunk of stream) { console.log(chunk);} ["France","Spain","Japan"] ### Non-streaming components[​](#non-streaming-components "Direct link to Non-streaming components") Like the above example, some built-in components like Retrievers do not offer any streaming. What happens if we try to `stream` them? import { OpenAIEmbeddings } from "@langchain/openai";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { ChatPromptTemplate } from "@langchain/core/prompts";const template = `Answer the question based only on the following context:{context}Question: {question}`;const prompt = ChatPromptTemplate.fromTemplate(template);const vectorstore = await MemoryVectorStore.fromTexts( ["mitochondria is the powerhouse of the cell", "buildings are made of brick"], [{}, {}], new OpenAIEmbeddings());const retriever = vectorstore.asRetriever();const chunks = [];for await (const chunk of await retriever.stream( "What is the powerhouse of the cell?")) { chunks.push(chunk);}console.log(chunks); [ [ Document { pageContent: "mitochondria is the powerhouse of the cell", metadata: {} }, Document { pageContent: "buildings are made of brick", metadata: {} } ]] Stream just yielded the final result from that component. This is OK! Not all components have to implement streaming – in some cases streaming is either unnecessary, difficult or just doesn’t make sense. tip An LCEL chain constructed using some non-streaming components will still be able to stream in a lot of cases, with streaming of partial output starting after the last non-streaming step in the chain. Here’s an example of this: import { RunnablePassthrough, RunnableSequence,} from "@langchain/core/runnables";import type { Document } from "@langchain/core/documents";import { StringOutputParser } from "@langchain/core/output_parsers";const formatDocs = (docs: Document[]) => { return docs.map((doc) => doc.pageContent).join("\n-----\n");};const retrievalChain = RunnableSequence.from([ { context: retriever.pipe(formatDocs), question: new RunnablePassthrough(), }, prompt, model, new StringOutputParser(),]);const stream = await retrievalChain.stream( "What is the powerhouse of the cell?");for await (const chunk of stream) { console.log(`${chunk}|`);} |M|ito|ch|ond|ria| is| the| powerhouse| of| the| cell|.|| Now that we’ve seen how the `stream` method works, let’s venture into the world of streaming events! Using Stream Events[​](#using-stream-events "Direct link to Using Stream Events") --------------------------------------------------------------------------------- Event Streaming is a **beta** API. This API may change a bit based on feedback. note Introduced in @langchain/core **0.1.27**. For the `streamEvents` method to work properly: * Any custom functions / runnables must propragate callbacks * Set proper parameters on models to force the LLM to stream tokens. * Let us know if anything doesn’t work as expected! ### Event Reference[​](#event-reference "Direct link to Event Reference") Below is a reference table that shows some events that might be emitted by the various Runnable objects. note When streaming is implemented properly, the inputs to a runnable will not be known until after the input stream has been entirely consumed. This means that `inputs` will often be included only for `end` events and rather than for `start` events. event name chunk input output on\_llm\_start \[model name\] {‘input’: ‘hello’} on\_llm\_stream \[model name\] ‘Hello’ `or` AIMessageChunk(content=“hello”) on\_llm\_end \[model name\] ‘Hello human!’ {“generations”: \[…\], “llmOutput”: None, …} on\_chain\_start format\_docs on\_chain\_stream format\_docs “hello world!, goodbye world!” on\_chain\_end format\_docs \[Document(…)\] “hello world!, goodbye world!” on\_tool\_start some\_tool {“x”: 1, “y”: “2”} on\_tool\_stream some\_tool {“x”: 1, “y”: “2”} on\_tool\_end some\_tool {“x”: 1, “y”: “2”} on\_retriever\_start \[retriever name\] {“query”: “hello”} on\_retriever\_chunk \[retriever name\] {documents: \[…\]} on\_retriever\_end \[retriever name\] {“query”: “hello”} {documents: \[…\]} on\_prompt\_start \[template\_name\] {“question”: “hello”} on\_prompt\_end \[template\_name\] {“question”: “hello”} ChatPromptValue(messages: \[SystemMessage, …\]) ### Chat Model[​](#chat-model "Direct link to Chat Model") Let’s start off by looking at the events produced by a chat model. const events = [];const eventStream = await model.streamEvents("hello", { version: "v1" });for await (const event of eventStream) { events.push(event);} 13 note Hey what’s that funny version=“v1” parameter in the API?! 😾 This is a **beta API**, and we’re almost certainly going to make some changes to it. This version parameter will allow us to mimimize such breaking changes to your code. In short, we are annoying you now, so we don’t have to annoy you later. Let’s take a look at the few of the start event and a few of the end events. events.slice(0, 3); [ { run_id: "3394874b-6a19-4d2c-a80f-bd3ff7f25e85", event: "on_llm_start", name: "ChatOpenAI", tags: [], metadata: {}, data: { input: "hello" } }, { event: "on_llm_stream", run_id: "3394874b-6a19-4d2c-a80f-bd3ff7f25e85", tags: [], metadata: {}, name: "ChatOpenAI", data: { chunk: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }, { event: "on_llm_stream", run_id: "3394874b-6a19-4d2c-a80f-bd3ff7f25e85", tags: [], metadata: {}, name: "ChatOpenAI", data: { chunk: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "Hello", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Hello", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }] events.slice(-2); [ { event: "on_llm_stream", run_id: "3394874b-6a19-4d2c-a80f-bd3ff7f25e85", tags: [], metadata: {}, name: "ChatOpenAI", data: { chunk: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: "stop" }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }, { event: "on_llm_end", name: "ChatOpenAI", run_id: "3394874b-6a19-4d2c-a80f-bd3ff7f25e85", tags: [], metadata: {}, data: { output: { generations: [ [Array] ] } } }] ### Chain[​](#chain "Direct link to Chain") Let’s revisit the example chain that parsed streaming JSON to explore the streaming events API. const chain = model.pipe(new JsonOutputParser());const eventStream = await chain.streamEvents( `Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`, { version: "v1" });const events = [];for await (const event of eventStream) { events.push(event);} 84 If you examine at the first few events, you’ll notice that there are **3** different start events rather than **2** start events. The three start events correspond to: 1. The chain (model + parser) 2. The model 3. The parser events.slice(0, 3); [ { run_id: "289af8b8-7047-44e6-a475-26b88ddc7e34", event: "on_chain_start", name: "RunnableSequence", tags: [], metadata: {}, data: { input: "Output a list of the countries france, spain and japan and their populations in JSON format. Use a d"... 129 more characters } }, { event: "on_llm_start", name: "ChatOpenAI", run_id: "d43b539d-23ae-42ad-9bec-64faf58cf423", tags: [ "seq:step:1" ], metadata: {}, data: { input: { messages: [ [Array] ] } } }, { event: "on_parser_start", name: "JsonOutputParser", run_id: "91b6f786-0838-4888-8c2d-25ecd5d62d47", tags: [ "seq:step:2" ], metadata: {}, data: {} }] What do you think you’d see if you looked at the last 3 events? what about the middle? Let’s use this API to take output the stream events from the model and the parser. We’re ignoring start events, end events and events from the chain. let eventCount = 0;const eventStream = await chain.streamEvents( `Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`, { version: "v1" });for await (const event of eventStream) { // Truncate the output if (eventCount > 30) { continue; } const eventType = event.event; if (eventType === "on_llm_stream") { console.log(`Chat model chunk: ${event.data.chunk.message.content}`); } else if (eventType === "on_parser_stream") { console.log(`Parser chunk: ${JSON.stringify(event.data.chunk)}`); } eventCount += 1;} Chat model chunk:Chat model chunk: ```Chat model chunk: jsonChat model chunk:Chat model chunk: {Chat model chunk:Chat model chunk: "Chat model chunk: countriesChat model chunk: ":Chat model chunk: [Chat model chunk:Chat model chunk: {Chat model chunk:Chat model chunk: "Chat model chunk: nameChat model chunk: ":Chat model chunk: "Chat model chunk: FranceChat model chunk: ",Chat model chunk:Chat model chunk: "Chat model chunk: populationChat model chunk: ":Chat model chunk:Chat model chunk: 673Chat model chunk: 480Chat model chunk: 00Chat model chunk: Because both the model and the parser support streaming, we see streaming events from both components in real time! Neat! 🦜 ### Filtering Events[​](#filtering-events "Direct link to Filtering Events") Because this API produces so many events, it is useful to be able to filter on events. You can filter by either component `name`, component `tags` or component `type`. #### By Name[​](#by-name "Direct link to By Name") const chain = model .withConfig({ runName: "model" }) .pipe(new JsonOutputParser().withConfig({ runName: "my_parser" }));const eventStream = await chain.streamEvents( `Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`, { version: "v1" }, { includeNames: ["my_parser"] });let eventCount = 0;for await (const event of eventStream) { // Truncate the output if (eventCount > 10) { continue; } console.log(event); eventCount += 1;} { event: "on_parser_start", name: "my_parser", run_id: "bd05589a-0725-486b-b814-81af62ba5d80", tags: [ "seq:step:2" ], metadata: {}, data: {}}{ event: "on_parser_stream", name: "my_parser", run_id: "bd05589a-0725-486b-b814-81af62ba5d80", tags: [ "seq:step:2" ], metadata: {}, data: { chunk: { countries: [ { name: "France", population: 65273511 }, { name: "Spain", population: 46754778 }, { name: "Japan", population: 126476461 } ] } }}{ event: "on_parser_end", name: "my_parser", run_id: "bd05589a-0725-486b-b814-81af62ba5d80", tags: [ "seq:step:2" ], metadata: {}, data: { output: { countries: [ { name: "France", population: 65273511 }, { name: "Spain", population: 46754778 }, { name: "Japan", population: 126476461 } ] } }} 3 #### By type[​](#by-type "Direct link to By type") const chain = model .withConfig({ runName: "model" }) .pipe(new JsonOutputParser().withConfig({ runName: "my_parser" }));const eventStream = await chain.streamEvents( `Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`, { version: "v1" }, { includeTypes: ["llm"] });let eventCount = 0;for await (const event of eventStream) { // Truncate the output if (eventCount > 10) { continue; } console.log(event); eventCount += 1;} { event: "on_llm_start", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { input: { messages: [ [ [HumanMessage] ] ] } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: "", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: "Sure", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "Sure", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "Sure", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: ",", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: ",", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: ",", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: " here's", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: " here's", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: " here's", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: " the", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: " the", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: " the", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: " JSON", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: " JSON", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: " JSON", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: " representation", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: " representation", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: " representation", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: " of", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: " of", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: " of", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: " the", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: " the", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: " the", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "model", run_id: "4c7dbe4a-57ea-40b9-9fc0-a77d7851c5fd", tags: [ "seq:step:1" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: " countries", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: " countries", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: " countries", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }} #### By Tags[​](#by-tags "Direct link to By Tags") caution Tags are inherited by child components of a given runnable. If you’re using tags to filter, make sure that this is what you want. const chain = model .pipe(new JsonOutputParser().withConfig({ runName: "my_parser" })) .withConfig({ tags: ["my_chain"] });const eventStream = await chain.streamEvents( `Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`, { version: "v1" }, { includeTags: ["my_chain"] });let eventCount = 0;for await (const event of eventStream) { // Truncate the output if (eventCount > 10) { continue; } console.log(event); eventCount += 1;} { run_id: "83f4ef67-4970-44f7-8ae1-5ebace8cbce0", event: "on_chain_start", name: "RunnableSequence", tags: [ "my_chain" ], metadata: {}, data: { input: "Output a list of the countries france, spain and japan and their populations in JSON format. Use a d"... 129 more characters }}{ event: "on_llm_start", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { input: { messages: [ [ [HumanMessage] ] ] } }}{ event: "on_parser_start", name: "my_parser", run_id: "346234e7-b109-4bf7-a568-70edd67bc209", tags: [ "seq:step:2", "my_chain" ], metadata: {}, data: {}}{ event: "on_llm_stream", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: "", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: "```", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "```", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "```", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: "json", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "json", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "json", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: "\n", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "\n", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "\n", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: "{\n", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "{\n", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "{\n", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: " ", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: " ", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: " ", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: ' "', generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: ' "', tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: ' "', name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }}{ event: "on_llm_stream", name: "ChatOpenAI", run_id: "d84bca89-bc85-4d1d-a7af-3403f5789bd0", tags: [ "seq:step:1", "my_chain" ], metadata: {}, data: { chunk: ChatGenerationChunk { text: "countries", generationInfo: { prompt: 0, completion: 0, finish_reason: null }, message: AIMessageChunk { lc_serializable: true, lc_kwargs: { content: "countries", tool_call_chunks: [], additional_kwargs: {}, tool_calls: [], invalid_tool_calls: [], response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "countries", name: undefined, additional_kwargs: {}, response_metadata: { prompt: 0, completion: 0, finish_reason: null }, tool_calls: [], invalid_tool_calls: [], tool_call_chunks: [] } } }} ### Streaming events over HTTP[​](#streaming-events-over-http "Direct link to Streaming events over HTTP") For convenience, `streamEvents` supports encoding streamed intermediate events as HTTP [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), encoded as bytes. Here’s what that looks like (using a [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) to reconvert the binary data back into a human readable string): const chain = model .pipe(new JsonOutputParser().withConfig({ runName: "my_parser" })) .withConfig({ tags: ["my_chain"] });const eventStream = await chain.streamEvents( `Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`, { version: "v1", encoding: "text/event-stream", });let eventCount = 0;const textDecoder = new TextDecoder();for await (const event of eventStream) { // Truncate the output if (eventCount > 3) { continue; } console.log(textDecoder.decode(event)); eventCount += 1;} event: datadata: {"run_id":"9344be82-f4e6-49be-9eea-88eb2ae53340","event":"on_chain_start","name":"RunnableSequence","tags":["my_chain"],"metadata":{},"data":{"input":"Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key \"name\" and \"population\""}}event: datadata: {"event":"on_llm_start","name":"ChatOpenAI","run_id":"20640210-4b45-4ac3-9e5e-ad6e6d48431f","tags":["seq:step:1","my_chain"],"metadata":{},"data":{"input":{"messages":[[{"lc":1,"type":"constructor","id":["langchain_core","messages","HumanMessage"],"kwargs":{"content":"Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key \"name\" and \"population\"","additional_kwargs":{},"response_metadata":{}}}]]}}}event: datadata: {"event":"on_parser_start","name":"my_parser","run_id":"0d035118-36bc-49a3-9bdd-5fcf8afcc5da","tags":["seq:step:2","my_chain"],"metadata":{},"data":{}}event: datadata: {"event":"on_llm_stream","name":"ChatOpenAI","run_id":"20640210-4b45-4ac3-9e5e-ad6e6d48431f","tags":["seq:step:1","my_chain"],"metadata":{},"data":{"chunk":{"text":"","generationInfo":{"prompt":0,"completion":0,"finish_reason":null},"message":{"lc":1,"type":"constructor","id":["langchain_core","messages","AIMessageChunk"],"kwargs":{"content":"","tool_call_chunks":[],"additional_kwargs":{},"tool_calls":[],"invalid_tool_calls":[],"response_metadata":{"prompt":0,"completion":0,"finish_reason":null}}}}}} A nice feature of this format is that you can pass the resulting stream directly into a native [HTTP response object](https://developer.mozilla.org/en-US/docs/Web/API/Response) with the correct headers (commonly used by frameworks like [Hono](https://hono.dev/) and [Next.js](https://nextjs.org/)), then parse that stream on the frontend. Your server-side handler would look something like this: const handler = async () => { const eventStream = await chain.streamEvents( `Output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`, { version: "v1", encoding: "text/event-stream", } ); return new Response(eventStream, { headers: { "content-type": "text/event-stream", }, });}; And your frontend could look like this (using the [`@microsoft/fetch-event-source`](https://www.npmjs.com/package/@microsoft/fetch-event-source) pacakge to fetch and parse the event source): import { fetchEventSource } from "@microsoft/fetch-event-source";const makeChainRequest = async () => { await fetchEventSource("https://your_url_here", { method: "POST", body: JSON.stringify({ foo: "bar", }), onmessage: (message) => { if (message.event === "data") { console.log(message.data); } }, onerror: (err) => { console.log(err); }, });}; ### Non-streaming components[​](#non-streaming-components-1 "Direct link to Non-streaming components") Remember how some components don’t stream well because they don’t operate on **input streams**? While such components can break streaming of the final output when using `stream`, `streamEvents` will still yield streaming events from intermediate steps that support streaming! // A function that operates on finalized inputs// rather than on an input_stream// A function that does not operates on input streams and breaks streaming.const extractCountryNames = (inputs: Record<string, any>) => { if (!Array.isArray(inputs.countries)) { return ""; } return JSON.stringify(inputs.countries.map((country) => country.name));};const chain = model.pipe(new JsonOutputParser()).pipe(extractCountryNames);const stream = await chain.stream( `output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`);for await (const chunk of stream) { console.log(chunk);} ["France","Spain","Japan"] As expected, the `stream` API doesn’t work correctly because `extractCountryNames` doesn’t operate on streams. Now, let’s confirm that with `streamEvents` we’re still seeing streaming output from the model and the parser. const eventStream = await chain.streamEvents( `output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of "countries" which contains a list of countries. Each country should have the key "name" and "population"`, { version: "v1" });let eventCount = 0;for await (const event of eventStream) { // Truncate the output if (eventCount > 30) { continue; } const eventType = event.event; if (eventType === "on_llm_stream") { console.log(`Chat model chunk: ${event.data.chunk.message.content}`); } else if (eventType === "on_parser_stream") { console.log(`Parser chunk: ${JSON.stringify(event.data.chunk)}`); } eventCount += 1;} Chat model chunk:Chat model chunk: Here'sChat model chunk: howChat model chunk: youChat model chunk: canChat model chunk: representChat model chunk: theChat model chunk: countriesChat model chunk: FranceChat model chunk: ,Chat model chunk: SpainChat model chunk: ,Chat model chunk: andChat model chunk: JapanChat model chunk: ,Chat model chunk: alongChat model chunk: withChat model chunk: theirChat model chunk: populationsChat model chunk: ,Chat model chunk: inChat model chunk: JSONChat model chunk: formatChat model chunk: :Chat model chunk: ```Chat model chunk: jsonChat model chunk:Chat model chunk: { * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to stream structured output to the client ](/v0.2/docs/how_to/stream_tool_client)[ Next How to create a time-weighted retriever ](/v0.2/docs/how_to/time_weighted_vectorstore) * [LLMs and Chat Models](#llms-and-chat-models) * [Chains](#chains) * [Working with Input Streams](#working-with-input-streams) * [Non-streaming components](#non-streaming-components) * [Using Stream Events](#using-stream-events) * [Event Reference](#event-reference) * [Chat Model](#chat-model) * [Chain](#chain) * [Filtering Events](#filtering-events) * [Streaming events over HTTP](#streaming-events-over-http) * [Non-streaming components](#non-streaming-components-1)
null
https://js.langchain.com/v0.2/docs/how_to/contextual_compression
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to do retrieval with contextual compression On this page How to do retrieval with contextual compression =============================================== Prerequisites This guide assumes familiarity with the following concepts: * [Retrievers](/v0.2/docs/concepts/#retrievers) * [Retrieval-augmented generation (RAG)](/v0.2/docs/tutorials/rag) One challenge with retrieval is that usually you don't know the specific queries your document storage system will face when you ingest data into the system. This means that the information most relevant to a query may be buried in a document with a lot of irrelevant text. Passing that full document through your application can lead to more expensive LLM calls and poorer responses. Contextual compression is meant to fix this. The idea is simple: instead of immediately returning retrieved documents as-is, you can compress them using the context of the given query, so that only the relevant information is returned. “Compressing” here refers to both compressing the contents of an individual document and filtering out documents wholesale. To use the Contextual Compression Retriever, you'll need: * a base retriever * a Document Compressor The Contextual Compression Retriever passes queries to the base retriever, takes the initial documents and passes them through the Document Compressor. The Document Compressor takes a list of documents and shortens it by reducing the contents of documents or dropping documents altogether. Using a vanilla vector store retriever[​](#using-a-vanilla-vector-store-retriever "Direct link to Using a vanilla vector store retriever") ------------------------------------------------------------------------------------------------------------------------------------------ Let's start by initializing a simple vector store retriever and storing the 2023 State of the Union speech (in chunks). Given an example question, our retriever returns one or two relevant docs and a few irrelevant docs, and even the relevant docs have a lot of irrelevant information in them. To extract all the context we can, we use an `LLMChainExtractor`, which will iterate over the initially returned documents and extract from each only the content that is relevant to the query. tip See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages). * npm * Yarn * pnpm npm install @langchain/openai @langchain/community yarn add @langchain/openai @langchain/community pnpm add @langchain/openai @langchain/community import * as fs from "fs";import { OpenAI, OpenAIEmbeddings } from "@langchain/openai";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { HNSWLib } from "@langchain/community/vectorstores/hnswlib";import { ContextualCompressionRetriever } from "langchain/retrievers/contextual_compression";import { LLMChainExtractor } from "langchain/retrievers/document_compressors/chain_extract";const model = new OpenAI({ model: "gpt-3.5-turbo-instruct",});const baseCompressor = LLMChainExtractor.fromLLM(model);const text = fs.readFileSync("state_of_the_union.txt", "utf8");const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000 });const docs = await textSplitter.createDocuments([text]);// Create a vector store from the documents.const vectorStore = await HNSWLib.fromDocuments(docs, new OpenAIEmbeddings());const retriever = new ContextualCompressionRetriever({ baseCompressor, baseRetriever: vectorStore.asRetriever(),});const retrievedDocs = await retriever.invoke( "What did the speaker say about Justice Breyer?");console.log({ retrievedDocs });/* { retrievedDocs: [ Document { pageContent: 'One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata: [Object] }, Document { pageContent: '"Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service."', metadata: [Object] }, Document { pageContent: 'The onslaught of state laws targeting transgender Americans and their families is wrong.', metadata: [Object] } ] }*/ #### API Reference: * [OpenAI](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [HNSWLib](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_hnswlib.HNSWLib.html) from `@langchain/community/vectorstores/hnswlib` * [ContextualCompressionRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_contextual_compression.ContextualCompressionRetriever.html) from `langchain/retrievers/contextual_compression` * [LLMChainExtractor](https://v02.api.js.langchain.com/classes/langchain_retrievers_document_compressors_chain_extract.LLMChainExtractor.html) from `langchain/retrievers/document_compressors/chain_extract` `EmbeddingsFilter`[​](#embeddingsfilter "Direct link to embeddingsfilter") -------------------------------------------------------------------------- Making an extra LLM call over each retrieved document is expensive and slow. The `EmbeddingsFilter` provides a cheaper and faster option by embedding the documents and query and only returning those documents which have sufficiently similar embeddings to the query. This is most useful for non-vector store retrievers where we may not have control over the returned chunk size, or as part of a pipeline, outlined below. Here's an example: import * as fs from "fs";import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { HNSWLib } from "@langchain/community/vectorstores/hnswlib";import { OpenAIEmbeddings } from "@langchain/openai";import { ContextualCompressionRetriever } from "langchain/retrievers/contextual_compression";import { EmbeddingsFilter } from "langchain/retrievers/document_compressors/embeddings_filter";const baseCompressor = new EmbeddingsFilter({ embeddings: new OpenAIEmbeddings(), similarityThreshold: 0.8,});const text = fs.readFileSync("state_of_the_union.txt", "utf8");const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000 });const docs = await textSplitter.createDocuments([text]);// Create a vector store from the documents.const vectorStore = await HNSWLib.fromDocuments(docs, new OpenAIEmbeddings());const retriever = new ContextualCompressionRetriever({ baseCompressor, baseRetriever: vectorStore.asRetriever(),});const retrievedDocs = await retriever.invoke( "What did the speaker say about Justice Breyer?");console.log({ retrievedDocs });/* { retrievedDocs: [ Document { pageContent: 'And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. \n' + '\n' + 'A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n' + '\n' + 'And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \n' + '\n' + 'We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \n' + '\n' + 'We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \n' + '\n' + 'We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster.', metadata: [Object] }, Document { pageContent: 'In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \n' + '\n' + 'We cannot let this happen. \n' + '\n' + 'Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n' + '\n' + 'Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n' + '\n' + 'One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n' + '\n' + 'And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata: [Object] } ] }*/ #### API Reference: * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [HNSWLib](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_hnswlib.HNSWLib.html) from `@langchain/community/vectorstores/hnswlib` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [ContextualCompressionRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_contextual_compression.ContextualCompressionRetriever.html) from `langchain/retrievers/contextual_compression` * [EmbeddingsFilter](https://v02.api.js.langchain.com/classes/langchain_retrievers_document_compressors_embeddings_filter.EmbeddingsFilter.html) from `langchain/retrievers/document_compressors/embeddings_filter` Stringing compressors and document transformers together[​](#stringing-compressors-and-document-transformers-together "Direct link to Stringing compressors and document transformers together") ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Using the `DocumentCompressorPipeline` we can also easily combine multiple compressors in sequence. Along with compressors we can add BaseDocumentTransformers to our pipeline, which don't perform any contextual compression but simply perform some transformation on a set of documents. For example `TextSplitters` can be used as document transformers to split documents into smaller pieces, and the `EmbeddingsFilter` can be used to filter out documents based on similarity of the individual chunks to the input query. Below we create a compressor pipeline by first splitting raw webpage documents retrieved from the [Tavily web search API retriever](/v0.2/docs/integrations/retrievers/tavily) into smaller chunks, then filtering based on relevance to the query. The result is smaller chunks that are semantically similar to the input query. This skips the need to add documents to a vector store to perform similarity search, which can be useful for one-off use cases: import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";import { OpenAIEmbeddings } from "@langchain/openai";import { ContextualCompressionRetriever } from "langchain/retrievers/contextual_compression";import { EmbeddingsFilter } from "langchain/retrievers/document_compressors/embeddings_filter";import { TavilySearchAPIRetriever } from "@langchain/community/retrievers/tavily_search_api";import { DocumentCompressorPipeline } from "langchain/retrievers/document_compressors";const embeddingsFilter = new EmbeddingsFilter({ embeddings: new OpenAIEmbeddings(), similarityThreshold: 0.8, k: 5,});const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 200, chunkOverlap: 0,});const compressorPipeline = new DocumentCompressorPipeline({ transformers: [textSplitter, embeddingsFilter],});const baseRetriever = new TavilySearchAPIRetriever({ includeRawContent: true,});const retriever = new ContextualCompressionRetriever({ baseCompressor: compressorPipeline, baseRetriever,});const retrievedDocs = await retriever.invoke( "What did the speaker say about Justice Breyer in the 2022 State of the Union?");console.log({ retrievedDocs });/* { retrievedDocs: [ Document { pageContent: 'Justice Stephen Breyer talks to President Joe Biden ahead of the State of the Union address on Tuesday. (jabin botsford/Agence France-Presse/Getty Images)', metadata: [Object] }, Document { pageContent: 'President Biden recognized outgoing US Supreme Court Justice Stephen Breyer during his State of the Union on Tuesday.', metadata: [Object] }, Document { pageContent: 'What we covered here\n' + 'Biden recognized outgoing Supreme Court Justice Breyer during his speech', metadata: [Object] }, Document { pageContent: 'States Supreme Court. Justice Breyer, thank you for your service,” the president said.', metadata: [Object] }, Document { pageContent: 'Court," Biden said. "Justice Breyer, thank you for your service."', metadata: [Object] } ] }*/ #### API Reference: * [RecursiveCharacterTextSplitter](https://v02.api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `@langchain/textsplitters` * [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai` * [ContextualCompressionRetriever](https://v02.api.js.langchain.com/classes/langchain_retrievers_contextual_compression.ContextualCompressionRetriever.html) from `langchain/retrievers/contextual_compression` * [EmbeddingsFilter](https://v02.api.js.langchain.com/classes/langchain_retrievers_document_compressors_embeddings_filter.EmbeddingsFilter.html) from `langchain/retrievers/document_compressors/embeddings_filter` * [TavilySearchAPIRetriever](https://v02.api.js.langchain.com/classes/langchain_community_retrievers_tavily_search_api.TavilySearchAPIRetriever.html) from `@langchain/community/retrievers/tavily_search_api` * [DocumentCompressorPipeline](https://v02.api.js.langchain.com/classes/langchain_retrievers_document_compressors.DocumentCompressorPipeline.html) from `langchain/retrievers/document_compressors` Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now learned a few ways to use contextual compression to remove bad data from your results. See the individual sections for deeper dives on specific retrievers, the [broader tutorial on RAG](/v0.2/docs/tutorials/rag), or this section to learn how to [create your own custom retriever over any data source](/v0.2/docs/how_to/custom_retriever/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to split code ](/v0.2/docs/how_to/code_splitter)[ Next How to create custom callback handlers ](/v0.2/docs/how_to/custom_callbacks) * [Using a vanilla vector store retriever](#using-a-vanilla-vector-store-retriever) * [`EmbeddingsFilter`](#embeddingsfilter) * [Stringing compressors and document transformers together](#stringing-compressors-and-document-transformers-together) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/tool_calls_multimodal
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to call tools with multimodal data On this page How to call tools with multimodal data ====================================== Prerequisites This guide assumes familiarity with the following concepts: * [Chat models](/v0.2/docs/concepts/#chat-models) * [LangChain Tools](/v0.2/docs/concepts/#tools) Here we demonstrate how to call tools with multimodal data, such as images. Some multimodal models, such as those that can reason over images or audio, support [tool calling](/v0.2/docs/concepts/#tool-calling) features as well. To call tools using such models, simply bind tools to them in the [usual way](/v0.2/docs/how_to/tool_calling), and invoke the model using content blocks of the desired type (e.g., containing image data). Below, we demonstrate examples using [OpenAI](/v0.2/docs/integrations/platforms/openai) and [Anthropic](/v0.2/docs/integrations/platforms/anthropic). We will use the same image and tool in all cases. Let’s first select an image, and build a placeholder tool that expects as input the string “sunny”, “cloudy”, or “rainy”. We will ask the models to describe the weather in the image. The `tool` function is available in `@langchain/core` version 0.2.7 and above. If you are on an older version of core, you should use instantiate and use [`DynamicStructuredTool`](https://api.js.langchain.com/classes/langchain_core_tools.DynamicStructuredTool.html) instead. import { tool } from "@langchain/core/tools";import { z } from "zod";const imageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg";const weatherTool = tool( async ({ weather }) => { console.log(weather); return weather; }, { name: "multiply", description: "Describe the weather", schema: z.object({ weather: z.enum(["sunny", "cloudy", "rainy"]), }), }); OpenAI[​](#openai "Direct link to OpenAI") ------------------------------------------ For OpenAI, we can feed the image URL directly in a content block of type “image\_url”: import { HumanMessage } from "@langchain/core/messages";import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI({ model: "gpt-4o",}).bindTools([weatherTool]);const message = new HumanMessage({ content: [ { type: "text", text: "describe the weather in this image", }, { type: "image_url", image_url: { url: imageUrl, }, }, ],});const response = await model.invoke([message]);console.log(response.tool_calls); [ { name: "multiply", args: { weather: "sunny" }, id: "call_ZaBYUggmrTSuDjcuZpMVKpMR" }] Note that we recover tool calls with parsed arguments in LangChain’s [standard format](/v0.2/docs/how_to/tool_calling) in the model response. Anthropic[​](#anthropic "Direct link to Anthropic") --------------------------------------------------- For Anthropic, we can format a base64-encoded image into a content block of type “image”, as below: import * as fs from "node:fs/promises";import { ChatAnthropic } from "@langchain/anthropic";import { HumanMessage } from "@langchain/core/messages";const imageData = await fs.readFile("../../data/sunny_day.jpeg");const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229",}).bindTools([weatherTool]);const message = new HumanMessage({ content: [ { type: "text", text: "describe the weather in this image", }, { type: "image_url", image_url: { url: `data:image/jpeg;base64,${imageData.toString("base64")}`, }, }, ],});const response = await model.invoke([message]);console.log(response.tool_calls); [ { name: "multiply", args: { weather: "sunny" }, id: "toolu_01HLY1KmXZkKMn7Ar4ZtFuAM" }] Google Generative AI[​](#google-generative-ai "Direct link to Google Generative AI") ------------------------------------------------------------------------------------ For Google GenAI, we can format a base64-encoded image into a content block of type “image”, as below: import { ChatGoogleGenerativeAI } from "@langchain/google-genai";import axios from "axios";import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";import { HumanMessage } from "@langchain/core/messages";const axiosRes = await axios.get(imageUrl, { responseType: "arraybuffer" });const base64 = btoa( new Uint8Array(axiosRes.data).reduce( (data, byte) => data + String.fromCharCode(byte), "" ));const model = new ChatGoogleGenerativeAI({ model: "gemini-1.5-pro-latest",}).bindTools([weatherTool]);const prompt = ChatPromptTemplate.fromMessages([ ["system", "describe the weather in this image"], new MessagesPlaceholder("message"),]);const response = await prompt.pipe(model).invoke({ message: new HumanMessage({ content: [ { type: "media", mimeType: "image/jpeg", data: base64, }, ], }),});console.log(response.tool_calls); [ { name: 'multiply', args: { weather: 'sunny' } } ] ### Audio input[​](#audio-input "Direct link to Audio input") Google’s Gemini also supports audio inputs. In this next example we’ll see how we can pass an audio file to the model, and get back a summary in structured format. import { SystemMessage } from "@langchain/core/messages";import { StructuredTool } from "@langchain/core/tools";class SummaryTool extends StructuredTool { schema = z.object({ summary: z.string().describe("The summary of the content to log"), }); description = "Log the summary of the content"; name = "summary_tool"; async _call(input: z.infer<typeof this.schema>) { return input.summary; }}const summaryTool = new SummaryTool();const audioUrl = "https://www.pacdv.com/sounds/people_sound_effects/applause-1.wav";const axiosRes = await axios.get(audioUrl, { responseType: "arraybuffer" });const base64 = btoa( new Uint8Array(axiosRes.data).reduce( (data, byte) => data + String.fromCharCode(byte), "" ));const model = new ChatGoogleGenerativeAI({ model: "gemini-1.5-pro-latest",}).bindTools([summaryTool]);const response = await model.invoke([ new SystemMessage( "Summarize this content. always use the summary_tool in your response" ), new HumanMessage({ content: [ { type: "media", mimeType: "audio/wav", data: base64, }, ], }),]);console.log(response.tool_calls); [ { name: 'summary_tool', args: { summary: 'The video shows a person clapping their hands.' } }] * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to use a chat model to call tools ](/v0.2/docs/how_to/tool_calling)[ Next How to pass run time values to a tool ](/v0.2/docs/how_to/tool_runtime) * [OpenAI](#openai) * [Anthropic](#anthropic) * [Google Generative AI](#google-generative-ai) * [Audio input](#audio-input)
null
https://js.langchain.com/v0.2/docs/how_to/custom_callbacks
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to create custom callback handlers On this page How to create custom callback handlers ====================================== Prerequisites This guide assumes familiarity with the following concepts: * [Callbacks](/v0.2/docs/concepts/#callbacks) LangChain has some built-in callback handlers, but you will often want to create your own handlers with custom logic. To create a custom callback handler, we need to determine the [event(s)](https://api.js.langchain.com/interfaces/langchain_core_callbacks_base.CallbackHandlerMethods.html) we want our callback handler to handle as well as what we want our callback handler to do when the event is triggered. Then all we need to do is attach the callback handler to the object, for example via [the constructor](/v0.2/docs/how_to/callbacks_constructor) or [at runtime](/v0.2/docs/how_to/callbacks_runtime). An easy way to construct a custom callback handler is to initialize it as an object whose keys are functions with names matching the events we want to handle. Here’s an example that only handles the start of a chat model and streamed tokens from the model run: import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatAnthropic } from "@langchain/anthropic";const prompt = ChatPromptTemplate.fromTemplate(`What is 1 + {number}?`);const model = new ChatAnthropic({ model: "claude-3-sonnet-20240229",});const chain = prompt.pipe(model);const customHandler = { handleChatModelStart: async (llm, inputMessages, runId) => { console.log("Chat model start:", llm, inputMessages, runId); }, handleLLMNewToken: async (token) => { console.log("Chat model new token", token); },};const stream = await chain.stream( { number: "2" }, { callbacks: [customHandler] });for await (const _ of stream) { // Just consume the stream so the callbacks run} Chat model start: { lc: 1, type: "constructor", id: [ "langchain", "chat_models", "anthropic", "ChatAnthropic" ], kwargs: { callbacks: undefined, model: "claude-3-sonnet-20240229", verbose: undefined, anthropic_api_key: { lc: 1, type: "secret", id: [ "ANTHROPIC_API_KEY" ] }, api_key: { lc: 1, type: "secret", id: [ "ANTHROPIC_API_KEY" ] } }} [ [ HumanMessage { lc_serializable: true, lc_kwargs: { content: "What is 1 + 2?", additional_kwargs: {}, response_metadata: {} }, lc_namespace: [ "langchain_core", "messages" ], content: "What is 1 + 2?", name: undefined, additional_kwargs: {}, response_metadata: {} } ]] b6e3b7ad-c602-4cef-9652-d51781a657b7Chat model new token TheChat model new token sumChat model new token ofChat model new tokenChat model new token 1Chat model new tokenChat model new token anChat model new token dChat model new token 2Chat model new tokenChat model new token isChat model new tokenChat model new token 3Chat model new token . You can see [this reference page](https://api.js.langchain.com/interfaces/langchain_core_callbacks_base.CallbackHandlerMethods.html) for a list of events you can handle. Note that the `handleChain*` events run for most LCEL runnables. Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You’ve now learned how to create your own custom callback handlers. Next, check out the other how-to guides in this section, such as [how to background callbacks](/v0.2/docs/how_to/callbacks_backgrounding). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to do retrieval with contextual compression ](/v0.2/docs/how_to/contextual_compression)[ Next How to write a custom retriever class ](/v0.2/docs/how_to/custom_retriever) * [Next steps](#next-steps)
null
https://js.langchain.com/v0.2/docs/how_to/tool_runtime
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to pass run time values to a tool How to pass run time values to a tool ===================================== Prerequisites This guide assumes familiarity with the following concepts: - [Chat models](/v0.2/docs/concepts/#chat-models) - [LangChain Tools](/v0.2/docs/concepts/#tools) - [How to create tools](/v0.2/docs/how_to/custom_tools) - [How to use a model to call tools](/v0.2/docs/how_to/tool_calling/) ::: This how-to guide uses models with native tool calling capability. You can find a [list of all models that support tool calling](/v0.2/docs/integrations/chat/). ::: You may need to bind values to a tool that are only known at runtime. For example, the tool logic may require using the ID of the user who made the request. Most of the time, such values should not be controlled by the LLM. In fact, allowing the LLM to control the user ID may lead to a security risk. Instead, the LLM should only control the parameters of the tool that are meant to be controlled by the LLM, while other parameters (such as user ID) should be fixed by the application logic. This how-to guide shows a simple design pattern that creates the tool dynamically at run time and binds to them appropriate values. We can bind them to chat models as follows: ### Pick your chat model: * OpenAI * Anthropic * FireworksAI * MistralAI * Groq * VertexAI #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai #### Add environment variables OPENAI_API_KEY=your-api-key #### Instantiate the model import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/anthropic yarn add @langchain/anthropic pnpm add @langchain/anthropic #### Add environment variables ANTHROPIC_API_KEY=your-api-key #### Instantiate the model import { ChatAnthropic } from "@langchain/anthropic";const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community #### Add environment variables FIREWORKS_API_KEY=your-api-key #### Instantiate the model import { ChatFireworks } from "@langchain/community/chat_models/fireworks";const llm = new ChatFireworks({ model: "accounts/fireworks/models/firefunction-v1", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai #### Add environment variables MISTRAL_API_KEY=your-api-key #### Instantiate the model import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({ model: "mistral-large-latest", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/groq yarn add @langchain/groq pnpm add @langchain/groq #### Add environment variables GROQ_API_KEY=your-api-key #### Instantiate the model import { ChatGroq } from "@langchain/groq";const llm = new ChatGroq({ model: "mixtral-8x7b-32768", temperature: 0}); #### Install dependencies tip See [this section for general instructions on installing integration packages](/docs/get_started/installation#installing-integration-packages). * npm * yarn * pnpm npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai #### Add environment variables GOOGLE_APPLICATION_CREDENTIALS=credentials.json #### Instantiate the model import { ChatVertexAI } from "@langchain/google-vertexai";const llm = new ChatVertexAI({ model: "gemini-1.5-pro", temperature: 0}); Passing request time information ================================ The idea is to create the tool dynamically at request time, and bind to it the appropriate information. For example, this information may be the user ID as resolved from the request itself. import { z } from "zod";import { StructuredTool } from "@langchain/core/tools";const userToPets: Record<string, string[]> = {};function generateToolsForUser(userId: string): StructuredTool[] { class UpdateFavoritePets extends StructuredTool { name = "update_favorite_pets"; description = "Add the list of favorite pets."; schema = z.object({ pets: z.array(z.string()), }); async _call(input: { pets: string[] }): Promise<string> { userToPets[userId] = input.pets; return "update_favorite_pets called."; } } class DeleteFavoritePets extends StructuredTool { name = "delete_favorite_pets"; description = "Delete the list of favorite pets."; schema = z.object({ no_op: z.boolean().optional().describe("No operation."), }); async _call(input: never): Promise<string> { if (userId in userToPets) { delete userToPets[userId]; } return "delete_favorite_pets called."; } } class ListFavoritePets extends StructuredTool { name = "list_favorite_pets"; description = "List favorite pets if any."; schema = z.object({ no_op: z.boolean().optional().describe("No operation."), }); async _call(input: never): Promise<string> { return JSON.stringify(userToPets[userId]) || JSON.stringify([]); } } return [ new UpdateFavoritePets(), new DeleteFavoritePets(), new ListFavoritePets(), ];} Verify that the tools work correctly const [updatePets, deletePets, listPets] = generateToolsForUser("brace");await updatePets.invoke({ pets: ["cat", "dog"] });console.log(userToPets);console.log(await listPets.invoke({})); { brace: [ 'cat', 'dog' ] }["cat","dog"] import { BaseChatModel } from "@langchain/core/language_models/chat_models";async function handleRunTimeRequest( userId: string, query: string, llm: BaseChatModel): Promise<any> { if (!llm.bindTools) { throw new Error("Language model does not support tools."); } const tools = generateToolsForUser(userId); const llmWithTools = llm.bindTools(tools); return llmWithTools.invoke(query);} This code will allow the LLM to invoke the tools, but the LLM is **unaware** of the fact that a **user ID** even exists! const aiMessage = await handleRunTimeRequest( "brace", "my favorite animals are cats and parrots.", llm);console.log(aiMessage.tool_calls[0]); { name: 'update_favorite_pets', args: { pets: [ 'cats', 'parrots' ] }, id: 'call_to1cbIVqMNuahHCdFO9oQzpN'} Click [here](https://smith.langchain.com/public/3d766ecc-8f28-400b-8636-632e6f1598c7/r) to see the LangSmith trace for the above run. Chat models only output requests to invoke tools, they don’t actually invoke the underlying tools. To see how to invoke the tools, please refer to [how to use a model to call tools](/v0.2/docs/how_to/tool_calling/). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to call tools with multimodal data ](/v0.2/docs/how_to/tool_calls_multimodal)[ Next How to use LangChain tools ](/v0.2/docs/how_to/tools_builtin)
null
https://js.langchain.com/v0.2/docs/how_to/tools_builtin
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to use LangChain tools On this page How to use LangChain tools ========================== Tools are interfaces that an agent, chain, or LLM can use to interact with the world. They combine a few things: 1. The name of the tool 2. A description of what the tool is 3. JSON schema of what the inputs to the tool are 4. The function to call 5. Whether the result of a tool should be returned directly to the user It is useful to have all this information because this information can be used to build action-taking systems! The name, description, and schema can be used to prompt the LLM so it knows how to specify what action to take, and then the function to call is equivalent to taking that action. The simpler the input to a tool is, the easier it is for an LLM to be able to use it. Many agents will only work with tools that have a single string input. For a list of agent types and which ones work with more complicated inputs, please see [this documentation](https://js.langchain.com/v0.1/docs/modules/agents/agent_types/) Importantly, the name, description, and schema (if used) are all used in the prompt. Therefore, it is vitally important that they are clear and describe exactly how the tool should be used. Default Tools[​](#default-tools "Direct link to Default Tools") --------------------------------------------------------------- Let’s take a look at how to work with tools. To do this, we’ll work with a built in tool. import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";const tool = new WikipediaQueryRun({ topKResults: 1, maxDocContentLength: 100,}); This is the default name: tool.name; "wikipedia-api" This is the default description: tool.description; "A tool for interacting with and fetching data from the Wikipedia API." This is the default schema of the inputs. This is a [Zod](https://zod.dev) schema on the tool class. We convert it to JSON schema for display purposes: import { zodToJsonSchema } from "zod-to-json-schema";zodToJsonSchema(tool.schema); { type: "object", properties: { input: { type: "string" } }, additionalProperties: false, "$schema": "http://json-schema.org/draft-07/schema#"} We can see if the tool should return directly to the user tool.returnDirect; false We can invoke this tool with an object input: await tool.invoke({ input: "langchain" }); "Page: LangChain\n" + "Summary: LangChain is a framework designed to simplify the creation of applications " We can also invoke this tool with a single string input. We can do this because this tool expects only a single input. If it required multiple inputs, we would not be able to do that. await tool.invoke("langchain"); "Page: LangChain\n" + "Summary: LangChain is a framework designed to simplify the creation of applications " How to use built-in toolkits[​](#how-to-use-built-in-toolkits "Direct link to How to use built-in toolkits") ------------------------------------------------------------------------------------------------------------ Toolkits are collections of tools that are designed to be used together for specific tasks. They have convenient loading methods. For a complete list of available ready-made toolkits, visit [Integrations](/v0.2/docs/integrations/toolkits/). All Toolkits expose a `getTools()` method which returns a list of tools. You’re usually meant to use them this way: // Initialize a toolkitconst toolkit = new ExampleTookit(...);// Get list of toolsconst tools = toolkit.getTools(); More Topics[​](#more-topics "Direct link to More Topics") --------------------------------------------------------- This was a quick introduction to tools in LangChain, but there is a lot more to learn **[Built-In Tools](/v0.2/docs/integrations/tools/)**: For a list of all built-in tools, see [this page](/v0.2/docs/integrations/tools/) **[Custom Tools](/v0.2/docs/how_to/custom_tools)**: Although built-in tools are useful, it’s highly likely that you’ll have to define your own tools. See [this guide](/v0.2/docs/how_to/custom_tools) for instructions on how to do so. * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to pass run time values to a tool ](/v0.2/docs/how_to/tool_runtime)[ Next How to trim messages ](/v0.2/docs/how_to/trim_messages) * [Default Tools](#default-tools) * [How to use built-in toolkits](#how-to-use-built-in-toolkits) * [More Topics](#more-topics)
null
https://js.langchain.com/v0.2/docs/how_to/custom_retriever
* [](/v0.2/) * [How-to guides](/v0.2/docs/how_to/) * How to write a custom retriever class On this page How to write a custom retriever class ===================================== Prerequisites This guide assumes familiarity with the following concepts: * [Retrievers](/v0.2/docs/concepts/#retrievers) To create your own retriever, you need to extend the [`BaseRetriever`](https://v02.api.js.langchain.com/classes/langchain_core_retrievers.BaseRetriever.html) class and implement a `_getRelevantDocuments` method that takes a `string` as its first parameter (and an optional `runManager` for tracing). This method should return an array of `Document`s fetched from some source. This process can involve calls to a database, to the web using `fetch`, or any other source. Note the underscore before `_getRelevantDocuments()`. The base class wraps the non-prefixed version in order to automatically handle tracing of the original call. Here's an example of a custom retriever that returns static documents: import { BaseRetriever, type BaseRetrieverInput,} from "@langchain/core/retrievers";import type { CallbackManagerForRetrieverRun } from "@langchain/core/callbacks/manager";import { Document } from "@langchain/core/documents";export interface CustomRetrieverInput extends BaseRetrieverInput {}export class CustomRetriever extends BaseRetriever { lc_namespace = ["langchain", "retrievers"]; constructor(fields?: CustomRetrieverInput) { super(fields); } async _getRelevantDocuments( query: string, runManager?: CallbackManagerForRetrieverRun ): Promise<Document[]> { // Pass `runManager?.getChild()` when invoking internal runnables to enable tracing // const additionalDocs = await someOtherRunnable.invoke(params, runManager?.getChild()); return [ // ...additionalDocs, new Document({ pageContent: `Some document pertaining to ${query}`, metadata: {}, }), new Document({ pageContent: `Some other document pertaining to ${query}`, metadata: {}, }), ]; }} Then, you can call `.invoke()` as follows: const retriever = new CustomRetriever({});await retriever.invoke("LangChain docs"); [ Document { pageContent: 'Some document pertaining to LangChain docs', metadata: {} }, Document { pageContent: 'Some other document pertaining to LangChain docs', metadata: {} }] Next steps[​](#next-steps "Direct link to Next steps") ------------------------------------------------------ You've now seen an example of implementing your own custom retriever. Next, check out the individual sections for deeper dives on specific retrievers, or the [broader tutorial on RAG](/v0.2/docs/tutorials/rag). * * * #### Was this page helpful? #### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E). [ Previous How to create custom callback handlers ](/v0.2/docs/how_to/custom_callbacks)[ Next How to create custom Tools ](/v0.2/docs/how_to/custom_tools) * [Next steps](#next-steps)
null