跳到主要內容

ChatAnthropic

本筆記本快速概述如何開始使用 Anthropic 聊天模型。如需所有 ChatAnthropic 功能和設定的詳細文檔,請前往 API 參考文檔

Anthropic 有多種聊天模型。您可以在 Anthropic 文檔中找到關於其最新模型及其成本、上下文窗口和支援的輸入類型等資訊。

AWS Bedrock 和 Google VertexAI

請注意,某些 Anthropic 模型也可以透過 AWS Bedrock 和 Google VertexAI 存取。請參閱 ChatBedrockChatVertexAI 整合,以透過這些服務使用 Anthropic 模型。

概觀

整合詳細資訊

類別套件本地可序列化JS 支援套件下載次數套件最新版本
ChatAnthropiclangchain-anthropicbetaPyPI - DownloadsPyPI - Version

模型功能

工具呼叫結構化輸出JSON 模式圖像輸入音訊輸入影片輸入Token 層級串流原生非同步Token 使用量Logprobs

設定

若要存取 Anthropic 模型,您需要建立一個 Anthropic 帳戶、取得 API 金鑰,並安裝 langchain-anthropic 整合套件。

憑證

前往 https://console.anthropic.com/ 註冊 Anthropic 並產生 API 金鑰。完成後,設定 ANTHROPIC_API_KEY 環境變數

import getpass
import os

if "ANTHROPIC_API_KEY" not in os.environ:
os.environ["ANTHROPIC_API_KEY"] = getpass.getpass("Enter your Anthropic API key: ")

如果您想要取得模型呼叫的自動追蹤,您也可以設定您的 LangSmith API 金鑰,取消註解下方即可

# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"

安裝

LangChain Anthropic 整合位於 langchain-anthropic 套件中

%pip install -qU langchain-anthropic

實例化

現在我們可以實例化我們的模型物件並產生聊天完成

from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(
model="claude-3-5-sonnet-20240620",
temperature=0,
max_tokens=1024,
timeout=None,
max_retries=2,
# other params...
)
API 參考文檔:ChatAnthropic

調用

messages = [
(
"system",
"You are a helpful assistant that translates English to French. Translate the user sentence.",
),
("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
ai_msg
AIMessage(content="J'adore la programmation.", response_metadata={'id': 'msg_018Nnu76krRPq8HvgKLW4F8T', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 29, 'output_tokens': 11}}, id='run-57e9295f-db8a-48dc-9619-babd2bedd891-0', usage_metadata={'input_tokens': 29, 'output_tokens': 11, 'total_tokens': 40})
print(ai_msg.content)
J'adore la programmation.

鏈接

我們可以像這樣使用提示範本鏈接我們的模型

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant that translates {input_language} to {output_language}.",
),
("human", "{input}"),
]
)

chain = prompt | llm
chain.invoke(
{
"input_language": "English",
"output_language": "German",
"input": "I love programming.",
}
)
API 參考文檔:ChatPromptTemplate
AIMessage(content="Here's the German translation:\n\nIch liebe Programmieren.", response_metadata={'id': 'msg_01GhkRtQZUkA5Ge9hqmD8HGY', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 23, 'output_tokens': 18}}, id='run-da5906b4-b200-4e08-b81a-64d4453643b6-0', usage_metadata={'input_tokens': 23, 'output_tokens': 18, 'total_tokens': 41})

內容區塊

Anthropic 模型與大多數其他模型之間需要注意的一個主要區別是,單個 Anthropic AI 消息的內容可以是單個字串或內容區塊列表。例如,當 Anthropic 模型調用工具時,工具調用是消息內容的一部分(以及在標準化的 AIMessage.tool_calls 中公開)

from pydantic import BaseModel, Field


class GetWeather(BaseModel):
"""Get the current weather in a given location"""

location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


llm_with_tools = llm.bind_tools([GetWeather])
ai_msg = llm_with_tools.invoke("Which city is hotter today: LA or NY?")
ai_msg.content
[{'text': "To answer this question, we'll need to check the current weather in both Los Angeles (LA) and New York (NY). I'll use the GetWeather function to retrieve this information for both cities.",
'type': 'text'},
{'id': 'toolu_01Ddzj5PkuZkrjF4tafzu54A',
'input': {'location': 'Los Angeles, CA'},
'name': 'GetWeather',
'type': 'tool_use'},
{'id': 'toolu_012kz4qHZQqD4qg8sFPeKqpP',
'input': {'location': 'New York, NY'},
'name': 'GetWeather',
'type': 'tool_use'}]
ai_msg.tool_calls
[{'name': 'GetWeather',
'args': {'location': 'Los Angeles, CA'},
'id': 'toolu_01Ddzj5PkuZkrjF4tafzu54A'},
{'name': 'GetWeather',
'args': {'location': 'New York, NY'},
'id': 'toolu_012kz4qHZQqD4qg8sFPeKqpP'}]

API 參考文檔

如需所有 ChatAnthropic 功能和設定的詳細文檔,請前往 API 參考文檔:https://langchain-python.dev.org.tw/api_reference/anthropic/chat_models/langchain_anthropic.chat_models.ChatAnthropic.html


此頁面是否對您有幫助?