以编程方式使用文档

本指南提供 Amazon Nova 入门快速概览 聊天模型。Amazon Nova 模型与 OpenAI 兼容,可通过指向 Nova 端点的 OpenAI SDK 访问,与 LangChain 标准接口无缝集成。Amazon Nova API 有免费套餐,但有速率限制。

对于需要更高吞吐量和企业功能的生产部署,请考虑通过 Amazon Bedrock.

您可以在以下位置找到有关 Amazon Nova 模型、功能和 API 详情的信息: Amazon Nova 文档.

概览

集成详情

ClassPackageSerializableJS/TS SupportDownloadsLatest Version
ChatAmazonNova@[langchain-amazon-novabeta 测试!PyPI - 下载量!PyPI - 版本

模型功能

工具调用结构化输出图像输入音频输入视频输入Token 级流式处理原生异步Token 使用量对数概率
取决于模型取决于模型 (Nova 2)

设置

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

安装

    pip install -U langchain-amazon-nova
    
    uv add langchain-amazon-nova
    

凭证

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

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,
    # other params...
)

调用

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 property:

ai_msg.content_blocks

使用 content_blocks 将以标准格式呈现内容,与其他模型提供商保持一致。阅读更多关于 内容块.

流式传输

Amazon Nova 支持令牌级流式传输,可实现实时响应生成:

stream = model.stream_events(messages, version="v3")
for token in stream.text:
    print(token, end="", flush=True)
J'adore la programmation.

异步流式传输

对于异步应用程序,使用 astream_events:

async def main():
    stream = await model.astream_events(messages, version="v3")
    async for token in stream.text:
        print(token, end="", flush=True)

asyncio.run(main())

工具调用

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

基本工具使用

使用 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 attribute:

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 parameter:

# Model decides whether to call tools (default)
model_auto = model.bind_tools([get_weather], tool_choice="auto")

# Model must call a tool
model_required = model.bind_tools([get_weather], tool_choice="required")

# Model cannot call tools
model_none = model.bind_tools([get_weather], tool_choice="none")

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

系统工具

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

可用的系统工具

Amazon Nova 支持以下内置工具:

网页接地(nova_grounding)

接地工具允许模型搜索网页并使用外部来源的实时信息来增强其响应。

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?")

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

代码解释器(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")

# Enable grounding for this specific call
response = model.invoke(
    "What's the weather today?",
    system_tools=["nova_grounding"]
)

当您希望对同一模型实例使用不同的系统工具处理不同查询时,这种方法非常有用。

有关系统工具、其参数和功能的完整详细信息,请参阅 Amazon Nova 文档.

结构化输出

Amazon Nova 通过以下方式支持结构化输出 with_structured_output() 方法,使您能够使用 Pydantic 模型或 JSON schema 以结构化格式获取 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 schema:

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': [...]}, ...)

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

嵌套和复杂 schema

您可以使用嵌套的 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)

模型配置

Amazon Nova 提供具有不同能力的各种模型。它包括对 LangChain 的支持 模型配置.

异步操作

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

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 表达式语言)无缝协作,用于构建链:

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,  # Number of retries on failure
    timeout=60.0,   # Request timeout in seconds
)

如需对重试进行更多控制,请使用 with_retry method:

model_with_custom_retry = model.with_retry(
    stop_after_attempt=5,
    wait_exponential_jitter=True,
)

故障排除

连接问题

如果遇到连接错误,请验证环境变量是否设置正确:

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 文档.

压缩错误

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

# The client is automatically configured with no compression
model = ChatAmazonNova(model="nova-2-lite-v1")
# model.client is the configured OpenAI client

工具调用验证错误

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

API 参考

有关所有 ChatAmazonNova 功能及配置的详细文档,请前往 ChatAmazonNova API 参考。

有关 Amazon Nova 特定功能、模型详情和 API 规范,请参阅 Amazon Nova 文档.