使用 Amazon Bedrock Converse API 简化大语言模型交互
本文将介绍如何使用 Amazon Bedrock 最新推出的 Converse API,来简化与各种大型语言模型的交互。该 API 提供了一致的接口,可以无缝调用各种大型模型,从而消除了需要自己编写复杂辅助功能函数的重复性工作。文中示例将展示它相比于以前针对每个模型进行独立集成的方式,具有更简单的实现。文中还将提供完整代码,展示使用 Converse API 来调用 Claude 3 Sonnet 模型进行多模态图像描述。
亚马逊云科技开发者社区为开发者们提供全球的开发技术资源。这里有技术文档、开发案例、技术专栏、培训视频、活动与竞赛等。帮助中国开发者对接世界最前沿技术,观点,和项目,并将中国优秀开发者或技术推荐给全球云社区。如果你还没有关注/收藏,看到这里请一定不要匆匆划过,点这里让它成为你的技术宝库!
为了帮助开发者快速理解新的 Converse API,我对比了在 Converse API 发布之前,开发者是如何用代码实现调用多个大模型,并集成到统一接口的示例。通过 Converse API 示例代码,我将展示 Converse API 是如何轻松完成简化统一多模型交互接口的工作。最后,我还会重点分享如何使用 Converse API 调用 Claude 3 Sonnet 模型,分析两张在美丽的中国香港拍摄的街景照片。
本文选自我于 2024 年 6 月,在 Amazon Web Services 开发者社区上发表的技术博客“Streaming Large Language Model Interactions with Amazon Bedrock Converse API”。
Converse API 之前的世界
过去,开发人员必须编写复杂的辅助函数,来统一应付不同大语言模型之前不同的的输入和输出格式。例如,在 2024 年 5 月初的亚马逊云科技香港峰会中,为了在一个文件中使用 Amazon Bedrock 调用 5-6 个不同的大语言模型,我需要编写总共 116 行代码来实现这个统一接口的功能。
我当时是使用 Python 语言来编写这个函数,其它语言实现也基本类似。在没有 Converse API 之前,开发者需要自己编写辅助函数,调用 Amazon Bedrock 中来自不同提供商(Anthropic、Mistral、AI21、Amazon、Cohere 和 Meta 等)的不同大型语言模型。
以下我的代码中的“invoke_model”函数接受提示词、模型名,以及各种参数配置(例如:温度、top-k、top-p 和停止序列等),最终得到来自指定语言模型生成的输出文本。
我之前需要编写的辅助函数代码中,需要考虑来自不同模型提供商的提示词格式要求,然后才能发送针对某些特定模型的指定输入数据和提示词结构。代码如下所示:
import json
import boto3def invoke_model(client, prompt, model, accept = 'application/json', content_type = 'application/json',max_tokens = 512, temperature = 1.0, top_p = 1.0, top_k = 200, stop_sequences = [],count_penalty = 0, presence_penalty = 0, frequency_penalty = 0, return_likelihoods = 'NONE'):# default responseoutput = ''# identify the model providerprovider = model.split('.')[0] # InvokeModelif (provider == 'anthropic'): input = {'prompt': prompt,'max_tokens_to_sample': max_tokens, 'temperature': temperature,'top_k': top_k,'top_p': top_p,'stop_sequences': stop_sequences}body=json.dumps(input)response = client.invoke_model(body=body, modelId=model, accept=accept,contentType=content_type)response_body = json.loads(response.get('body').read())output = response_body['completion']elif (provider == 'mistral'): input = {'prompt': prompt,'max_tokens': max_tokens,'temperature': temperature,'top_k': top_k,'top_p': top_p,'stop': stop_sequences}body=json.dumps(input)response = client.invoke_model(body=body, modelId=model, accept=accept,contentType=content_type)response_body = json.loads(response.get('body').read())results = response_body['outputs']for result in results:output = output + result['text'] elif (provider == 'ai21'): input = {'prompt': prompt, 'maxTokens': max_tokens,'temperature': temperature,'topP': top_p,'stopSequences': stop_sequences,'countPenalty': {'scale': count_penalty},'presencePenalty': {'scale': presence_penalty},'frequencyPenalty': {'scale': frequency_penalty}}body=json.dumps(input)response = client.invoke_model(body=body, modelId=model, accept=accept,contentType=content_type)response_body = json.loads(response.get('body').read())completions = response_body['completions']for part in completions:output = output + part['data']['text']elif (provider == 'amazon'): input = {'inputText': prompt,'textGenerationConfig': {'maxTokenCount': max_tokens,'stopSequences': stop_sequences,'temperature': temperature,'topP': top_p}}body=json.dumps(input)response = client.invoke_model(body=body, modelId=model, accept=accept,contentType=content_type)response_body = json.loads(response.get('body').read())results = response_body['results']for result in results:output = output + result['outputText']elif (provider == 'cohere'): input = {'prompt': prompt, 'max_tokens': max_tokens,'temperature': temperature,'k': top_k,'p': top_p,'stop_sequences': stop_sequences,'return_likelihoods': return_likelihoods}body=json.dumps(input)response = client.invoke_model(body=body, modelId=model, accept=accept,contentType=content_type)response_body = json.loads(response.get('body').read())results = response_body['generations']for result in results:output = output + result['text']elif (provider == 'meta'): input = {'prompt': prompt,'max_gen_len': max_tokens,'temperature': temperature,'top_p': top_p}body=json.dumps(input)response = client.invoke_model(body=body, modelId=model, accept=accept,contentType=content_type)response_body = json.loads(response.get('body').read())output = response_body['generation']# returnreturn output# main function
bedrock = boto3.client(service_name='bedrock-runtime'
)
model = 'mistral.mistral-7b-instruct-v0:2'
prompt = """Human: Explain how chicken swim to an 8 year old using 2 paragraphs.Assistant:
"""
output = invoke_model(client=bedrock, prompt=prompt, model=model)
print(output)
以上代码行数仅展示了针对这几个模型的接口函数实现,随着需要统一调用的不同大型模型越来越多,代码量还会不断增长。完整代码如下所示:https://catalog.us-east-1.prod.workshops.aws/workshops/5501fb48-e04b-476d-89b0-43a7ecaf1595/en-US/full-day-event-fm-and-embedding/fm/03-making-things-simpler?trk=cndc-detail
使用 Converse API 的世界
以下来自亚马逊云科技官方网站的代码片段,展示了使用 Amazon Bedrock Converse API 调用大型语言模型的简易性:
def generate_conversation(bedrock_client,model_id,system_text,input_text):……# Send the message.response = bedrock_client.converse(modelId=model_id,messages=messages,system=system_prompts,inferenceConfig=inference_config,additionalModelRequestFields=additional_model_fields)……
完整代码可以参考以下链接:https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html#message-inference-examples?trk=cndc-detail
为了提供给开发者们一个使用 Converse API 调用大模型的完整代码示例,特设计以下这个香港铜锣湾街景的大模型描述任务。
代码示例中,主要使用 converse() 方法将文本和图像发送到 Claude 3 Sonnet 模型的示例。代码读入一个图像文件,使用文本提示和图像字节创建消息有效负载,然后打印出模型对场景的描述。另外,在这段代码中如果要使用不同的图像进行测试,只需更新输入文件路径即可。
输入图片为两张照片,如下所示。这是我在撰写这篇技术文章时,从窗户拍摄出去的香港铜锣湾的美丽街景照:
Causeway Bay Street View, Hong Kong (Image 1)
Causeway Bay Street View, Hong Kong (Image 2)
在核心代码部分,我根据前面提到的亚马逊云科技官方网站提供的示例代码,稍做修改编写了一个新的 generate_conversation_with_image() 函数,并在 main() 主函数的合适位置调用这个函数。完整代码如下所示:
def generate_conversation_with_image(bedrock_client,model_id,input_text,input_image):"""Sends a message to a model.Args:bedrock_client: The Boto3 Bedrock runtime client.model_id (str): The model ID to use.input text : The input message.input_image : The input image.Returns:response (JSON): The conversation that the model generated."""logger.info("Generating message with model %s", model_id)# Message to send.with open(input_image, "rb") as f:image = f.read()message = {"role": "user","content": [{"text": input_text},{"image": {"format": 'png',"source": {"bytes": image}}}]}messages = [message]# Send the message.response = bedrock_client.converse(modelId=model_id,messages=messages)return responsedef main():"""Entrypoint for Anthropic Claude 3 Sonnet example."""logging.basicConfig(level=logging.INFO,format="%(levelname)s: %(message)s")model_id = "anthropic.claude-3-sonnet-20240229-v1:0"input_text = "What's in this image?"input_image = "IMG_1_Haowen.jpg"try:bedrock_client = boto3.client(service_name="bedrock-runtime")response = generate_conversation_with_image(bedrock_client, model_id, input_text, input_image)output_message = response['output']['message']print(f"Role: {output_message['role']}")for content in output_message['content']:print(f"Text: {content['text']}")token_usage = response['usage']print(f"Input tokens: {token_usage['inputTokens']}")print(f"Output tokens: {token_usage['outputTokens']}")print(f"Total tokens: {token_usage['totalTokens']}")print(f"Stop reason: {response['stopReason']}")except ClientError as err:message = err.response['Error']['Message']logger.error("A client error occurred: %s", message)print(f"A client error occured: {message}")else:print(f"Finished generating text with model {model_id}.")if __name__ == "__main__":main()
对于铜锣湾街景照片之一,我从 Claude 3 Sonnet 模型中获得以下输出结果:
为了读者阅读的方便,我在此处复制了这个模型的输出结果:
Role: assistant
Text: This image shows a dense urban cityscape with numerous high-rise residential and office buildings in Hong Kong. In the foreground, there are sports facilities like a running track, soccer/football fields, and tennis/basketball courts surrounded by the towering skyscrapers of the city. The sports venues provide open green spaces amidst the densely packed urban environment. The scene captures the juxtaposition of modern city living and recreational amenities in a major metropolitan area like Hong Kong.
Input tokens: 1580
Output tokens: 103
Total tokens: 1683
Stop reason: end_turn
Finished generating text with model anthropic.claude-3-sonnet-20240229-v1:0.
对于铜锣湾街景照片之二,我只是简单地将代码中的 input_image 路径修改为新的图像路径。当我将该照片作为新图像输入到 Claude 3 Sonnet 模型时,我从 Claude 3 Sonnet 模型中获得了以下输出结果:
为了读者阅读的方便,我在此处同样复制了这个模型的输出结果:
Role: assistant
Text: This image shows an aerial view of a dense urban city skyline, likely in a major metropolitan area. The cityscape is dominated by tall skyscrapers and high-rise apartment or office buildings of varying architectural styles, indicating a highly developed and populous city center.In the foreground, a major highway or expressway can be seen cutting through the city, with multiple lanes of traffic visible, though the traffic appears relatively light in this particular view. There are also some pockets of greenery interspersed among the buildings, such as parks or green spaces.One notable feature is a large billboard or advertisement for the luxury brand Chanel prominently displayed on the side of a building, suggesting this is a commercial and shopping district.Overall, the image captures the concentrated urban density, modern infrastructure, and mixture of residential, commercial, and transportation elements characteristic of a major cosmopolitan city.
Input tokens: 1580
Output tokens: 188
Total tokens: 1768
Stop reason: end_turn
Finished generating text with model anthropic.claude-3-sonnet-20240229-v1:0.
小结
Amazon Bedrock 的新 Converse API 通过提供一致的接口,简化了与大型语言模型之间的不同交互,而无需针对于特定模型编写特定的实现。传统方式下,开发人员需要编写包含数百行代码的复杂辅助函数,以统一各个模型的输入/输出格式。Converse API 允许使用相同的 API 无缝调用各种大语言模型,从而大大降低了代码复杂度。
本文的代码示例展示了 Converse API 的简洁性,而过去的方法需要针对每个模型提供者进行独特的集成。第二个代码示例重点介绍了通过 Converse API 调用 Claude 3 Sonnet 模型进行图像描述。
总体而言,Converse API 简化了在 Amazon Bedrock 中使用不同的大型语言模型的交互过程,通过一致性的界面大幅减少了开发工作量,让生成式 AI 应用的开发者可以更加专注于基于自己业务的独特创新和想象力。
说明:本博客文章的封面图像由在 Amazon Bedrock 上的 Stable Diffusion SDXL 1.0 大模型生成。
提供给 Stable Diffusion SDXL 1.0 大模型的英文提示词如下,供参考:
“a developer sitting in the cafe, comic, graphic illustration, comic art, graphic novel art, vibrant, highly detailed, colored, 2d minimalistic”
文章来源:使用 Amazon Bedrock Converse API 简化大语言模型交互
相关文章:

使用 Amazon Bedrock Converse API 简化大语言模型交互
本文将介绍如何使用 Amazon Bedrock 最新推出的 Converse API,来简化与各种大型语言模型的交互。该 API 提供了一致的接口,可以无缝调用各种大型模型,从而消除了需要自己编写复杂辅助功能函数的重复性工作。文中示例将展示它相比于以前针对每…...
第二十一章 函数(Python)
文章目录 前言一、定义函数二、函数参数三、参数类型四、函数返回值五、函数类型1、无参数,无返回值2、无参数,有返回值3、有参数,无返回值4、有参数,有返回值 六、函数的嵌套七、全局变量和局部变量1、局部变量2、全局变量 前言 …...

使用pyqt5编写一个七彩时钟
使用pyqt5编写一个七彩时钟 效果代码解析定义 RainbowClockWindow 类初始化用户界面显示时间方法 完整代码 在这篇博客中,我们将使用 PyQt5 创建一个简单的七彩数字时钟。 效果 代码解析 定义 RainbowClockWindow 类 class RainbowClockWindow(QMainWindow):def _…...

【Linux】:命令行参数
朋友们、伙计们,我们又见面了,本期来给大家解读一下有关Linux命令行参数的相关知识点,如果看完之后对你有一定的启发,那么请留下你的三连,祝大家心想事成! C 语 言 专 栏:C语言:从入…...

高考假期预习指南,送给迷茫的你
高考结束,离别了熟悉的地方,踏上远方。 你,,迷茫吗? 大学是什么?到了大学我该怎样学习?真像网上说的毕业即失业吗? 大学是一个让你学会一技之长的地方,到了大学找到自…...
独孤思维:负债了,还可以翻身吗
01 其实独孤早年也负债。 负债并不可怕。 可怕的是因为负债而催生的想要快速赚钱的心态。 越是有这种心态,越是不可能赚到钱。 相反,可能会让你陷入恶性循环中。 盲目付费,盲目寄希望于某个项目或者某个人。 当成唯一的救命稻草。 这…...

SwiftUI八与UIKIT交互
代码下载 SwiftUI可以在苹果全平台上无缝兼容现有的UI框架。例如,可以在SwiftUI视图中嵌入UIKit视图或UIKit视图控制器,反过来在UIKit视图或UIKit视图控制器中也可以嵌入SwiftUI视图。 本文展示如何把landmark应用的主页混合使用UIPageViewController和…...

RedHat9 | 内部YUM本地源服务器搭建
服务器参数 标识公司内部YUM服务器主机名yum-server网络信息192.168.37.1/24网络属性静态地址主要操作用户root 一、基础环境信息配置 修改主机名 [rootyum-server ~]# hostnamectl hostname yum-server添加网络信息 [rootyum-server ~]# nmcli connection modify ens160 …...

无偏归一化自适应心电ECG信号降噪方法(MATLAB)
心电信号作为一种生物信号,含有大量的临床应用价值的信息,在现代生命医学研究中占有重要的地位。但心电信号低频、低幅值的特点,使其在采集和传输的过程中经常受到噪声的干扰,使心电波形严重失真,从而影响后续的病情分…...

AI基本概念(人工智能、机器学习、深度学习)
人工智能 、 机器学习、 深度学习的概念和关系 人工智能 (Artificial Intelligence)AI- 机器展现出人类智慧机器学习 (Machine Learning) ML, 达到人工智能的方法深度学习 (Deep Learning)DL,执行机器学习的技术 从范围…...

LabVIEW幅频特性测试系统
使用LabVIEW软件开发的幅频特性测试系统。该系统整合了Agilent 83732B信号源与Agilent 8563EC频谱仪,通过LabVIEW编程实现自动控制和数据处理,提供了成本效益高、操作简便的解决方案,有效替代了昂贵的专用仪器,提高了测试效率和设…...

校园卡手机卡怎么注销?
校园手机卡的注销流程可以根据不同的运营商和具体情况有所不同,但一般来说,以下是注销校园手机卡的几种常见方式,我将以分点的方式详细解释: 一、线上注销(通过手机APP或官方网站) 下载并打开对应运营商的…...
logback自定义规则脱敏
自定义规则conversionRule public class LogabckMessageConverter extends MessageConverter {Overridepublic String convert(ILoggingEvent event) {String msg event.getMessage();if ("INFO".equals(event.getLevel().toString())) {msg .....脱敏实现}return …...

高效批量复制与覆盖:一键实现文件管理,轻松应对同名文件,简化工作流程
在数字时代,我们每天都在与海量的文件和数据打交道。你是否曾经遇到过这样的情况:需要批量复制文件到指定文件夹,但一遇到同名文件就头疼不已,要么手动一个个确认覆盖,要么冒着数据丢失的风险直接操作?别担…...

vue3中使用Antv G6渲染树形结构并支持节点增删改
写在前面 在一些管理系统中,会对组织架构、级联数据等做一些管理,你会怎么实现呢?在经过调研很多插件之后决定使用 Antv G6 实现,文档也比较清晰,看看怎么实现吧,先来看看效果图。点击在线体验 实现的功能…...

【PB案例学习笔记】-26制作一个带浮动图标的工具栏
写在前面 这是PB案例学习笔记系列文章的第26篇,该系列文章适合具有一定PB基础的读者。 通过一个个由浅入深的编程实战案例学习,提高编程技巧,以保证小伙伴们能应付公司的各种开发需求。 文章中设计到的源码,小凡都上传到了gite…...

反向沙箱技术:安全隔离上网
在信息化建设不断深化的今天,业务系统的安全性和稳定性成为各公司和相关部门关注的焦点。面对日益复杂的网络威胁,传统的安全防护手段已难以满足需求。深信达反向沙箱技术,以其独特的设计和强大的功能,成为保障政务系统信息安全的…...
前端在for循环中使用Element-plus el-select中的@click.native动态传参
<el-table ref"table" :data"editTableVariables" cell-dblclick"handleRowDblClick" style"width: 100%" > <!-- el-table-column: 表格列组件,定义每列的展示内容和属性 --><el-table-column prop&q…...
Oracle SQL - CONNECT BY语句Where条件中不能使用OR?[已解决]
数据 SQL> SELECT * FROM demo_a;CUSTOMER TOTAL ---------- ---------- A 100200SQL> SELECT * FROM demo_b;CUSTOMER RN QTY ---------- ---------- ---------- A 1 30 A 2 …...

python-逻辑语句
if else语句 不同于C:else if range语句: continue continue的作用是: 中断所在循环的当次执行,直接进入下一次 continue在嵌套循环中的应用 break 直接结束所在的循环 break在嵌套循环中的应用 continue和break,在…...

[网页五子棋][用户模块]客户端开发(登录功能和注册功能)
文章目录 客户端开发登录功能htmlcsscommon.csslogin.css jQuery引入 jquery 运行程序注册功能 客户端开发 登录功能 html <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8"> <meta name"viewport&…...
【Python-Day 20】揭秘Python变量作用域:LEGB规则与global/nonlocal关键字详解
Langchain系列文章目录 01-玩转LangChain:从模型调用到Prompt模板与输出解析的完整指南 02-玩转 LangChain Memory 模块:四种记忆类型详解及应用场景全覆盖 03-全面掌握 LangChain:从核心链条构建到动态任务分配的实战指南 04-玩转 LangChai…...

Python 训练营打卡 Day 30-模块和库的导入
模块和库的导入 1.1标准导入 import mathprint("方式1: 使用 import math") print(f"圆周率π的值: {math.pi}") print(f"2的平方根: {math.sqrt(2)}\n") 1.2从库中导入特定项 from math import pi, sqrtprint("方式2:使用 f…...
CesiumInstancedMesh 实例
CesiumInstancedMesh 实例 import * as Cesium from cesium;// Three.js 风格的 InstancedMesh 类, https://threejs.org/docs/#api/en/objects/InstancedMesh export class CesiumInstancedMesh {/*** Creates an instance of InstancedMesh.** param {Cesium.Geometry} geom…...

2025年5月24号高项综合知识真题以及答案解析(第1批次)
2025年5月24号高项综合知识真题以及答案解析...

Python训练营打卡Day40
DAY 40 训练和测试的规范写法 知识点回顾: 1.彩色和灰度图片测试和训练的规范写法:封装在函数中 2.展平操作:除第一个维度batchsize外全部展平 3.dropout操作:训练阶段随机丢弃神经元,测试阶段eval模式关闭dropout 作…...
00 QEMU源码中文注释与架构讲解
QEMU源码中文注释与架构讲解 先占坑:等后续完善后再更新此文章 注释作者将狼才鲸创建日期2025-05-30更新日期NULL CSDN阅读地址:00 QEMU源码中文注释与架构讲解Gitee源码仓库地址:才鲸嵌入式/qemu 一、前言 参考网址 QEMU 源码目录简介qe…...
【Kubernetes】ubuntu20.04通过kubeadm + Docker安装k8s
Kubernetes v1.24集群安装配置步骤总结 一、环境准备 (一)系统要求 运行兼容deb/rpm的Linux操作系统(如Ubuntu或CentOS)的计算机,1台或多台。每台机器内存2GB以上,内存不足会限制应用运行。控制平面节点…...

OpenGL Chan视频学习-9 Index Buffers inOpenGL
bilibili视频链接: 【最好的OpenGL教程之一】https://www.bilibili.com/video/BV1MJ411u7Bc?p5&vd_source44b77bde056381262ee55e448b9b1973 函数网站: docs.gl 说明: 1.之后就不再单独整理网站具体函数了,网站直接翻译会…...
indel_snp_ssr_primer
indel标记使用 1.得到vcf文件 2.提取指定区域vcf文件并压缩构建索引 bcftools view -r <CHROM>:<START>-<END> input.vcf -o output.vcf bgzip -c all.filtered.indel.vcf > all.filtered.indel.vcf.gz tabix -p vcf all.filtered.indel.vcf.gz3.准备参…...