2026/10/2 8:04:12

Amazon Bedrock 文本生成实战:Invoke API 与 Converse API 从摘要、代码生成到函数调用完整指南

Amazon Bedrock 文本生成实战:Invoke API 与 Converse API 从摘要、代码生成到函数调用完整指南 示例工程【免费下载链接】amazon-bedrock-workshopThis is a workshop designed for Amazon Bedrock a foundational model service.项目地址https://gitcode.com/GitHub_Trending/am/amazon-bedrock-workshop点击查看免费下载导读本文是 Amazon Bedrock Workshop 系列的第一个模块Module 1 - Text Generation的完整技术解读对应仓库中的 01_Text_generation/README.md 及其核心实验 Notebook 01_text_and_code_generation_w_bedrock.ipynb。你将掌握 Amazon Bedrock 两套文本推理 API基础的 Invoke Model API 与功能更强的 Converse API的调用模式并实际完成文本摘要、跨模型对比、跨区域推理、多轮对话、流式响应、代码生成与函数调用Function Calling / Tool Use六大实战场景。读完本文你可以直接用 boto3 在 SageMaker Studio 或自有环境中编写可切换任意受支持模型的对话式 AI 应用。1. 模块定位与实验环境1.1 这个模块讲什么根据 01_Text_generation/README.md 的说明本模块的学习目标非常明确掌握 Amazon BedrockInvoke API的基础用法探索功能更强大的Converse API包括多轮对话multi-turn conversation、流式输出streaming与函数调用function calling将上述 API 应用于多种基础模型对比不同前沿模型state-of-the-art models的结果差异。README 同时要求按照 Notebook 的命名顺序逐个执行实验Please go through the module by executing the notebook labs in their naming order.因此下文将严格按照 Notebook 的章节脉络Setup → 摘要 → 代码生成 → 函数调用 → 总结展开。1.2 前置条件与运行环境需要能够访问Amazon Bedrock的权限Notebook 的 Pre-requisites 一节明确要求 Access Amazon Bedrock。整个仓库建议在Amazon SageMaker Studio的 JupyterLab 空间中运行见根目录 README.mdAWS 举办的 workshop 环境会预装好依赖。依赖管理由仓库根目录的 pyproject.toml 定义其中与本模块直接相关的核心依赖为boto31.43.24AWS SDK for Python与ipython9.14.1。若在自定义环境中运行取消 Notebook 中# %pip install -e ..一行的注释即可安装。Python 版本要求3.12见 pyproject.toml 中requires-python字段。1.3 客户端初始化所有实验都基于bedrock-runtime客户端。Notebook 中的初始化代码非常简洁import json import time import boto3 # AWS SDK for Python from botocore.exceptions import ClientError # for error handling # Initialize Bedrock client session boto3.Session() region session.region_name bedrock boto3.client(service_namebedrock-runtime, region_nameregion)接下来 Notebook 定义了一个贯穿全程的模型字典默认模型为 Claude Haiku 4.5并给出了五个可切换的模型 ID注意这些 ID 均为带us.前缀的跨区域推理 Profile 格式而非裸模型 ID第 2.5 节会详述原因MODELS { Claude Haiku 4.5: us.anthropic.claude-haiku-4-5-20251001-v1:0, Claude Sonnet 4.5: us.anthropic.claude-sonnet-4-5-20250929-v1:0, Amazon Nova Pro: us.amazon.nova-pro-v1:0, Amazon Nova 2 Lite: us.amazon.nova-2-lite-v1:0, Meta Llama 3.1 70B Instruct: us.meta.llama3-1-70b-instruct-v1:0, }仓库中 tutor/learning_paths/text-generation.md配套教学路径文档给出了一个等价的最小化 Hello World 模式可用于快速验证连通性import boto3 client boto3.client(bedrock-runtime, region_nameREGION) response client.converse( modelIdus.anthropic.claude-haiku-4-5-20251001-v1:0, messages[ {role: user, content: [{text: Hello! Introduce yourself.}]} ] ) print(response[output][message][content][0][text])2. 文本摘要从 Invoke Model API 到 Converse APINotebook 以一段介绍 Amazon Bedrock 的 AWS 博客文字text_to_summarize作为统一的摘要素材先后演示两套 API。2.1 Invoke Model API逐模型定制请求体Invoke Model API 是向基础模型发送请求的最基础方式。其核心特点是每个模型家族都有自己独特的请求/响应格式调用方必须为特定模型手工构造 JSON payload。Notebook 以 Claude Haiku 4.5 为例构造请求体注意其中包含 Anthropic 特有的字段prompt fPlease provide a summary of the following text. Do not add any information that is not mentioned in the text below. text {text_to_summarize} /text claude_body json.dumps( { anthropic_version: bedrock-2023-05-31, max_tokens: 1000, temperature: 0.5, messages: [{role: user, content: [{type: text, text: prompt}]}], } ) response bedrock.invoke_model( modelIdMODELS[Claude Haiku 4.5], bodyclaude_body, acceptapplication/json, contentTypeapplication/json, ) response_body json.loads(response.get(body).read()) claude_summary response_body[content][0][text]几个值得注意的细节invoke_model的 body 是一个字符串由json.dumps序列化且响应正文需要通过response.get(body).read()读取后再反序列化Claude 系模型要求显式传入anthropic_version: bedrock-2023-05-31并且消息结构为messages[].content[]列表若要调用 Llama、Nova 等其他模型则需要按其各自的参数规范如max_gen_len、top_p等重写请求体——这正是 Invoke API 的痛点。Notebook 还演示了标准化的异常处理捕获ClientError当错误码为AccessDeniedException时输出 IAM 权限排障指引否则重新抛出。2.2 Converse API统一的消息接口Converse API 的请求结构对所有支持 messages 的模型一致无需为每个模型改写 payload。同样的摘要任务用 Converse API 表达为converse_request { messages: [ { role: user, content: [ {text: fPlease provide a concise summary of the following text in 2-3 sentences. Text to summarize: {text_to_summarize}} ], } ], inferenceConfig: { maxTokens: 500, temperature: 0.4, }, } response bedrock.converse( modelIdMODELS[Claude Haiku 4.5], messagesconverse_request[messages], inferenceConfigconverse_request[inferenceConfig], ) claude_converse_response response[output][message][content][0][text]2.3 Converse API 关键参数详解Notebook 用一个带注释的 JSON 结构完整列出了 Converse API 的核心组件这是理解本模块的钥匙{ modelId: us.anthropic.claude-haiku-4-5-20251001-v1:0, // Required: Model identifier messages: [ // Required: Conversation history { role: user, // Who sent the message content: [ { text: Your prompt or message here } // Message content ] } ], system: [ // Optional: System instructions { text: You are a helpful AI assistant. } ], inferenceConfig: { // Optional: Inference parameters temperature: 0.7, // Randomness (0.0-1.0) topP: 0.9, // Diversity control (0.0-1.0) maxTokens: 2000, // Maximum response length stopSequences: [] // Stop generation triggers }, toolConfig: { // Optional: Function calling setup tools: [], toolChoice: { auto: {} } // Let model decide when to use tools } }参数语义归纳参数层级作用备注modelId顶层必填模型标识符本模块中使用带区域前缀的 inference profilemessages顶层必填对话历史role取user/assistantcontent为内容块列表多轮对话时逐轮追加system顶层可选系统指令设定人设与行为约束对整段对话持续生效inferenceConfig.temperature推理配置可选采样随机性范围 0.0–1.00.0 偏确定性适合代码生成与结构化任务inferenceConfig.topP推理配置可选核采样多样性控制0.0–1.0与 temperature 协同控制输出inferenceConfig.maxTokens推理配置可选最大生成长度防止超长与成本失控inferenceConfig.stopSequences推理配置可选停止序列命中即终止生成toolConfig.tools/toolConfig.toolChoice推理配置可选工具定义与选择策略auto表示由模型自行决定是否调用工具关于inferenceConfig的取值经验仓库的 tutor/learning_paths/text-generation.md 给出了可复用的最佳实践默认从temperature0.7起步作为平衡值生产系统追求一致性时用0.0创造性写作/头脑风暴用0.7–1.0始终设置maxTokens以避免意外成本。为什么推荐 Converse APINotebook 明确指出提供一致的 API适用于所有支持 messages 的 Bedrock 模型——代码写一次即可复用若某模型有独有推理参数Converse API 允许以模型特有结构透传原生支持多轮对话、tool use工具调用与guardrails护栏适合构建带人设/语气定制的聊天机器人。2.4 同一请求切换多模型质量与延迟对比Converse API 的最大优势在此体现同一份请求循环调用不同模型即可对比。Notebook 遍历MODELS字典向每个模型发送完全相同的摘要请求并记录响应与耗时results {} for model_name, model_id in MODELS.items(): # looping over all models defined above try: start_time time.time() response bedrock.converse( modelIdmodel_id, messagesconverse_request[messages], inferenceConfigconverse_request[inferenceConfig] if inferenceConfig in converse_request else None, ) end_time time.time() model_response response[output][message][content][0][text] response_time round(end_time - start_time, 2) results[model_name] {response: model_response, time: response_time} print(f✅ Successfully called {model_name} (took {response_time} seconds)) except Exception as e: print(f❌ Error calling {model_name}: {str(e)}) results[model_name] {response: fError: {str(e)}, time: None}随后 Notebook 逐模型格式化展示响应与耗时让你在不改动任何应用代码的前提下评估 Claude Haiku 4.5、Claude Sonnet 4.5、Amazon Nova Pro、Amazon Nova 2 Lite、Meta Llama 3.1 70B 的质量与延迟差异。这里的results字典还会被第 2.6 节的多轮对话复用作为上一轮的 assistant 回复。2.5 跨区域推理Cross-Regional InferenceConverse API 的modelId位置可以填跨区域推理 Profileinference profile由 Bedrock 自动在所选地理范围内选择最优区域处理请求。Notebook 归纳了三个地理前缀us.— 仅在美区区域间路由eu.— 仅在欧区区域间路由global.— 在全球所有受支持区域间路由。{ US regional profile: us.anthropic.claude-haiku-4-5-20251001-v1:0, Global profile: global.anthropic.claude-haiku-4-5-20251001-v1:0 }跨区域推理带来的收益依 Notebook 原文最高可达约 2 倍的配额吞吐上限、在高峰时段跨区域动态路由以增强韧性无额外路由与数据传输成本、可由客户选择预定义区域集以符合数据驻留与主权法规并优先就近使用 Bedrock API 源区域以降低延迟。特别提醒像 Claude Haiku 4.5 这样的较新模型必须使用带前缀的 inference profile直接以无前缀方式按需调用不被支持。这正是本模块MODELS字典中所有 ID 都带us.前缀的原因。Notebook 还演示了如何用一行代码把us.前缀替换为global.来切换 profilecris_messages [ {role: user, content: [{text: In one sentence, what is the Amazon Bedrock Converse API?}]} ] # US cross-region inference profile (routes within US regions) us_response bedrock.converse(modelIdMODELS[Claude Haiku 4.5], messagescris_messages) # Global cross-region inference profile (routes across all supported regions) global_response bedrock.converse( modelIdglobal. MODELS[Claude Haiku 4.5][3:], # swap us. for global. messagescris_messages, )两种 profile 都会返回有效响应实践中global.profile 在峰值期间可用性可能更高。2.6 多轮对话让上下文延续Converse API 让多轮对话变得简单——只需把历史消息按user → assistant → user的交替顺序传入messages即可。Notebook 先让模型完成摘要再要求把摘要压缩成一句话验证模型能理解前文multi_turn_messages [ {role: user, content: [{text: fPlease summarize this text: {text_to_summarize}}]}, {role: assistant, content: [{text: results[Claude Haiku 4.5][response]}]}, {role: user, content: [{text: Can you make this summary even shorter, just 1 sentence?}]}, ] response bedrock.converse( modelIdMODELS[Claude Haiku 4.5], messagesmulti_turn_messages, inferenceConfig{temperature: 0.2, maxTokens: 500}, ) follow_up_response response[output][message][content][0][text]注意其中assistant角色的消息内容直接取自上一轮results字典中的真实模型输出——这是聊天机器人每轮构建在先前上下文之上的实现本质。2.7 流式响应ConverseStream API对于长文本生成流式输出能显著改善用户体验。Notebook 封装了一个可复用的stream_converse函数核心是bedrock.converse_stream与对事件流的逐事件处理def stream_converse(model_id, messages, inference_configNone): if inference_config is None: inference_config {} full_response try: response bedrock.converse_stream( modelIdmodel_id, messagesmessages, inferenceConfiginference_config ) response_stream response.get(stream) if response_stream: for event in response_stream: if messageStart in event: print(f\nRole: {event[messageStart][role]}) if contentBlockDelta in event: print(event[contentBlockDelta][delta][text], end) if messageStop in event: print(f\nStop reason: {event[messageStop][stopReason]}) if metadata in event: metadata event[metadata] if usage in metadata: print(\nToken usage) print(fInput tokens: {metadata[usage][inputTokens]}) print(fOutput tokens: {metadata[usage][outputTokens]}) print(fTotal tokens: {metadata[usage][totalTokens]}) if metrics in event[metadata]: print(fLatency: {metadata[metrics][latencyMs]} milliseconds) return full_response except Exception as e: print(fError in streaming: {str(e)}) return None流式事件的关键类型可从代码结构推断messageStart— 流开始携带rolecontentBlockDelta— 内容增量其中delta.text是需要拼接的文本片段这就是逐块打印的实现messageStop— 流结束携带stopReasonmetadata— 携带usage输入/输出/总 token 数与metricslatencyMs延迟毫秒数。调用示例向 Claude Haiku 4.5 请求一份详细、包含关键点与含义的长摘要temperature0.4, maxTokens1000。3. 代码生成让模型写函数基础模型不仅能写散文也能生成编程代码。Notebook 让 Claude 生成一个get_weather函数——这个函数会在第 4 节作为工具被集成进函数调用流程。3.1 为代码生成设计确定性提示词提示词通过明确的规则约束输出格式这是代码生成提示工程的关键code_generation_prompt Create a Python function called get_weather that accepts a location as a string parameter. The function should return a dictionary containing weather data (condition, temperature, humidity) using hardcoded mock values for predefined cities. Include New York, San Francisco, Miami, and Seattle as default cities. The return statement must be: return weather_data.get(location, {condition: Unknown, temperature: 0, humidity: 0}) Rules: - Return ONLY the function definition, nothing else - No imports of any kind - No main() function - No API calls, no SDK usage, no class definitions - No preamble, explanation, or markdown formatting 3.2 用 temperature0.0 获取确定性输出代码生成受益于低随机性Notebook 将temperature设为0.0保证每次运行生成的函数一致converse_request { messages: [{role: user, content: [{text: f{code_generation_prompt}}]}], inferenceConfig: {temperature: 0.0, maxTokens: 500}, } response bedrock.converse( modelIdMODELS[Claude Haiku 4.5], messagesconverse_request[messages], inferenceConfigconverse_request[inferenceConfig], ) claude_converse_response response[output][message][content][0][text]生成后Notebook 要求把函数定义复制粘贴到下方单元格中使其成为当前 Kernel 中可被调用的真实函数若复制出错也提供了备用的硬编码实现含 New York / San Francisco / Miami / Seattle 四城天气数据未知城市返回{condition: Unknown, temperature: 0, humidity: 0}。4. 函数调用Function Calling / Tool Use4.1 函数调用是什么现代 LLM 不仅能生成自由文本还能推理何时应调用外部工具/函数——这就是函数调用function calling又称 tool use。Notebook 强调三个关键事实模型负责决定调用哪个函数、何时调用、传入什么参数但模型自身并不执行函数模型返回结构化结果通常为 JSON描述其意图的函数调用由你的应用检测该输出、执行函数如调用 API 或查询数据库再把结果回传给模型最终让模型生成融合真实数据的用户友好回复。典型的函数调用流程分三步Notebook 原图流程Step 1 - Function Recognition模型识别需要工具如西雅图天气如何返回函数名get_weather与输入参数locationSeattleStep 2 - Function Execution由应用执行执行函数、捕获输出如当前天气数据、把结果回传给模型Step 3 - Final Response GenerationLLM 基于函数输出生成面向用户的自然语言回复。4.2 工具规范toolSpec与请求构造工具规范用 JSON Schema 描述函数签名。本模块为get_weather定义如下toolConfigweather_tool { tools: [ { toolSpec: { name: get_weather, description: Get current weather for a specific location, inputSchema: { json: { type: object, properties: { location: { type: string, description: The city name to get weather for, } }, required: [location], } }, } } ], toolChoice: { auto: {} # Let the model decide when to use the tool }, }配套的函数调用请求temperature0.0保证函数调用的确定性function_request { messages: [ { role: user, content: [ {text: Whats the weather like in San Francisco right now? And what should I wear?} ], } ], inferenceConfig: { temperature: 0.0, # Use 0 temperature for deterministic function calling maxTokens: 500, }, }将两者一并传给bedrock.converse后模型会在响应内容块中正确填充toolUse结构——用print(json.dumps(response, indent2))可以直观看到模型输出的toolUse块包含toolUseId、name、input。4.3 完整函数调用闭环handle_function_callingNotebook 把整个闭环封装为handle_function_calling(model_id, request, tool_config)是本文最值得精读的实现其逻辑分四步Step 1发送初始请求并检测 toolUseresponse bedrock.converse( modelIdmodel_id, messagesrequest[messages], inferenceConfigrequest[inferenceConfig], toolConfigtool_config, ) content_blocks response[output][message][content] has_tool_use any(toolUse in block for block in content_blocks)Step 2解析 toolUse 并执行工具tool_use_block next(block for block in content_blocks if toolUse in block) tool_use tool_use_block[toolUse] tool_name tool_use[name] tool_input tool_use[input] tool_use_id tool_use[toolUseId] if tool_name get_weather: tool_result get_weather(tool_input[location]) # noqa: F821 else: tool_result {error: fUnknown tool: {tool_name}}Step 3把工具结果以 toolResult 消息回传模型updated_messages request[messages] [ { role: assistant, content: [{toolUse: {toolUseId: tool_use_id, name: tool_name, input: tool_input}}], }, { role: user, content: [{toolResult: {toolUseId: tool_use_id, content: [{json: tool_result}], status: success}}], }, ]Step 4再次调用模型得到最终自然语言回复final_response bedrock.converse( modelIdmodel_id, messagesupdated_messages, inferenceConfigrequest[inferenceConfig], toolConfigtool_config, ) final_text for block in final_response[output][message][content]: if text in block: final_text block[text] break返回结构汇总了三要素tool_call函数名与输入、tool_result执行结果、final_response最终回复。若模型本轮未触发工具has_tool_use为 False则直接返回文本回复。执行示例function_result handle_function_calling(MODELS[Claude Haiku 4.5], function_request, weather_tool) if tool_call in function_result: print(fTool Call: {function_result[tool_call][name]}({function_result[tool_call][input]})) print(fTool Result: {function_result[tool_result]}) display_response(function_result[final_response], Claude Haiku 4.5 (Function Calling))从实现细节可以看出两个工程要点toolResult必须通过toolUseId与模型请求的toolUse一一对应toolResult的content使用{json: tool_result}结构化块承载数据。5. 总结与下一步Notebook 的 Conclusion 一节将本模块的成果归纳为六项能力文本摘要同时使用 Invoke 与 Converse API 生成简洁摘要模型灵活性同一请求轻松切换不同基础模型多轮对话用 Converse API 构建带上下文的对话流式响应用 ConverseStream API 实现实时内容交付代码生成用 LLM 生成可用的函数代码函数调用集成外部工具获取指定位置的天气信息。完成本模块后即可进入下一章Knowledge Bases 与 RAG对应仓库 02_Knowledge_Bases_and_RAG/README.md包含知识库构建、托管 RAG 的 RetrieveAndGenerate API 与自定义 RAG 管线的 Retrieve API。整个仓库的模块路径为文本生成01→ 知识库与 RAG02→ 模型定制03含微调、蒸馏与强化微调→ Agents04→ 分布式推理引擎05本模块为后续所有对话式 AI 实验奠定了 API 调用基础。赞分享示例工程【免费下载链接】amazon-bedrock-workshopThis is a workshop designed for Amazon Bedrock a foundational model service.项目地址https://gitcode.com/GitHub_Trending/am/amazon-bedrock-workshop点击查看免费下载相关推荐如何在3分钟内构建专业级企业组织结构图d3-org-chart完全指南如何在3分钟内构建专业级企业组织结构图d3 org chart完全指南 还在为复杂的企业组织架构可视化而烦恼吗传统的图表工具要么功能受限要么配置复杂难以使用 AWS SDK for Kotlin 调用 Amazon Bedrock RuntimeAmazon Nova 文本生成与图像生成实战指南使用 AWS SDK for Kotlin 调用 Amazon Bedrock RuntimeAmazon Nova 文本生成与图像生成实战指南 导读 本文基示例工程教程后端Data-Science-EBooks数据科学学习者的终极免费资源宝库Data Science EBooks数据科学学习者的终极免费资源宝库 你是否正在寻找高质量的数据科学学习资源Data Science EBooks项目为你上一篇UmiJS 4终极性能优化指南5个专业技巧解决umi.js文件过大的加载缓慢问题下一篇如何快速掌握AssetRipperUnity资源提取工具的完整实战指南创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考