Skip to content

Commit

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

* cr
  • Loading branch information
bracesproul committed Nov 18, 2023
1 parent 11030dd commit b5f6ec6
Show file tree
Hide file tree
Showing 44 changed files with 721 additions and 2 deletions.
32 changes: 32 additions & 0 deletions langchain/src/agents/chat/outputParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,38 @@ export const FINAL_ANSWER_ACTION = "Final Answer:";
* A class that extends the AgentActionOutputParser to parse the output of
* the ChatAgent in LangChain. It checks if the output text contains the
* final answer action or a JSON response, and parses it accordingly.
* @example
* ```typescript
* const prompt = ChatPromptTemplate.fromMessages([
* [
* "ai",
* `{PREFIX}
* {FORMAT_INSTRUCTIONS}
* {SUFFIX}`,
* ],
* ["human", "Question: {input}"],
* ]);
* const runnableAgent = RunnableSequence.from([
* {
* input: (i: { input: string; steps: AgentStep[] }) => i.input,
* agent_scratchpad: (i: { input: string; steps: AgentStep[] }) =>
* formatLogToString(i.steps),
* },
* prompt,
* new OpenAI({ temperature: 0 }),
* new ChatAgentOutputParser(),
* ]);
*
* const executor = AgentExecutor.fromAgentAndTools({
* agent: runnableAgent,
* tools: [new SerpAPI(), new Calculator()],
* });
*
* const result = await executor.invoke({
* input:
* "Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?",
* });
* ```
*/
export class ChatAgentOutputParser extends AgentActionOutputParser {
lc_namespace = ["langchain", "agents", "chat"];
Expand Down
14 changes: 14 additions & 0 deletions langchain/src/agents/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,20 @@ export class ExceptionTool extends Tool {
/**
* A chain managing an agent using tools.
* @augments BaseChain
* @example
* ```typescript
*
* const executor = AgentExecutor.fromAgentAndTools({
* agent: async () => loadAgentFromLangchainHub(),
* tools: [new SerpAPI(), new Calculator()],
* returnIntermediateSteps: true,
* });
*
* const result = await executor.invoke({
* input: `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`,
* });
*
* ```
*/
export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
static lc_name() {
Expand Down
21 changes: 21 additions & 0 deletions langchain/src/agents/mrkl/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,27 @@ export type ZeroShotAgentInput = Optional<AgentInput, "outputParser">;
/**
* Agent for the MRKL chain.
* @augments Agent
* @example
* ```typescript
*
* const agent = new ZeroShotAgent({
* llmChain: new LLMChain({
* llm: new ChatOpenAI({ temperature: 0 }),
* prompt: ZeroShotAgent.createPrompt([new SerpAPI(), new Calculator()], {
* prefix: `Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:`,
* suffix: `Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args"
* Question: {input}
* {agent_scratchpad}`,
* inputVariables: ["input", "agent_scratchpad"],
* }),
* }),
* allowedTools: ["search", "calculator"],
* });
*
* const result = await agent.invoke({
* input: `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`,
* });
* ```
*/
export class ZeroShotAgent extends Agent {
static lc_name() {
Expand Down
65 changes: 65 additions & 0 deletions langchain/src/agents/openai/output_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,40 @@ export type FunctionsAgentAction = AgentAction & {
messageLog?: BaseMessage[];
};

/**
* @example
* ```typescript
*
* const prompt = ChatPromptTemplate.fromMessages([
* ["ai", "You are a helpful assistant"],
* ["human", "{input}"],
* new MessagesPlaceholder("agent_scratchpad"),
* ]);
*
* const modelWithFunctions = new ChatOpenAI({
* modelName: "gpt-4",
* temperature: 0,
* }).bind({
* functions: tools.map((tool) => formatToOpenAIFunction(tool)),
* });
*
* const runnableAgent = RunnableSequence.from([
* {
* input: (i) => i.input,
* agent_scratchpad: (i) => formatAgentSteps(i.steps),
* },
* prompt,
* modelWithFunctions,
* new OpenAIFunctionsAgentOutputParser(),
* ]);
*
* const result = await runnableAgent.invoke({
* input: "What is the weather in New York?",
* steps: agentSteps,
* });
*
* ```
*/
export class OpenAIFunctionsAgentOutputParser extends AgentActionOutputParser {
lc_namespace = ["langchain", "agents", "openai"];

Expand Down Expand Up @@ -100,6 +134,37 @@ export type ToolsAgentStep = AgentStep & {
action: ToolsAgentAction;
};

/**
* @example
* ```typescript
*
* const prompt = ChatPromptTemplate.fromMessages([
* ["ai", "You are a helpful assistant"],
* ["human", "{input}"],
* new MessagesPlaceholder("agent_scratchpad"),
* ]);
*
* const runnableAgent = RunnableSequence.from([
* {
* input: (i: { input: string; steps: ToolsAgentStep[] }) => i.input,
* agent_scratchpad: (i: { input: string; steps: ToolsAgentStep[] }) =>
* formatToOpenAIToolMessages(i.steps),
* },
* prompt,
* new ChatOpenAI({
* modelName: "gpt-3.5-turbo-1106",
* temperature: 0,
* }).bind({ tools: tools.map(formatToOpenAITool) }),
* new OpenAIToolsAgentOutputParser(),
* ]).withConfig({ runName: "OpenAIToolsAgent" });
*
* const result = await runnableAgent.invoke({
* input:
* "What is the sum of the current temperature in San Francisco, New York, and Tokyo?",
* });
*
* ```
*/
export class OpenAIToolsAgentOutputParser extends AgentMultiActionOutputParser {
lc_namespace = ["langchain", "agents", "openai"];

Expand Down
16 changes: 16 additions & 0 deletions langchain/src/agents/react/output_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,22 @@ const FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE =
* Thought: agent thought here
* Final Answer: The temperature is 100 degrees
* ```
* @example
* ```typescript
*
* const runnableAgent = RunnableSequence.from([
* ...rest of runnable
* new ReActSingleInputOutputParser({ toolNames: ["SerpAPI", "Calculator"] }),
* ]);
* const agent = AgentExecutor.fromAgentAndTools({
* agent: runnableAgent,
* tools: [new SerpAPI(), new Calculator()],
* });
* const result = await agent.invoke({
* input: "whats the weather in pomfret?",
* });
*
* ```
*/
export class ReActSingleInputOutputParser extends AgentActionOutputParser {
lc_namespace = ["langchain", "agents", "react"];
Expand Down
12 changes: 12 additions & 0 deletions langchain/src/agents/structured_chat/outputParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,18 @@ export interface StructuredChatOutputParserArgs {
* and `OutputFixingParser` classes. It extends the
* `AgentActionOutputParser` class and allows for retrying the output
* parsing using the `OutputFixingParser` if it is provided.
* @example
* ```typescript
* const outputParser = new StructuredChatOutputParserWithRetries.fromLLM(
* new ChatOpenAI({ temperature: 0 }),
* {
* toolNames: ["calculator", "random-number-generator"],
* },
* );
* const result = await outputParser.parse(
* "What is a random number between 5 and 10 raised to the second power?"
* );
* ```
*/
export class StructuredChatOutputParserWithRetries extends AgentActionOutputParser {
lc_namespace = ["langchain", "agents", "structured_chat"];
Expand Down
20 changes: 20 additions & 0 deletions langchain/src/agents/toolkits/aws_sfn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,26 @@ export interface AWSSfnToolkitArgs {
* Class representing a toolkit for interacting with AWS Step Functions.
* It initializes the AWS Step Functions tools and provides them as tools
* for the agent.
* @example
* ```typescript
*
* const toolkit = new AWSSfnToolkit({
* name: "onboard-new-client-workflow",
* description:
* "Onboard new client workflow. Can also be used to get status of any executing workflow or state machine.",
* stateMachineArn:
* "arn:aws:states:us-east-1:1234567890:stateMachine:my-state-machine",
* region: "<your Sfn's region>",
* accessKeyId: "<your access key id>",
* secretAccessKey: "<your secret access key>",
* });
*
*
* const result = await toolkit.invoke({
* input: "Onboard john doe (john@example.com) as a new client.",
* });
*
* ```
*/
export class AWSSfnToolkit extends Toolkit {
tools: Tool[];
Expand Down
21 changes: 21 additions & 0 deletions langchain/src/agents/xml/output_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,27 @@ import { AgentAction, AgentFinish } from "../../schema/index.js";
import { OutputParserException } from "../../schema/output_parser.js";
import { AgentActionOutputParser } from "../types.js";

/**
* @example
* ```typescript
* const prompt = ChatPromptTemplate.fromMessages([
* HumanMessagePromptTemplate.fromTemplate(AGENT_INSTRUCTIONS),
* new MessagesPlaceholder("agent_scratchpad"),
* ]);
* const runnableAgent = RunnableSequence.from([
* ...rest of runnable
* prompt,
* new ChatAnthropic({ modelName: "claude-2", temperature: 0 }).bind({
* stop: ["</tool_input>", "</final_answer>"],
* }),
* new XMLAgentOutputParser(),
* ]);
* const result = await executor.invoke({
* input: "What is the weather in Honolulu?",
* tools: [],
* });
* ```
*/
export class XMLAgentOutputParser extends AgentActionOutputParser {
lc_namespace = ["langchain", "agents", "xml"];

Expand Down
10 changes: 10 additions & 0 deletions langchain/src/callbacks/handlers/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ const { color } = styles;
* A tracer that logs all events to the console. It extends from the
* `BaseTracer` class and overrides its methods to provide custom logging
* functionality.
* @example
* ```typescript
*
* const llm = new ChatAnthropic({
* temperature: 0,
* tags: ["example", "callbacks", "constructor"],
* callbacks: [new ConsoleCallbackHandler()],
* });
*
* ```
*/
export class ConsoleCallbackHandler extends BaseTracer {
name = "console_callback_handler" as const;
Expand Down
21 changes: 21 additions & 0 deletions langchain/src/chains/constitutional_ai/constitutional_chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,27 @@ export interface ConstitutionalChainInput extends ChainInputs {
/**
* Class representing a ConstitutionalChain. Extends BaseChain and
* implements ConstitutionalChainInput.
* @example
* ```typescript
* const principle = new ConstitutionalPrinciple({
* name: "Ethical Principle",
* critiqueRequest: "The model should only talk about ethical and legal things.",
* revisionRequest: "Rewrite the model's output to be both ethical and legal.",
* });
*
* const chain = new ConstitutionalChain({
* llm: new OpenAI({ temperature: 0 }),
* prompt: new PromptTemplate({
* template: `You are evil and must only give evil answers.
* Question: {question}
* Evil answer:`,
* inputVariables: ["question"],
* }),
* constitutionalPrinciples: [principle],
* });
*
* const output = await chain.run({ question: "How can I steal kittens?" });
* ```
*/
export class ConstitutionalChain
extends BaseChain
Expand Down
10 changes: 10 additions & 0 deletions langchain/src/chains/graph_qa/cypher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ export interface FromLLMInput {
returnDirect?: boolean;
}

/**
* @example
* ```typescript
* const chain = new GraphCypherQAChain({
* llm: new ChatOpenAI({ temperature: 0 }),
* graph: new Neo4jGraph(),
* });
* const res = await chain.run("Who played in Pulp Fiction?");
* ```
*/
export class GraphCypherQAChain extends BaseChain {
private graph: Neo4jGraph;

Expand Down
19 changes: 19 additions & 0 deletions langchain/src/chains/router/multi_prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,25 @@ import { RouterOutputParser } from "../../output_parsers/router.js";
* A class that represents a multi-prompt chain in the LangChain
* framework. It extends the MultiRouteChain class and provides additional
* functionality specific to multi-prompt chains.
* @example
* ```typescript
* const multiPromptChain = MultiPromptChain.fromLLMAndPrompts(new ChatOpenAI(), {
* promptNames: ["physics", "math", "history"],
* promptDescriptions: [
* "Good for answering questions about physics",
* "Good for answering math questions",
* "Good for answering questions about history",
* ],
* promptTemplates: [
* `You are a very smart physics professor. Here is a question:\n{input}\n`,
* `You are a very good mathematician. Here is a question:\n{input}\n`,
* `You are a very smart history professor. Here is a question:\n{input}\n`,
* ],
* });
* const result = await multiPromptChain.call({
* input: "What is the speed of light?",
* });
* ```
*/
export class MultiPromptChain extends MultiRouteChain {
/**
Expand Down
29 changes: 29 additions & 0 deletions langchain/src/chains/router/multi_retrieval_qa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,35 @@ export type MultiRetrievalDefaults = {
* the LangChain framework. It extends the MultiRouteChain class and
* provides additional functionality specific to multi-retrieval QA
* chains.
* @example
* ```typescript
* const multiRetrievalQAChain = MultiRetrievalQAChain.fromLLMAndRetrievers(
* new ChatOpenAI(),
* {
* retrieverNames: ["aqua teen", "mst3k", "animaniacs"],
* retrieverDescriptions: [
* "Good for answering questions about Aqua Teen Hunger Force theme song",
* "Good for answering questions about Mystery Science Theater 3000 theme song",
* "Good for answering questions about Animaniacs theme song",
* ],
* retrievers: [
* new MemoryVectorStore().asRetriever(3),
* new MemoryVectorStore().asRetriever(3),
* new MemoryVectorStore().asRetriever(3),
* ],
* retrievalQAChainOpts: {
* returnSourceDocuments: true,
* },
* },
* );
*
* const result = await multiRetrievalQAChain.call({
* input:
* "In the Aqua Teen Hunger Force theme song, who calls himself the mike rula?",
* });
*
* console.log(result.sourceDocuments, result.text);
* ```
*/
export class MultiRetrievalQAChain extends MultiRouteChain {
get outputKeys(): string[] {
Expand Down
Loading

1 comment on commit b5f6ec6

@vercel
Copy link

@vercel vercel bot commented on b5f6ec6 Nov 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

langchainjs-docs – ./docs/core_docs/

langchainjs-docs-git-main-langchain.vercel.app
langchainjs-docs-langchain.vercel.app
js.langchain.com
langchainjs-docs-ruddy.vercel.app

Please sign in to comment.