当前位置: 首页 > news >正文

使用 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 模型的示例。代码读入一个图像文件,使用文本提示和图像字节创建消息有效负载,然后打印出模型对场景的描述。另外,在这段代码中如果要使用不同的图像进行测试,只需更新输入文件路径即可。

输入图片为两张照片,如下所示。这是我在撰写这篇技术文章时,从窗户拍摄出去的香港铜锣湾的美丽街景照:

image.png

Causeway Bay Street View, Hong Kong (Image 1)

image.png

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 模型中获得以下输出结果:

image.png

为了读者阅读的方便,我在此处复制了这个模型的输出结果:

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 模型中获得了以下输出结果:

image.png

为了读者阅读的方便,我在此处同样复制了这个模型的输出结果:

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: 表格列组件&#xff0c;定义每列的展示内容和属性 --><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&#xff1a;else if range语句&#xff1a; continue continue的作用是&#xff1a; 中断所在循环的当次执行&#xff0c;直接进入下一次 continue在嵌套循环中的应用 break 直接结束所在的循环 break在嵌套循环中的应用 continue和break&#xff0c;在…...

Java - Mysql数据类型对应

Mysql数据类型java数据类型备注整型INT/INTEGERint / java.lang.Integer–BIGINTlong/java.lang.Long–––浮点型FLOATfloat/java.lang.FloatDOUBLEdouble/java.lang.Double–DECIMAL/NUMERICjava.math.BigDecimal字符串型CHARjava.lang.String固定长度字符串VARCHARjava.lang…...

linux 下常用变更-8

1、删除普通用户 查询用户初始UID和GIDls -l /home/ ###家目录中查看UID cat /etc/group ###此文件查看GID删除用户1.编辑文件 /etc/passwd 找到对应的行&#xff0c;YW343:x:0:0::/home/YW343:/bin/bash 2.将标红的位置修改为用户对应初始UID和GID&#xff1a; YW3…...

零基础设计模式——行为型模式 - 责任链模式

第四部分&#xff1a;行为型模式 - 责任链模式 (Chain of Responsibility Pattern) 欢迎来到行为型模式的学习&#xff01;行为型模式关注对象之间的职责分配、算法封装和对象间的交互。我们将学习的第一个行为型模式是责任链模式。 核心思想&#xff1a;使多个对象都有机会处…...

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别 直接训练提示词嵌入向量的核心区别 您提到的代码: prompt_embedding = initial_embedding.clone().requires_grad_(True) optimizer = torch.optim.Adam([prompt_embedding...

IP如何挑?2025年海外专线IP如何购买?

你花了时间和预算买了IP&#xff0c;结果IP质量不佳&#xff0c;项目效率低下不说&#xff0c;还可能带来莫名的网络问题&#xff0c;是不是太闹心了&#xff1f;尤其是在面对海外专线IP时&#xff0c;到底怎么才能买到适合自己的呢&#xff1f;所以&#xff0c;挑IP绝对是个技…...

Java求职者面试指南:计算机基础与源码原理深度解析

Java求职者面试指南&#xff1a;计算机基础与源码原理深度解析 第一轮提问&#xff1a;基础概念问题 1. 请解释什么是进程和线程的区别&#xff1f; 面试官&#xff1a;进程是程序的一次执行过程&#xff0c;是系统进行资源分配和调度的基本单位&#xff1b;而线程是进程中的…...

二维FDTD算法仿真

二维FDTD算法仿真&#xff0c;并带完全匹配层&#xff0c;输入波形为高斯波、平面波 FDTD_二维/FDTD.zip , 6075 FDTD_二维/FDTD_31.m , 1029 FDTD_二维/FDTD_32.m , 2806 FDTD_二维/FDTD_33.m , 3782 FDTD_二维/FDTD_34.m , 4182 FDTD_二维/FDTD_35.m , 4793...

Mac flutter环境搭建

一、下载flutter sdk 制作 Android 应用 | Flutter 中文文档 - Flutter 中文开发者网站 - Flutter 1、查看mac电脑处理器选择sdk 2、解压 unzip ~/Downloads/flutter_macos_arm64_3.32.2-stable.zip \ -d ~/development/ 3、添加环境变量 命令行打开配置环境变量文件 ope…...

写一个shell脚本,把局域网内,把能ping通的IP和不能ping通的IP分类,并保存到两个文本文件里

写一个shell脚本&#xff0c;把局域网内&#xff0c;把能ping通的IP和不能ping通的IP分类&#xff0c;并保存到两个文本文件里 脚本1 #!/bin/bash #定义变量 ip10.1.1 #循环去ping主机的IP for ((i1;i<10;i)) doping -c1 $ip.$i &>/dev/null[ $? -eq 0 ] &&am…...

表单设计器拖拽对象时添加属性

背景&#xff1a;因为项目需要。自写设计器。遇到的坑在此记录 使用的拖拽组件时vuedraggable。下面放上局部示例截图。 坑1。draggable标签在拖拽时可以获取到被拖拽的对象属性定义 要使用 :clone, 而不是clone。我想应该是因为draggable标签比较特。另外在使用**:clone时要将…...