Skip to content

Commit

Permalink
[AUTO-GENERATED] Add JSDoc examples to classes. (langchain-ai#3330)
Browse files Browse the repository at this point in the history
* [AUTO-GENERATED] Add JSDoc examples to classes.

* cr
  • Loading branch information
bracesproul authored Nov 18, 2023
1 parent 8d991cf commit 1e9707f
Show file tree
Hide file tree
Showing 21 changed files with 360 additions and 0 deletions.
8 changes: 8 additions & 0 deletions langchain/src/agents/toolkits/json/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
Expand Down
18 changes: 18 additions & 0 deletions langchain/src/agents/toolkits/openapi/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
8 changes: 8 additions & 0 deletions langchain/src/agents/toolkits/sql/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
Expand Down
16 changes: 16 additions & 0 deletions langchain/src/agents/toolkits/vectorstore/vectorstore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
Expand Down
10 changes: 10 additions & 0 deletions langchain/src/agents/toolkits/zapier/zapier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = [];
Expand Down
14 changes: 14 additions & 0 deletions langchain/src/retrievers/self_query/pinecone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions langchain/src/retrievers/self_query/supabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions langchain/src/retrievers/self_query/weaviate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions langchain/src/schema/runnable/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<RunInput> extends Runnable<
RunInput,
Expand Down
28 changes: 28 additions & 0 deletions langchain/src/schema/runnable/branch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,34 @@ export type BranchLike<RunInput, RunOutput> = [
* 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<RunInput = any, RunOutput = any> extends Runnable<
Expand Down
25 changes: 25 additions & 0 deletions langchain/src/stores/message/cassandra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: "<path to your secure bundle>",
* },
* credentials: {
* username: "token",
* password: "<your Cassandra access token>",
* },
* keyspace: "langchain",
* table: "message_history",
* sessionId: "<some unique session identifier>",
* });
*
* 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"];
Expand Down
18 changes: 18 additions & 0 deletions langchain/src/stores/message/cloudflare_d1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
19 changes: 19 additions & 0 deletions langchain/src/stores/message/firestore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
18 changes: 18 additions & 0 deletions langchain/src/stores/message/ioredis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
18 changes: 18 additions & 0 deletions langchain/src/stores/message/momento.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
11 changes: 11 additions & 0 deletions langchain/src/stores/message/mongodb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"];

Expand Down
Loading

0 comments on commit 1e9707f

Please sign in to comment.