diff --git a/langchain/src/agents/toolkits/json/json.ts b/langchain/src/agents/toolkits/json/json.ts index de385273f2b7..bbf9e8c742f3 100644 --- a/langchain/src/agents/toolkits/json/json.ts +++ b/langchain/src/agents/toolkits/json/json.ts @@ -14,6 +14,14 @@ import { AgentExecutor } from "../../executor.js"; /** * Represents a toolkit for working with JSON data. It initializes the * JSON tools based on the provided JSON specification. + * @example + * ```typescript + * const toolkit = new JsonToolkit(new JsonSpec()); + * const executor = createJsonAgent(model, toolkit); + * const result = await executor.invoke({ + * input: 'What are the required parameters in the request body to the /completions endpoint?' + * }); + * ``` */ export class JsonToolkit extends Toolkit { tools: Tool[]; diff --git a/langchain/src/agents/toolkits/openapi/openapi.ts b/langchain/src/agents/toolkits/openapi/openapi.ts index 11bef2ffd334..e21b17f72402 100644 --- a/langchain/src/agents/toolkits/openapi/openapi.ts +++ b/langchain/src/agents/toolkits/openapi/openapi.ts @@ -36,6 +36,24 @@ export class RequestsToolkit extends Toolkit { * exploring JSON data. It creates a JSON agent using the `JsonToolkit` * and the provided language model, and adds the JSON explorer tool to the * toolkit. + * @example + * ```typescript + * const toolkit = new OpenApiToolkit( + * new JsonSpec({ + * }), + * new ChatOpenAI({ temperature: 0 }), + * { + * "Content-Type": "application/json", + * Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, + * }, + * ); + * + * const result = await toolkit.invoke({ + * input: + * "Make a POST request to openai /completions. The prompt should be 'tell me a joke.'", + * }); + * console.log(`Got output ${result.output}`); + * ``` */ export class OpenApiToolkit extends RequestsToolkit { constructor(jsonSpec: JsonSpec, llm: BaseLanguageModel, headers?: Headers) { diff --git a/langchain/src/agents/toolkits/sql/sql.ts b/langchain/src/agents/toolkits/sql/sql.ts index 2bd6b947cf1f..d11711dde28d 100644 --- a/langchain/src/agents/toolkits/sql/sql.ts +++ b/langchain/src/agents/toolkits/sql/sql.ts @@ -26,6 +26,14 @@ export interface SqlCreatePromptArgs extends ZeroShotCreatePromptArgs { /** * Class that represents a toolkit for working with SQL databases. It * initializes SQL tools based on the provided SQL database. + * @example + * ```typescript + * const model = new ChatOpenAI({}); + * const toolkit = new SqlToolkit(sqlDb, model); + * const executor = createSqlAgent(model, toolkit); + * const result = await executor.invoke({ input: 'List the total sales per country. Which country's customers spent the most?' }); + * console.log(`Got output ${result.output}`); + * ``` */ export class SqlToolkit extends Toolkit { tools: Tool[]; diff --git a/langchain/src/agents/toolkits/vectorstore/vectorstore.ts b/langchain/src/agents/toolkits/vectorstore/vectorstore.ts index c473c6cbfd4c..5b7eaf3042f0 100644 --- a/langchain/src/agents/toolkits/vectorstore/vectorstore.ts +++ b/langchain/src/agents/toolkits/vectorstore/vectorstore.ts @@ -23,6 +23,22 @@ export interface VectorStoreInfo { * Class representing a toolkit for working with a single vector store. It * initializes the vector store QA tool based on the provided vector store * information and language model. + * @example + * ```typescript + * const toolkit = new VectorStoreToolkit( + * { + * name: "state_of_union_address", + * description: "the most recent state of the Union address", + * vectorStore: new HNSWLib(), + * }, + * new ChatOpenAI({ temperature: 0 }), + * ); + * const result = await toolkit.invoke({ + * input: + * "What did biden say about Ketanji Brown Jackson in the state of the union address?", + * }); + * console.log(`Got output ${result.output}`); + * ``` */ export class VectorStoreToolkit extends Toolkit { tools: Tool[]; diff --git a/langchain/src/agents/toolkits/zapier/zapier.ts b/langchain/src/agents/toolkits/zapier/zapier.ts index 3205f2c3da5d..c192149b4abe 100644 --- a/langchain/src/agents/toolkits/zapier/zapier.ts +++ b/langchain/src/agents/toolkits/zapier/zapier.ts @@ -5,6 +5,16 @@ import { ZapierNLARunAction, ZapierNLAWrapper } from "../../../tools/zapier.js"; /** * Represents a toolkit for working with Zapier actions. It extends the * Toolkit class and provides functionality for managing Zapier tools. + * @example + * ```typescript + * const toolkit = await ZapierToolKit.fromZapierNLAWrapper( + * new ZapierNLAWrapper(), + * ); + * const result = await toolkit.invoke({ + * input: + * "Summarize the last email I received regarding Silicon Valley Bank. Send the summary to the #test-zapier Slack channel.", + * }); + * ``` */ export class ZapierToolKit extends Toolkit { tools: Tool[] = []; diff --git a/langchain/src/retrievers/self_query/pinecone.ts b/langchain/src/retrievers/self_query/pinecone.ts index 0a59d98f96cd..b948de281142 100644 --- a/langchain/src/retrievers/self_query/pinecone.ts +++ b/langchain/src/retrievers/self_query/pinecone.ts @@ -8,6 +8,20 @@ import { BasicTranslator } from "./base.js"; * LangChain. The class is initialized with a set of allowed operators and * comparators, which are used in the translation process to construct * queries and compare results. + * @example + * ```typescript + * const selfQueryRetriever = await SelfQueryRetriever.fromLLM({ + * llm: new ChatOpenAI(), + * vectorStore: new PineconeStore(), + * documentContents: "Brief summary of a movie", + * attributeInfo: [], + * structuredQueryTranslator: new PineconeTranslator(), + * }); + * + * const queryResult = await selfQueryRetriever.getRelevantDocuments( + * "Which movies are directed by Greta Gerwig?", + * ); + * ``` */ export class PineconeTranslator< T extends PineconeStore diff --git a/langchain/src/retrievers/self_query/supabase.ts b/langchain/src/retrievers/self_query/supabase.ts index 25a59ec1b9fe..b9ebc629f3bb 100644 --- a/langchain/src/retrievers/self_query/supabase.ts +++ b/langchain/src/retrievers/self_query/supabase.ts @@ -36,6 +36,20 @@ type ValueType = { * A specialized translator designed to work with Supabase, extending the * BaseTranslator class. It translates structured queries into a format * that can be understood by the Supabase database. + * @example + * ```typescript + * const selfQueryRetriever = new SelfQueryRetriever({ + * llm: new ChatOpenAI(), + * vectorStore: new SupabaseVectorStore(), + * documentContents: "Brief summary of a movie", + * attributeInfo: [], + * structuredQueryTranslator: new SupabaseTranslator(), + * }); + * + * const queryResult = await selfQueryRetriever.getRelevantDocuments( + * "Which movies are directed by Greta Gerwig?", + * ); + * ``` */ export class SupabaseTranslator< T extends SupabaseVectorStore diff --git a/langchain/src/retrievers/self_query/weaviate.ts b/langchain/src/retrievers/self_query/weaviate.ts index 89dab2fe6252..924a0c07412c 100644 --- a/langchain/src/retrievers/self_query/weaviate.ts +++ b/langchain/src/retrievers/self_query/weaviate.ts @@ -54,6 +54,20 @@ export type WeaviateStructuredQueryResult = { * A class that translates or converts data into a format that can be used * with Weaviate, a vector search engine. It extends the `BaseTranslator` * class and provides specific implementation for Weaviate. + * @example + * ```typescript + * const selfQueryRetriever = new SelfQueryRetriever({ + * llm: new ChatOpenAI(), + * vectorStore: new WeaviateStore(), + * documentContents: "Brief summary of a movie", + * attributeInfo: [], + * structuredQueryTranslator: new WeaviateTranslator(), + * }); + * + * const relevantDocuments = await selfQueryRetriever.getRelevantDocuments( + * "Which movies are rated higher than 8.5?", + * ); + * ``` */ export class WeaviateTranslator< T extends WeaviateStore diff --git a/langchain/src/schema/runnable/base.ts b/langchain/src/schema/runnable/base.ts index 0eb242bacb9b..83b8d3e51dc7 100644 --- a/langchain/src/schema/runnable/base.ts +++ b/langchain/src/schema/runnable/base.ts @@ -966,6 +966,14 @@ export class RunnableRetry< /** * A sequence of runnables, where the output of each is the input of the next. + * @example + * ```typescript + * const promptTemplate = PromptTemplate.fromTemplate( + * "Tell me a joke about {topic}", + * ); + * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({})]); + * const result = await chain.invoke({ topic: "bears" }); + * ``` */ export class RunnableSequence< // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -1260,6 +1268,18 @@ export class RunnableSequence< /** * A runnable that runs a mapping of runnables in parallel, * and returns a mapping of their outputs. + * @example + * ```typescript + * const mapChain = RunnableMap.from({ + * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( + * new ChatAnthropic({}), + * ), + * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( + * new ChatAnthropic({}), + * ), + * }); + * const result = await mapChain.invoke({ topic: "bear" }); + * ``` */ export class RunnableMap extends Runnable< RunInput, diff --git a/langchain/src/schema/runnable/branch.ts b/langchain/src/schema/runnable/branch.ts index f574c9d9e805..97b01c6d06d9 100644 --- a/langchain/src/schema/runnable/branch.ts +++ b/langchain/src/schema/runnable/branch.ts @@ -24,6 +24,34 @@ export type BranchLike = [ * it evaluates the condition of each branch in order and executes the * corresponding branch if the condition is true. If none of the conditions * are true, it executes the default branch. + * @example + * ```typescript + * 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 result = await fullChain.invoke({ + * question: "how do I use LangChain?", + * }); + * ``` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export class RunnableBranch extends Runnable< diff --git a/langchain/src/stores/message/cassandra.ts b/langchain/src/stores/message/cassandra.ts index e819973550ec..5e63b2b1f11f 100644 --- a/langchain/src/stores/message/cassandra.ts +++ b/langchain/src/stores/message/cassandra.ts @@ -19,6 +19,31 @@ export interface CassandraChatMessageHistoryOptions extends DseClientOptions { * Class for storing chat message history within Cassandra. It extends the * BaseListChatMessageHistory class and provides methods to get, add, and * clear messages. + * @example + * ```typescript + * const chatHistory = new CassandraChatMessageHistory({ + * cloud: { + * secureConnectBundle: "", + * }, + * credentials: { + * username: "token", + * password: "", + * }, + * keyspace: "langchain", + * table: "message_history", + * sessionId: "", + * }); + * + * const chain = new ConversationChain({ + * llm: new ChatOpenAI(), + * memory: chatHistory, + * }); + * + * const response = await chain.invoke({ + * input: "What did I just say my name was?", + * }); + * console.log({ response }); + * ``` */ export class CassandraChatMessageHistory extends BaseListChatMessageHistory { lc_namespace = ["langchain", "stores", "message", "cassandra"]; diff --git a/langchain/src/stores/message/cloudflare_d1.ts b/langchain/src/stores/message/cloudflare_d1.ts index 97a9dfe03561..a88cb595c2ca 100644 --- a/langchain/src/stores/message/cloudflare_d1.ts +++ b/langchain/src/stores/message/cloudflare_d1.ts @@ -39,6 +39,24 @@ interface selectStoredMessagesDTO { /** * Class for storing and retrieving chat message history from a * Cloudflare D1 database. Extends the BaseListChatMessageHistory class. + * @example + * ```typescript + * const memory = new BufferMemory({ + * returnMessages: true, + * chatHistory: new CloudflareD1MessageHistory({ + * tableName: "stored_message", + * sessionId: "example", + * database: env.DB, + * }), + * }); + * + * const chainInput = { input }; + * + * const res = await memory.chatHistory.invoke(chainInput); + * await memory.saveContext(chainInput, { + * output: res, + * }); + * ``` */ export class CloudflareD1MessageHistory extends BaseListChatMessageHistory { lc_namespace = ["langchain", "stores", "message", "cloudflare_d1"]; diff --git a/langchain/src/stores/message/firestore.ts b/langchain/src/stores/message/firestore.ts index 0efbf1cacd47..8d342bc5b981 100644 --- a/langchain/src/stores/message/firestore.ts +++ b/langchain/src/stores/message/firestore.ts @@ -33,6 +33,25 @@ export interface FirestoreDBChatMessageHistory { /** * Class for managing chat message history using Google's Firestore as a * storage backend. Extends the BaseListChatMessageHistory class. + * @example + * ```typescript + * const chatHistory = new FirestoreChatMessageHistory({ + * collectionName: "langchain", + * sessionId: "lc-example", + * userId: "a@example.com", + * config: { projectId: "your-project-id" }, + * }); + * + * const chain = new ConversationChain({ + * llm: new ChatOpenAI(), + * memory: new BufferMemory({ chatHistory }), + * }); + * + * const response = await chain.invoke({ + * input: "What did I just say my name was?", + * }); + * console.log({ response }); + * ``` */ export class FirestoreChatMessageHistory extends BaseListChatMessageHistory { lc_namespace = ["langchain", "stores", "message", "firestore"]; diff --git a/langchain/src/stores/message/ioredis.ts b/langchain/src/stores/message/ioredis.ts index 7e77d20775e4..c705b9228769 100644 --- a/langchain/src/stores/message/ioredis.ts +++ b/langchain/src/stores/message/ioredis.ts @@ -21,6 +21,24 @@ export type RedisChatMessageHistoryInput = { /** * Class used to store chat message history in Redis. It provides methods * to add, retrieve, and clear messages from the chat history. + * @example + * ```typescript + * const chatHistory = new RedisChatMessageHistory({ + * sessionId: new Date().toISOString(), + * sessionTTL: 300, + * url: "redis: + * }); + * + * const chain = new ConversationChain({ + * llm: new ChatOpenAI({ temperature: 0 }), + * memory: { chatHistory }, + * }); + * + * const response = await chain.invoke({ + * input: "What did I just say my name was?", + * }); + * console.log({ response }); + * ``` */ export class RedisChatMessageHistory extends BaseListChatMessageHistory { lc_namespace = ["langchain", "stores", "message", "ioredis"]; diff --git a/langchain/src/stores/message/momento.ts b/langchain/src/stores/message/momento.ts index d9df7c2af387..c902980f694b 100644 --- a/langchain/src/stores/message/momento.ts +++ b/langchain/src/stores/message/momento.ts @@ -51,6 +51,24 @@ export interface MomentoChatMessageHistoryProps { * A class that stores chat message history using Momento Cache. It * interacts with a Momento cache client to perform operations like * fetching, adding, and deleting messages. + * @example + * ```typescript + * const chatHistory = await MomentoChatMessageHistory.fromProps({ + * client: new CacheClient({ + * configuration: Configurations.Laptop.v1(), + * credentialProvider: CredentialProvider.fromEnvironmentVariable({ + * environmentVariableName: "MOMENTO_API_KEY", + * }), + * defaultTtlSeconds: 60 * 60 * 24, + * }), + * cacheName: "langchain", + * sessionId: new Date().toISOString(), + * sessionTtl: 300, + * }); + * + * const messages = await chatHistory.getMessages(); + * console.log({ messages }); + * ``` */ export class MomentoChatMessageHistory extends BaseListChatMessageHistory { lc_namespace = ["langchain", "stores", "message", "momento"]; diff --git a/langchain/src/stores/message/mongodb.ts b/langchain/src/stores/message/mongodb.ts index 3b08aa8038ae..ccca599f1c91 100644 --- a/langchain/src/stores/message/mongodb.ts +++ b/langchain/src/stores/message/mongodb.ts @@ -10,6 +10,17 @@ export interface MongoDBChatMessageHistoryInput { sessionId: string; } +/** + * @example + * ```typescript + * const chatHistory = new MongoDBChatMessageHistory({ + * collection: myCollection, + * sessionId: 'unique-session-id', + * }); + * const messages = await chatHistory.getMessages(); + * await chatHistory.clear(); + * ``` + */ export class MongoDBChatMessageHistory extends BaseListChatMessageHistory { lc_namespace = ["langchain", "stores", "message", "mongodb"]; diff --git a/langchain/src/stores/message/planetscale.ts b/langchain/src/stores/message/planetscale.ts index 69d2c0317f53..10ca1cddf810 100644 --- a/langchain/src/stores/message/planetscale.ts +++ b/langchain/src/stores/message/planetscale.ts @@ -42,6 +42,24 @@ interface selectStoredMessagesDTO { /** * Class for storing and retrieving chat message history from a * PlanetScale database. Extends the BaseListChatMessageHistory class. + * @example + * ```typescript + * const chatHistory = new PlanetScaleChatMessageHistory({ + * tableName: "stored_message", + * sessionId: "lc-example", + * config: { + * url: "ADD_YOURS_HERE", + * }, + * }); + * const chain = new ConversationChain({ + * llm: new ChatOpenAI(), + * memory: chatHistory, + * }); + * const response = await chain.invoke({ + * input: "What did I just say my name was?", + * }); + * console.log({ response }); + * ``` */ export class PlanetScaleChatMessageHistory extends BaseListChatMessageHistory { lc_namespace = ["langchain", "stores", "message", "planetscale"]; diff --git a/langchain/src/stores/message/redis.ts b/langchain/src/stores/message/redis.ts index 0f3be850d49c..fef97ac84af7 100644 --- a/langchain/src/stores/message/redis.ts +++ b/langchain/src/stores/message/redis.ts @@ -28,6 +28,24 @@ export type RedisChatMessageHistoryInput = { /** * Class for storing chat message history using Redis. Extends the * `BaseListChatMessageHistory` class. + * @example + * ```typescript + * const chatHistory = new RedisChatMessageHistory({ + * sessionId: new Date().toISOString(), + * sessionTTL: 300, + * url: "redis: + * }); + * + * const chain = new ConversationChain({ + * llm: new ChatOpenAI({ modelName: "gpt-3.5-turbo", temperature: 0 }), + * memory: { chatHistory }, + * }); + * + * const response = await chain.invoke({ + * input: "What did I just say my name was?", + * }); + * console.log({ response }); + * ``` */ export class RedisChatMessageHistory extends BaseListChatMessageHistory { lc_namespace = ["langchain", "stores", "message", "redis"]; diff --git a/langchain/src/stores/message/xata.ts b/langchain/src/stores/message/xata.ts index 4901177e11ee..b459f38de8f2 100644 --- a/langchain/src/stores/message/xata.ts +++ b/langchain/src/stores/message/xata.ts @@ -58,6 +58,29 @@ const chatMemoryColumns: Schemas.Column[] = [ * extends the BaseListChatMessageHistory class and provides methods to * get, add, and clear messages. It also ensures the existence of a table * where the chat messages are stored. + * @example + * ```typescript + * const chatHistory = new XataChatMessageHistory({ + * table: "messages", + * sessionId: new Date().toISOString(), + * client: new BaseClient({ + * databaseURL: process.env.XATA_DB_URL, + * apiKey: process.env.XATA_API_KEY, + * branch: "main", + * }), + * apiKey: process.env.XATA_API_KEY, + * }); + * + * const chain = new ConversationChain({ + * llm: new ChatOpenAI(), + * memory: new BufferMemory({ chatHistory }), + * }); + * + * const response = await chain.invoke({ + * input: "What did I just say my name was?", + * }); + * console.log({ response }); + * ``` */ export class XataChatMessageHistory< XataClient extends BaseClient diff --git a/langchain/src/tools/google_calendar/create.ts b/langchain/src/tools/google_calendar/create.ts index 83819a85f6d3..fabc69b5a6a8 100644 --- a/langchain/src/tools/google_calendar/create.ts +++ b/langchain/src/tools/google_calendar/create.ts @@ -3,6 +3,28 @@ import { GoogleCalendarBase, GoogleCalendarAgentParams } from "./base.js"; import { runCreateEvent } from "./commands/run-create-events.js"; import { CREATE_TOOL_DESCRIPTION } from "./descriptions.js"; +/** + * @example + * ```typescript + * const googleCalendarCreateTool = new GoogleCalendarCreateTool({ + * credentials: { + * clientEmail: process.env.GOOGLE_CALENDAR_CLIENT_EMAIL, + * privateKey: process.env.GOOGLE_CALENDAR_PRIVATE_KEY, + * calendarId: process.env.GOOGLE_CALENDAR_CALENDAR_ID, + * }, + * scopes: [ + * "https: + * "https: + * ], + * model: new ChatOpenAI({}), + * }); + * const createInput = `Create a meeting with John Doe next Friday at 4pm - adding to the agenda of it the result of 99 + 99`; + * const createResult = await googleCalendarCreateTool.invoke({ + * input: createInput, + * }); + * console.log("Create Result", createResult); + * ``` + */ export class GoogleCalendarCreateTool extends GoogleCalendarBase { name = "google_calendar_create"; diff --git a/langchain/src/tools/google_calendar/view.ts b/langchain/src/tools/google_calendar/view.ts index a75a1dd9abcc..3dc2d51690dc 100644 --- a/langchain/src/tools/google_calendar/view.ts +++ b/langchain/src/tools/google_calendar/view.ts @@ -4,6 +4,26 @@ import { VIEW_TOOL_DESCRIPTION } from "./descriptions.js"; import { runViewEvents } from "./commands/run-view-events.js"; import { CallbackManagerForToolRun } from "../../callbacks/manager.js"; +/** + * @example + * ```typescript + * const googleCalendarViewTool = new GoogleCalendarViewTool({ + * credentials: { + * clientEmail: process.env.GOOGLE_CALENDAR_CLIENT_EMAIL, + * privateKey: process.env.GOOGLE_CALENDAR_PRIVATE_KEY, + * calendarId: process.env.GOOGLE_CALENDAR_CALENDAR_ID, + * }, + * scopes: [ + * "https: + * "https: + * ], + * model: new ChatOpenAI({}), + * }); + * const viewInput = `What meetings do I have this week?`; + * const viewResult = await googleCalendarViewTool.invoke({ input: viewInput }); + * console.log("View Result", viewResult); + * ``` + */ export class GoogleCalendarViewTool extends GoogleCalendarBase { name = "google_calendar_view";