本指南提供了 Amazon Nova 聊天模型的快速入门概述。Amazon Nova 模型兼容 OpenAI 接口,通过指向 Nova 端点的 OpenAI SDK 进行访问,与 LangChain 的标准接口无缝集成。Amazon Nova API 提供免费套餐,并有速率限制。
如需更高吞吐量和企业级功能的生产部署,请考虑通过 Amazon Bedrock 使用 Amazon Nova 模型。
您可以在 Amazon Nova 文档 中找到有关 Amazon Nova 模型、其功能和 API 详情的信息。
集成详情
模型功能
要访问 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,
# 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})
J'adore la programmation.
内容块
Amazon Nova 消息可以包含单个字符串或内容块列表。您可以使用 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 属性以标准格式访问工具调用:
[{'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 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")
Nova 的 tool_choice 值Amazon Nova 支持 tool_choice 值为 "auto"、"required" 和 "none"。与某些其他提供商不同,Nova 不支持 tool_choice="any" 或将特定工具名称指定为选择值。
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"]
)
当您希望对同一模型实例的不同查询使用不同的系统工具时,此方法很有用。
工具输出和引用使用系统工具时,模型的响应将包括:
- 主要文本响应
- 引用或参考(用于接地工具)
- 代码执行结果(用于代码解释器)
这些输出包含在消息的 response_metadata 中,可用于显示来源或调试。
有关系统工具、其参数和功能的完整详情,请参阅 Amazon Nova 文档。
结构化输出
Amazon Nova 通过 with_structured_output() 方法支持结构化输出,使您能够使用 Pydantic 模型或 JSON 模式以结构化格式获取 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 模式支持
您也可以直接提供 JSON 模式:
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': [...]}, ...)
这对于调试、访问元数据或处理解析可能失败的边缘情况非常有用。
嵌套和复杂模式
您可以使用嵌套 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' 以确保一致的结构化响应。模式被转换为工具定义,工具调用响应被解析回请求的格式。
模型配置文件
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 表达语言)无缝配合,用于构建链:
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)
错误处理
模型包含内置的重试逻辑,具有可配置的参数:
model = ChatAmazonNova(
model="nova-2-lite-v1",
max_retries=3, # Number of retries on failure
timeout=60.0, # Request timeout in seconds
)
要对重试进行额外控制,请使用 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 文档。
压缩错误
如果需要自定义 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 文档。