Skip to content

Commit

Permalink
anthropic[patch]: Update JSDoc on chat model (langchain-ai#6466)
Browse files Browse the repository at this point in the history
* anthropic[patch]: Update JSDoc on chat model

* add outputs

* cr
  • Loading branch information
bracesproul authored Aug 8, 2024
1 parent be246a6 commit 758ea9b
Showing 1 changed file with 363 additions and 18 deletions.
381 changes: 363 additions & 18 deletions libs/langchain-anthropic/src/chat_models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,28 +176,373 @@ function extractToken(chunk: AIMessageChunk): string | undefined {
}

/**
* Wrapper around Anthropic large language models.
*
* To use this package, you should have an Anthropic API key set as an
* environment variable named `ANTHROPIC_API_KEY` or passed
* into the constructor.
*
* @remarks
* Any parameters that are valid to be passed to {@link
* https://console.anthropic.com/docs/api/reference |
* `anthropic.messages`} can be passed through {@link invocationKwargs},
* even if not explicitly available on this class.
* @example
* Anthropic chat model integration.
*
* Setup:
* Install `@langchain/anthropic` and set environment variable `ANTHROPIC_API_KEY`.
*
* ```bash
* npm install @langchain/anthropic
* export ANTHROPIC_API_KEY="your-api-key"
* ```
*
* ## Key args
*
* ### [Init args](/classes/langchain_anthropic.ChatAnthropic.html#constructor)
*
* ### [Runtime args](/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html)
*
* > See full list of supported init args and their descriptions in the [`constructor`](/classes/langchain_anthropic.ChatAnthropic.html#constructor) section.
*
* ## Examples
*
* <details open>
* <summary><strong>Instantiate</strong></summary>
*
* ```typescript
* 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...
* });
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Invoking</strong></summary>
*
* ```typescript
* const messages = [
* {
* type: "system" as const,
* content: "You are a helpful translator. Translate the user sentence to French.",
* },
* {
* type: "human" as const,
* content: "I love programming.",
* },
* ];
* const result = await llm.invoke(messages);
* console.log(result);
* ```
*
* ```txt
* 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
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Streaming Chunks</strong></summary>
*
* ```typescript
* for await (const chunk of await llm.stream(messages)) {
* console.log(chunk);
* }
* ```
*
* ```txt
* 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
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
*
* ```typescript
* import { AIMessageChunk } from '@langchain/core/messages';
* import { concat } from '@langchain/core/utils/stream';
*
* const stream = await llm.stream(messages);
* let full: AIMessageChunk | undefined;
* for await (const chunk of stream) {
* full = !full ? chunk : concat(full, chunk);
* }
* console.log(full);
* ```
*
* ```txt
* 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
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Bind tools</strong></summary>
*
* ```typescript
* 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);
* ```
*
* ```txt
* [
* {
* 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'
* }
* ]
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Structured Output</strong></summary>
*
* ```typescript
* import { ChatAnthropic } from "@langchain/anthropic";
* 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 model = new ChatAnthropic({
* temperature: 0.9,
* apiKey: 'YOUR-API-KEY',
* const structuredLlm = llm.withStructuredOutput(Joke);
* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
* console.log(jokeResult);
* ```
*
* ```txt
* {
* setup: "Why don't cats play poker in the jungle?",
* punchline: 'Too many cheetahs!',
* rating: 7
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Multimodal</strong></summary>
*
* ```typescript
* 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 res = await model.invoke({ input: 'Hello!' });
* console.log(res);
*
* const imageDescriptionAiMsg = await llm.invoke([message]);
* console.log(imageDescriptionAiMsg.content);
* ```
*
* ```txt
* 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.
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Usage Metadata</strong></summary>
*
* ```typescript
* const aiMsgForMetadata = await llm.invoke(messages);
* console.log(aiMsgForMetadata.usage_metadata);
* ```
*
* ```txt
* { input_tokens: 25, output_tokens: 19, total_tokens: 44 }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Stream Usage Metadata</strong></summary>
*
* ```typescript
* const streamForMetadata = await llm.stream(
* messages,
* {
* streamUsage: true
* }
* );
* let fullForMetadata: AIMessageChunk | undefined;
* for await (const chunk of streamForMetadata) {
* fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);
* }
* console.log(fullForMetadata?.usage_metadata);
* ```
*
* ```txt
* { input_tokens: 25, output_tokens: 20, total_tokens: 45 }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Response Metadata</strong></summary>
*
* ```typescript
* const aiMsgForResponseMetadata = await llm.invoke(messages);
* console.log(aiMsgForResponseMetadata.response_metadata);
* ```
*
* ```txt
* {
* 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'
* }
* ```
* </details>
*
* <br />
*/
export class ChatAnthropicMessages<
CallOptions extends ChatAnthropicCallOptions = ChatAnthropicCallOptions
Expand Down

0 comments on commit 758ea9b

Please sign in to comment.