> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# ChatAmazonNova 集成

> 使用 LangChain Python 集成 ChatAmazonNova 聊天模型。

本指南提供了快速入门 Amazon Nova [聊天模型](/oss/python/langchain/models) 的概览。Amazon Nova 模型兼容 OpenAI，并通过指向 Nova 端点的 OpenAI SDK 进行访问，从而与 LangChain 的标准接口实现无缝集成。Amazon Nova API 提供免费套餐，但有速率限制。

对于需要更高吞吐量和企业功能的生产部署，请考虑通过 [Amazon Bedrock](/oss/python/integrations/chat/bedrock) 使用 Amazon Nova 模型。

您可以在 [Amazon Nova 文档](https://nova.amazon.com/dev/documentation) 中找到有关 Amazon Nova 模型、其功能和 API 详细信息。

<Tip>
  **API 参考**

  有关所有 [`ChatAmazonNova`](https://reference.langchain.com/python/langchain-amazon-nova/chat_models/ChatAmazonNova) 功能和配置选项的详细文档，请访问 [`ChatAmazonNova`](https://reference.langchain.com/python/langchain-amazon-nova/chat_models/ChatAmazonNova) API 参考。

  有关 Amazon Nova 模型的详细信息和功能，请参阅 [Amazon Nova 文档](https://nova.amazon.com/dev/documentation)。
</Tip>

## 概述

### 集成详情

| 类                                                                                                           | 包                                                                                        | 可序列化 | JS/TS 支持 |                                                   下载量                                                  |                                                 最新版本                                                |
| :---------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------- | :--: | :------: | :----------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------: |
| [`ChatAmazonNova`](https://reference.langchain.com/python/langchain-amazon-nova/chat_models/ChatAmazonNova) | [`langchain-amazon-nova`](https://reference.langchain.com/python/langchain-amazon-nova/) | beta |     ❌    | ![PyPI - Downloads](https://img.shields.io/pypi/dm/langchain-amazon-nova?style=flat-square\&label=%20) | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-amazon-nova?style=flat-square\&label=%20) |

### 模型功能

| [工具调用](/oss/python/langchain/tools) | [结构化输出](/oss/python/langchain/structured-output) | [图像输入](/oss/python/langchain/messages#multimodal) | 音频输入 |      视频输入     | [令牌级流式传输](/oss/python/langchain/streaming/) | 原生异步 | [令牌使用量](/oss/python/langchain/models#token-usage) | [对数概率](/oss/python/langchain/models#log-probabilities) |
| :---------------------------------: | :----------------------------------------------: | :-----------------------------------------------: | :--: | :-----------: | :-----------------------------------------: | :--: | :-----------------------------------------------: | :----------------------------------------------------: |
|                  ✅                  |                         ✅                        |                        模型相关                       |   ❌  | 模型相关 (Nova 2) |                      ✅                      |   ✅  |                         ✅                         |                            ❌                           |

## 设置

要访问 Amazon Nova 模型，您需要 [获取 API 凭证](https://nova.amazon.com/dev) 并安装 [`langchain-amazon-nova`](https://reference.langchain.com/python/langchain-amazon-nova/) 集成包。

### 安装

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -U langchain-amazon-nova
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langchain-amazon-nova
  ```
</CodeGroup>

### 凭证

将您的 Nova API 凭证设置为环境变量：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass
import os

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

if "NOVA_BASE_URL" not in os.environ:
    os.environ["NOVA_BASE_URL"] = getpass.getpass("Enter your Nova base URL: ")
```

要启用模型调用的自动跟踪，请设置您的 [LangSmith](/langsmith/home) API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## 实例化

现在我们可以实例化模型对象并生成聊天补全：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_amazon_nova import ChatAmazonNova

model = ChatAmazonNova(
    model="nova-2-lite-v1",
    temperature=0.7,
    max_tokens=2048,
    timeout=None,
    max_retries=2,
    # other params...
)
```

<Info>
  有关支持的参数及其描述的完整列表，请参阅 [Amazon Nova 文档](https://nova.amazon.com/dev/documentation)。
</Info>

## 调用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
messages = [
    (
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ),
    ("user", "I love programming."),
]
ai_msg = model.invoke(messages)
ai_msg
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
AIMessage(content="J'adore la programmation.", response_metadata={'model': 'nova-2-lite-v1', 'finish_reason': 'stop'}, id='run-12345678-1234-1234-1234-123456789abc', usage_metadata={'input_tokens': 29, 'output_tokens': 8, 'total_tokens': 37})
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
print(ai_msg.content)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
J'adore la programmation.
```

## 内容块

Amazon Nova 消息可以包含单个字符串或内容块列表。您可以使用 `content_blocks` 属性访问标准化的内容块：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ai_msg.content_blocks
```

使用 `content_blocks` 将以与其他模型提供商一致的标准格式呈现内容。阅读更多关于 [内容块](/oss/python/langchain/messages#standard-content-blocks) 的信息。

## 流式传输

Amazon Nova 支持令牌级流式传输，用于实时响应生成：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
for chunk in model.stream(messages):
    print(chunk.content, end="", flush=True)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
J'adore la programmation.
```

### 异步流式传输

对于异步应用程序，请使用 `astream`：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import asyncio

async def main():
    async for chunk in model.astream(messages):
        print(chunk.content, end="", flush=True)

asyncio.run(main())
```

## 工具调用

Amazon Nova 在兼容的模型上支持工具调用（函数调用）。您可以使用 LangChain 模型配置文件检查模型是否支持工具调用。

<Info>
  有关 Nova 工具调用实现和可用参数的详细信息，请参阅 [工具调用文档](https://nova.amazon.com/dev/documentation)。
</Info>

### 基本工具用法

使用 Pydantic 模型或 LangChain [`@tool`](https://reference.langchain.com/python/langchain-core/tools/convert/tool) 将工具绑定到模型：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from pydantic import BaseModel, Field

class GetWeather(BaseModel):
    """Get the weather for a location."""

    location: str = Field(description="City name")

model_with_tools = model.bind_tools([GetWeather])
response = model_with_tools.invoke("What's the weather in Paris?")
print(response.tool_calls)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{'name': 'GetWeather', 'args': {'location': 'Paris'}, 'id': 'call_abc123', 'type': 'tool_call'}]
```

您也可以使用 `tool_calls` 属性以标准格式专门访问工具调用：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
response.tool_calls
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{'name': 'GetWeather',
  'args': {'location': 'Paris'},
  'id': 'call_abc123',
  'type': 'tool_call'}]
```

### 使用 LangChain 工具

您也可以使用标准的 LangChain 工具：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.tools import tool

@tool
def get_weather(location: str) -> str:
    """Get the weather for a location."""
    return f"Weather in {location}: Sunny, 72°F"

model_with_tools = model.bind_tools([get_weather])
response = model_with_tools.invoke("What's the weather in San Francisco?")
```

### 控制工具选择

Amazon Nova 支持通过 `tool_choice` 参数控制模型何时应使用工具：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 模型决定是否调用工具（默认）
model_auto = model.bind_tools([get_weather], tool_choice="auto")

# 模型必须调用一个工具
model_required = model.bind_tools([get_weather], tool_choice="required")

# 模型不能调用工具
model_none = model.bind_tools([get_weather], tool_choice="none")
```

<Warning>
  **Nova 的 tool\_choice 值**

  Amazon Nova 支持 `tool_choice` 值为 `"auto"`、`"required"` 和 `"none"`。与某些其他提供商不同，Nova 不支持 `tool_choice="any"` 或将特定工具名称指定为选择值。
</Warning>

`tool_choice="required"` 选项对于确保模型始终使用工具特别有用，例如在结构化输出场景中。

## 系统工具

Amazon Nova 提供内置系统工具，通过集成功能增强模型的能力。这些工具通过传递给模型初始化或作为调用参数来启用。

### 可用系统工具

Amazon Nova 支持以下内置工具：

#### Web grounding (nova\_grounding)

grounding 工具允许模型搜索网络，并使用来自外部来源的实时信息来支撑其响应。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_amazon_nova import ChatAmazonNova

model_with_grounding = ChatAmazonNova(
    model="nova-2-lite-v1",
    system_tools=["nova_grounding"],
)

response = model_with_grounding.invoke("What are the latest developments in AI?")
```

grounding 工具将自动搜索相关信息，并在响应中包含引用。

#### 代码解释器 (nova\_code\_interpreter)

代码解释器工具使模型能够在沙盒环境中编写和执行 Python 代码，适用于数学计算、数据分析和代码生成任务。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_amazon_nova import ChatAmazonNova

model_with_code = ChatAmazonNova(
    model="nova-2-lite-v1",
    system_tools=["nova_code_interpreter"],
)

response = model_with_code.invoke("Calculate the fibonacci sequence up to the 10th number")
```

代码解释器安全地执行代码，并返回代码及其输出。

### 组合系统工具

您可以同时启用多个系统工具：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_amazon_nova import ChatAmazonNova

model_with_tools = ChatAmazonNova(
    model="nova-2-lite-v1",
    system_tools=["nova_grounding", "nova_code_interpreter"],
)

response = model_with_tools.invoke(
    "Search for the current price of Bitcoin and calculate its 7-day moving average"
)
```

模型将根据查询自动确定使用哪个工具。

### 系统工具作为调用参数

您也可以在调用时指定系统工具，而不是在初始化期间：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_amazon_nova import ChatAmazonNova

model = ChatAmazonNova(model="nova-2-lite-v1")

# 为此特定调用启用 grounding
response = model.invoke(
    "What's the weather today?",
    system_tools=["nova_grounding"]
)
```

当您想对同一模型实例的不同查询使用不同的系统工具时，此方法很有用。

<Info>
  **工具输出和引用**

  使用系统工具时，模型的响应将包括：

  * 主要文本响应
  * 引用或参考文献（用于 grounding 工具）
  * 代码执行结果（用于代码解释器）

  这些输出包含在消息的 `response_metadata` 中，可以访问以显示来源或进行调试。
</Info>

有关系统工具、其参数和功能的完整详细信息，请参阅 [Amazon Nova 文档](https://nova.amazon.com/dev/documentation)。

## 结构化输出

Amazon Nova 通过 `with_structured_output()` 方法支持结构化输出，使您能够使用 Pydantic 模型或 JSON 模式以结构化格式获取 LLM 响应。

### 使用 Pydantic 的基本用法

您可以使用 Pydantic 模型约束 LLM 响应以匹配特定结构：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from pydantic import BaseModel, Field
from langchain_amazon_nova import ChatAmazonNova

class Person(BaseModel):
    """Information about a person."""
    name: str = Field(description="The person's name")
    age: int = Field(description="The person's age")

model = ChatAmazonNova(model="nova-pro-v1")
structured_model = model.with_structured_output(Person)

result = structured_model.invoke("John is 30 years old")
print(result)
```

```output theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Person(name='John', age=30)
```

### JSON 模式支持

您也可以直接提供 JSON 模式：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
json_schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"}
    },
    "required": ["name", "age"]
}

structured_model = model.with_structured_output(json_schema)
result = structured_model.invoke("Sarah is 28 years old")
print(result)
```

```output theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{'name': 'Sarah', 'age': 28}
```

### 流式结构化输出

结构化输出适用于流式传输。一旦完整响应到达，将返回解析后的对象：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from pydantic import BaseModel, Field

class Person(BaseModel):
    """Information about a person."""
    name: str = Field(description="The person's name")
    age: int = Field(description="The person's age")

structured_model = model.with_structured_output(Person)

for chunk in structured_model.stream("Michael is 35 years old"):
    print(chunk)
```

```output theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Person(name='Michael', age=35)
```

### 访问原始消息

`include_raw` 参数允许同时访问解析后的输出和原始 AIMessage：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
structured_model = model.with_structured_output(Person, include_raw=True)
result = structured_model.invoke("John is 30 years old")

print(f"Parsed: {result['parsed']}")
print(f"Raw message: {result['raw']}")
```

```output theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Parsed: Person(name='John', age=30)
Raw message: AIMessage(content='', additional_kwargs={'tool_calls': [...]}, ...)
```

这对于调试、访问元数据或处理解析可能失败的边缘情况很有用。

### 嵌套和复杂模式

您可以使用嵌套的 Pydantic 模型来处理复杂的数据结构：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from pydantic import BaseModel, Field
from typing import List

class Address(BaseModel):
    """A physical address."""
    street: str
    city: str
    country: str

class Person(BaseModel):
    """Information about a person."""
    name: str
    age: int
    addresses: List[Address] = Field(description="List of addresses")

structured_model = model.with_structured_output(Person)
result = structured_model.invoke(
    "John is 30 years old. He lives at 123 Main St in Seattle, USA "
    "and has a vacation home at 456 Beach Rd in Miami, USA."
)
print(result)
```

<Info>
  **实现细节**

  结构化输出在底层使用 Nova 的工具调用功能，并设置 `tool_choice='required'` 以确保一致的结构化响应。模式被转换为工具定义，工具调用响应被解析回请求的格式。
</Info>

## 模型配置文件

Amazon Nova 提供具有不同功能的不同模型。它包括对 LangChain [模型配置文件](/oss/python/langchain/models#model-profiles) 的支持。

<Info>
  **模型功能因模型而异**

  某些 Amazon Nova 模型支持视觉输入，而其他模型则不支持。在使用多模态功能之前，请务必检查模型功能。

  有关可用模型及其功能的完整列表，请参阅 [Amazon Nova 文档](https://nova.amazon.com/dev/documentation)。
</Info>

## 异步操作

对于需要高吞吐量的生产应用程序，请使用原生异步操作：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import asyncio

async def main():
    messages = [
        ("system", "You are a helpful assistant."),
        ("human", "What is the capital of France?"),
    ]
    response = await model.ainvoke(messages)
    print(response.content)

asyncio.run(main())
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
The capital of France is Paris.
```

## 链式调用

Amazon Nova 模型与 LangChain 的 LCEL（LangChain 表达式语言）无缝协作，用于构建链：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

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

chain = prompt | model | StrOutputParser()

result = chain.invoke({
    "input_language": "English",
    "output_language": "Spanish",
    "text": "Hello, how are you?"
})
print(result)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Hola, ¿cómo estás?
```

## 错误处理

该模型包含具有可配置参数的内置重试逻辑：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
model = ChatAmazonNova(
    model="nova-2-lite-v1",
    max_retries=3,  # Number of retries on failure
    timeout=60.0,   # Request timeout in seconds
)
```

要对重试进行额外控制，请使用 `with_retry` 方法：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
model_with_custom_retry = model.with_retry(
    stop_after_attempt=5,
    wait_exponential_jitter=True,
)
```

## 故障排除

### 连接问题

如果您遇到连接错误，请验证您的环境变量是否设置正确：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
print(f"API Key set: {'NOVA_API_KEY' in os.environ}")
print(f"Base URL: {os.environ.get('NOVA_BASE_URL', 'Not set')}")
```

有关身份验证和连接问题，请参阅 [Amazon Nova 文档](https://nova.amazon.com/dev/documentation)。

### 压缩错误

<Note>
  [`ChatAmazonNova`](https://reference.langchain.com/python/langchain-amazon-nova/chat_models/ChatAmazonNova) 客户端会自动禁用压缩以避免潜在的解压缩问题。
</Note>

如果您需要自定义 HTTP 客户端行为，可以访问底层的 OpenAI 客户端：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 客户端已自动配置为不压缩
model = ChatAmazonNova(model="nova-2-lite-v1")
# model.client 是已配置的 OpenAI 客户端
```

### 工具调用验证错误

如果在绑定工具时收到验证错误，请确保模型支持工具调用。

***

## API 参考

有关所有 [`ChatAmazonNova`](https://reference.langchain.com/python/langchain-amazon-nova/chat_models/ChatAmazonNova) 功能和配置的详细文档，请访问 [`ChatAmazonNova`](https://reference.langchain.com/python/langchain-amazon-nova/chat_models/ChatAmazonNova) API 参考。

有关 Amazon Nova 特定功能、模型详细信息和 API 规范，请参阅 [Amazon Nova 文档](https://nova.amazon.com/dev/documentation)。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs) 到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/chat/amazon_nova.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
