langchain.js
    Preparing search index...

    Class ChatAnthropicMessages<CallOptions>

    Anthropic chat model integration.

    Setup: Install @langchain/anthropic and set an environment variable named ANTHROPIC_API_KEY.

    npm install @langchain/anthropic
    export ANTHROPIC_API_KEY="your-api-key"

    Runtime args can be passed as the second argument to any of the base runnable methods .invoke. .stream, .batch, etc. They can also be passed via .bind, or the second arg in .bindTools, like shown in the examples below:

    // When calling `.bind`, call options should be passed via the first argument
    const llmWithArgsBound = llm.bindTools([...]).withConfig({
    stop: ["\n"],
    });

    // When calling `.bindTools`, call options should be passed via the second argument
    const llmWithTools = llm.bindTools(
    [...],
    {
    tool_choice: "auto",
    }
    );
    Instantiate
    import { ChatAnthropic } from '@langchain/anthropic';

    const llm = new ChatAnthropic({
    model: "claude-3-5-sonnet-20240620",
    temperature: 0,
    maxTokens: undefined,
    maxRetries: 2,
    // apiKey: "...",
    // baseUrl: "...",
    // other params...
    });

    Invoking
    const input = `Translate "I love programming" into French.`;

    // Models also accept a list of chat messages or a formatted prompt
    const result = await llm.invoke(input);
    console.log(result);
    AIMessage {
      "id": "msg_01QDpd78JUHpRP6bRRNyzbW3",
      "content": "Here's the translation to French:\n\nJ'adore la programmation.",
      "response_metadata": {
        "id": "msg_01QDpd78JUHpRP6bRRNyzbW3",
        "model": "claude-3-5-sonnet-20240620",
        "stop_reason": "end_turn",
        "stop_sequence": null,
        "usage": {
          "input_tokens": 25,
          "output_tokens": 19
        },
        "type": "message",
        "role": "assistant"
      },
      "usage_metadata": {
        "input_tokens": 25,
        "output_tokens": 19,
        "total_tokens": 44
      }
    }
    

    Streaming Chunks
    for await (const chunk of await llm.stream(input)) {
    console.log(chunk);
    }
    AIMessageChunk {
      "id": "msg_01N8MwoYxiKo9w4chE4gXUs4",
      "content": "",
      "additional_kwargs": {
        "id": "msg_01N8MwoYxiKo9w4chE4gXUs4",
        "type": "message",
        "role": "assistant",
        "model": "claude-3-5-sonnet-20240620"
      },
      "usage_metadata": {
        "input_tokens": 25,
        "output_tokens": 1,
        "total_tokens": 26
      }
    }
    AIMessageChunk {
      "content": "",
    }
    AIMessageChunk {
      "content": "Here",
    }
    AIMessageChunk {
      "content": "'s",
    }
    AIMessageChunk {
      "content": " the translation to",
    }
    AIMessageChunk {
      "content": " French:\n\nJ",
    }
    AIMessageChunk {
      "content": "'adore la programmation",
    }
    AIMessageChunk {
      "content": ".",
    }
    AIMessageChunk {
      "content": "",
      "additional_kwargs": {
        "stop_reason": "end_turn",
        "stop_sequence": null
      },
      "usage_metadata": {
        "input_tokens": 0,
        "output_tokens": 19,
        "total_tokens": 19
      }
    }
    

    Aggregate Streamed Chunks
    import { AIMessageChunk } from '@langchain/core/messages';
    import { concat } from '@langchain/core/utils/stream';

    const stream = await llm.stream(input);
    let full: AIMessageChunk | undefined;
    for await (const chunk of stream) {
    full = !full ? chunk : concat(full, chunk);
    }
    console.log(full);
    AIMessageChunk {
      "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA",
      "content": "Here's the translation to French:\n\nJ'adore la programmation.",
      "additional_kwargs": {
        "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA",
        "type": "message",
        "role": "assistant",
        "model": "claude-3-5-sonnet-20240620",
        "stop_reason": "end_turn",
        "stop_sequence": null
      },
      "usage_metadata": {
        "input_tokens": 25,
        "output_tokens": 20,
        "total_tokens": 45
      }
    }
    

    Bind tools
    import { z } from 'zod';

    const GetWeather = {
    name: "GetWeather",
    description: "Get the current weather in a given location",
    schema: z.object({
    location: z.string().describe("The city and state, e.g. San Francisco, CA")
    }),
    }

    const GetPopulation = {
    name: "GetPopulation",
    description: "Get the current population in a given location",
    schema: z.object({
    location: z.string().describe("The city and state, e.g. San Francisco, CA")
    }),
    }

    const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
    const aiMsg = await llmWithTools.invoke(
    "Which city is hotter today and which is bigger: LA or NY?"
    );
    console.log(aiMsg.tool_calls);
    [
      {
        name: 'GetWeather',
        args: { location: 'Los Angeles, CA' },
        id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',
        type: 'tool_call'
      },
      {
        name: 'GetWeather',
        args: { location: 'New York, NY' },
        id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',
        type: 'tool_call'
      },
      {
        name: 'GetPopulation',
        args: { location: 'Los Angeles, CA' },
        id: 'toolu_0165qYWBA2VFyUst5RA18zew',
        type: 'tool_call'
      },
      {
        name: 'GetPopulation',
        args: { location: 'New York, NY' },
        id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',
        type: 'tool_call'
      }
    ]
    

    Structured Output
    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")
    }).describe('Joke to tell user.');

    const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
    const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
    console.log(jokeResult);
    {
      setup: "Why don't cats play poker in the jungle?",
      punchline: 'Too many cheetahs!',
      rating: 7
    }
    

    Multimodal
    import { HumanMessage } from '@langchain/core/messages';

    const imageUrl = "https://example.com/image.jpg";
    const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
    const base64Image = Buffer.from(imageData).toString('base64');

    const message = new HumanMessage({
    content: [
    { type: "text", text: "describe the weather in this image" },
    {
    type: "image_url",
    image_url: { url: `data:image/jpeg;base64,${base64Image}` },
    },
    ]
    });

    const imageDescriptionAiMsg = await llm.invoke([message]);
    console.log(imageDescriptionAiMsg.content);
    The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth.
    

    Usage Metadata
    const aiMsgForMetadata = await llm.invoke(input);
    console.log(aiMsgForMetadata.usage_metadata);
    { input_tokens: 25, output_tokens: 19, total_tokens: 44 }
    

    Stream Usage Metadata
    const streamForMetadata = await llm.stream(
    input,
    {
    streamUsage: true
    }
    );
    let fullForMetadata: AIMessageChunk | undefined;
    for await (const chunk of streamForMetadata) {
    fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);
    }
    console.log(fullForMetadata?.usage_metadata);
    { input_tokens: 25, output_tokens: 20, total_tokens: 45 }
    

    Response Metadata
    const aiMsgForResponseMetadata = await llm.invoke(input);
    console.log(aiMsgForResponseMetadata.response_metadata);
    {
      id: 'msg_01STxeQxJmp4sCSpioD6vK3L',
      model: 'claude-3-5-sonnet-20240620',
      stop_reason: 'end_turn',
      stop_sequence: null,
      usage: { input_tokens: 25, output_tokens: 19 },
      type: 'message',
      role: 'assistant'
    }
    

    Type Parameters

    Hierarchy (View Summary)

    Implements

    Index

    Constructors

    Properties

    anthropicApiKey?: string

    Anthropic API key

    apiKey?: string

    Anthropic API key

    apiUrl?: string
    batchClient: Anthropic
    clientOptions: ClientOptions

    Overridable Anthropic ClientOptions

    createClient: (options: ClientOptions) => Anthropic

    Optional method that returns an initialized underlying Anthropic client. Useful for accessing Anthropic models hosted on other cloud services such as Google Vertex.

    invocationKwargs?: Kwargs

    Holds any additional parameters that are valid to pass to anthropic.messages that are not explicitly specified on this class.

    lc_serializable: boolean = true
    maxTokens: number = 2048

    A maximum number of tokens to generate before stopping.

    model: string = "claude-2.1"

    Model name to use

    modelName: string = "claude-2.1"

    Use "model" instead

    stopSequences?: string[]

    A list of strings upon which to stop generating. You probably want ["\n\nHuman:"], as that's the cue for the next turn in the dialog agent.

    streaming: boolean = false

    Whether to stream the results or not

    streamingClient: Anthropic
    streamUsage: boolean = true

    Whether or not to include token usage data in streamed chunks.

    true
    
    temperature: undefined | number = 1

    Amount of randomness injected into the response. Ranges from 0 to 1. Use temp closer to 0 for analytical / multiple choice, and temp closer to 1 for creative and generative tasks. To not set this field, pass null. If undefined is passed, the default (1) will be used.

    thinking: ThinkingConfigParam = ...

    Options for extended thinking.

    topK: number = -1

    Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. Defaults to -1, which disables it.

    topP: undefined | number = -1

    Does nucleus sampling, in which we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by top_p. Defaults to -1, which disables it. Note that you should either alter temperature or top_p, but not both.

    To not set this field, pass null. If undefined is passed, the default (-1) will be used.

    For Opus 4.1, this defaults to null.

    Accessors

    • get lc_aliases(): Record<string, string>

      Returns Record<string, string>

    • get lc_secrets(): undefined | { [key: string]: string }

      Returns undefined | { [key: string]: string }

    Methods

    • Returns string

    • Parameters

      • messages: BaseMessage[]
      • options: unknown
      • OptionalrunManager: any

      Returns AsyncGenerator<ChatGenerationChunk>

    • Parameters

      Returns Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions>

    • Creates a streaming request with retry.

      Parameters

      • request: MessageCreateParamsStreaming & Kwargs

        The parameters for creating a completion.

      • Optionaloptions: RequestOptions

      Returns Promise<Stream<RawMessageStreamEvent>>

      A streaming request.

    • Formats LangChain StructuredTools to AnthropicTools.

      Parameters

      • tools: undefined | any[]

        The tools to format

      Returns undefined | ToolUnion[]

      The formatted tools, or undefined if none are passed.

    • Parameters

      • options: unknown

      Returns LangSmithParams

    • Get the identifying parameters for the model

      Returns { model_name: string }

    • Get the parameters used to invoke the model

      Parameters

      • Optionaloptions: unknown

      Returns Omit<MessageCreateParamsNonStreaming | MessageCreateParamsStreaming, "messages"> & Kwargs

    • Type Parameters

      • RunOutput extends Record<string, any> = Record<string, any>

      Parameters

      • outputSchema: any
      • Optionalconfig: any

      Returns Runnable<BaseLanguageModelInput, RunOutput>

    • Type Parameters

      • RunOutput extends Record<string, any> = Record<string, any>

      Parameters

      • outputSchema: any
      • Optionalconfig: any

      Returns Runnable<BaseLanguageModelInput, { parsed: RunOutput; raw: BaseMessage }>

    • Returns string