Skip to main content
本指南提供了快速入门 Amazon Nova 聊天模型 的概述。Amazon Nova 模型与 OpenAI 兼容,并通过指向 Nova 端点的 OpenAI SDK 访问,从而与 LangChain 的标准接口无缝集成。Amazon Nova API 提供免费层级,但有限制。 对于需要更高吞吐量和企业功能的生产部署,请考虑通过 Amazon Bedrock 使用 Amazon Nova 模型。 您可以在 Amazon Nova 文档 中找到有关 Amazon Nova 模型、其功能和 API 详细信息。
API 参考有关所有 ChatAmazonNova 功能和配置选项的详细文档,请参阅 ChatAmazonNova API 参考。有关 Amazon Nova 模型详细信息和功能,请参阅 Amazon Nova 文档

概述

集成详情

可序列化JS/TS 支持下载量最新版本
ChatAmazonNovalangchain-amazon-novabetaPyPI - 下载量PyPI - 版本

模型功能

工具调用结构化输出图像输入音频输入视频输入Token 级流式传输原生异步Token 用量Logprobs
取决于模型取决于模型 (Nova 2)

设置

要访问 Amazon Nova 模型,您需要 获取 API 凭证 并安装 langchain-amazon-nova 集成包。

安装

pip install -U langchain-amazon-nova

凭证

将您的 Nova API 凭证设置为环境变量:
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 API 密钥:
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

实例化

现在我们可以实例化模型对象并生成聊天补全:
from langchain_amazon_nova import ChatAmazonNova

model = ChatAmazonNova(
    model="nova-2-lite-v1",
    temperature=0.7,
    max_tokens=2048,
    timeout=None,
    max_retries=2,
    # 其他参数...
)
有关支持参数及其描述的完整列表,请参阅 Amazon Nova 文档

调用

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
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})
print(ai_msg.content)
J'adore la programmation.

内容块

Amazon Nova 消息可以包含单个字符串或内容块列表。您可以使用 content_blocks 属性访问标准化内容块:
ai_msg.content_blocks
使用 content_blocks 将以与其他模型提供商一致的标准格式渲染内容。了解更多关于 内容块 的信息。

流式传输

Amazon Nova 支持用于实时响应生成的 Token 级流式传输:
for chunk in model.stream(messages):
    print(chunk.content, end="", flush=True)
J'adore la programmation.

异步流式传输

对于异步应用程序,使用 astream
import asyncio

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

asyncio.run(main())

工具调用

Amazon Nova 支持兼容模型上的工具调用(函数调用)。您可以使用 LangChain 模型配置文件检查模型是否支持工具调用。
有关 Nova 工具调用实现和可用参数的详细信息,请参阅 工具调用文档

基本工具用法

使用 Pydantic 模型或 LangChain @tool 将工具绑定到模型:
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)
[{'name': 'GetWeather', 'args': {'location': 'Paris'}, 'id': 'call_abc123', 'type': 'tool_call'}]
您还可以使用 tool_calls 属性以标准格式专门访问工具调用:
response.tool_calls
[{'name': 'GetWeather',
  'args': {'location': 'Paris'},
  'id': 'call_abc123',
  'type': 'tool_call'}]

使用 LangChain 工具

您还可以使用标准 LangChain 工具:
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 参数控制模型何时使用工具:
# 模型决定是否调用工具(默认)
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")
Nova 的 tool_choice 值Amazon Nova 支持 tool_choice 值为 "auto""required""none"。与其他一些提供商不同,Nova 不支持 tool_choice="any" 或将特定工具名称指定为选择值。
tool_choice="required" 选项对于确保模型始终使用工具特别有用,例如在结构化输出场景中。

系统工具

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

可用系统工具

Amazon Nova 支持以下内置工具:

Web grounding (nova_grounding)

grounding 工具允许模型搜索 Web 并使用来自外部来源的实时信息为其响应提供依据。
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 代码,适用于数学计算、数据分析和代码生成任务。
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")
代码解释器安全地执行代码并返回代码及其输出。

组合系统工具

您可以同时启用多个系统工具:
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"
)
模型将根据查询自动确定使用哪个工具。

作为调用参数的系统工具

您还可以在调用时指定系统工具,而不是在初始化期间:
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"]
)
当您想对同一模型实例的不同查询使用不同系统工具时,此方法很有用。
工具输出和引用使用系统工具时,模型的响应将包括:
  • 主要文本响应
  • 引用或参考(对于 grounding 工具)
  • 代码执行结果(对于代码解释器)
这些输出包含在消息的 response_metadata 中,可用于显示来源或调试。
有关系统工具、其参数和功能的完整详细信息,请参阅 Amazon Nova 文档

结构化输出

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

使用 Pydantic 的基本用法

您可以使用 Pydantic 模型限制 LLM 响应以匹配特定结构:
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)
Person(name='John', age=30)

JSON schema 支持

您也可以直接提供 JSON schemas:
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)
{'name': 'Sarah', 'age': 28}

流式结构化输出

结构化输出适用于流式传输。解析后的对象在完整响应到达后返回:
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)
Person(name='Michael', age=35)

访问原始消息

include_raw 参数允许访问解析后的输出和原始 AIMessage:
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']}")
Parsed: Person(name='John', age=30)
Raw message: AIMessage(content='', additional_kwargs={'tool_calls': [...]}, ...)
这对于调试、访问元数据或处理解析可能失败的边缘情况很有用。

嵌套和复杂 schemas

您可以使用嵌套的 Pydantic 模型来处理复杂数据结构:
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)
实现细节结构化输出在底层使用 Nova 的工具调用功能,带有 tool_choice='required' 以确保一致的结构化响应。schema 被转换为工具定义,工具调用响应被解析回请求的格式。

模型配置文件

Amazon Nova 提供具有不同功能的不同模型。它支持 LangChain 模型配置文件
模型功能因模型而异某些 Amazon Nova 模型支持视觉输入,而其他模型则不支持。在使用多模态功能之前,请始终检查模型功能。有关可用模型及其功能的完整列表,请参阅 Amazon Nova 文档

异步操作

对于需要高吞吐量的生产应用程序,使用原生异步操作:
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())
The capital of France is Paris.

链式调用

Amazon Nova 模型与 LangChain 的 LCEL (LangChain Expression Language) 无缝协作以构建链:
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)
Hola, ¿cómo estás?

错误处理

模型包含具有可配置参数的内置重试逻辑:
model = ChatAmazonNova(
    model="nova-2-lite-v1",
    max_retries=3,  # 失败时的重试次数
    timeout=60.0,   # 请求超时(秒)
)
要对重试进行额外控制,请使用 with_retry 方法:
model_with_custom_retry = model.with_retry(
    stop_after_attempt=5,
    wait_exponential_jitter=True,
)

故障排除

连接问题

如果遇到连接错误,请验证环境变量是否设置正确:
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 文档

压缩错误

ChatAmazonNova 客户端自动禁用压缩以避免潜在的解压缩问题。
如果您需要自定义 HTTP 客户端行为,您可以访问底层的 OpenAI 客户端:
# 客户端自动配置为无压缩
model = ChatAmazonNova(model="nova-2-lite-v1")
# model.client 是配置好的 OpenAI 客户端

工具调用验证错误

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

API 参考

有关所有 ChatAmazonNova 功能和配置的详细文档,请参阅 ChatAmazonNova API 参考。 有关 Amazon Nova 特定功能、模型详细信息和 API 规范,请参阅 Amazon Nova 文档