使用 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 簡化大語言模型交互

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/38742.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/38742.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/38742.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

如何在Windows上使用Docker搭建PHP開發環境

前言 在本地搭建開發環境我好像沒幾年就要折騰一次,因為本地開發電腦使用的是windows,早些年的時候,用過很多類似WAMP之類的東西,但最終都有或多或少不滿意的地方,前兩年的時候,還折騰過WSL,但…

批量文件名修改軟件:一鍵解決同一編碼多型號文件分類與命名難題,高效管理文件

在數字化時代,圖片文件已經成為我們工作中不可或缺的一部分。然而,當面對成百上千個同一編碼下不同型號的圖片文件時,如何快速、準確地進行分類和命名,成為了許多職場人士頭疼的問題。現在,我們為您帶來了一款神奇的批…

MyBatisPlus 基礎數據表的增刪改查 入門 簡單查詢

MyBatisPlus MyBatisPlus(簡稱MP)是一個基于MyBatis的增強工具庫,簡化了MyBatis的開發,提供了很多實用的功能和特性,如自動生成SQL、通用CRUD操作、分頁插件、條件構造器、代碼生成器等。它不僅簡化了開發過程&#x…

2024海亮日記

寫在前面:長文預警 20240617 聽說要去海亮,不考(補考)期末考試,于是進行一個停課的辦理,第一次進入410,被逆天的配置和氣氛所震驚 發誓這回去HL一定要有好效果,于是制定了詳細的計…

golang 未指定類型interface{} 類型的 int類型數據json.Unmarshal 解碼后變成float64類型問題解決方法

golang內置的json反序列化方法,默認情況下對應 未指定類型interface{} 類型的的 int類型數據在經過Unmarshal解碼后 int類型的數據會變成 float64類型。 因為json里面默認將interface{}類型的int數據都當做float64來處理。 解決方法很簡單,就是使用自定…

優盤有盤符顯示0字節:故障解析與數據恢復策略

一、優盤有盤符顯示0字節現象描述 在使用優盤的過程中,我們有時會遇到一種令人困惑的情況:插入優盤后,電腦能正常識別到優盤的盤符,但當我們嘗試訪問其中的數據時,卻發現優盤的容量顯示為0字節,無法讀取或…

快速掌握MyBatis

MyBatis 是一個流行的 Java 持久層框架,它提供了一種半自動的 SQL 映射方式,使得開發者能夠更加靈活地編寫 SQL 語句,同時避免了傳統 JDBC 代碼的冗余和復雜性。下面進行簡要概述: MyBatis 快速掌握 核心概念:理解 My…

8.1 Firmware Update Process

8.1 Firmware Update Process 通過reset激活firmware 更新的過程: host發出firmare下載命令,將FW image下載到控制器。FW image可能有多個部分要下載,因此FW image 下載命令中指定正在下載的FW image的每個部分的偏移量。FW image 下載命令…

Sui創始團隊在競速環節中的快問快答

在Sui Basecamp活動期間,Sui區塊鏈的最初貢獻者在Oracle紅牛賽車模擬器上展示了他們的技術能力,在駕駛圈時回答了有關Sui的問題。 Evan Cheng(又名Revvin’ Evan)在解釋Mysticeti創下區塊鏈最終性記錄的同時保持著他的駕駛線路。…

Java | Leetcode Java題解之第200題島嶼數量

題目&#xff1a; 題解&#xff1a; class Solution {void dfs(char[][] grid, int r, int c) {int nr grid.length;int nc grid[0].length;if (r < 0 || c < 0 || r > nr || c > nc || grid[r][c] 0) {return;}grid[r][c] 0;dfs(grid, r - 1, c);dfs(grid, r…

go Channel原理 (三)

Channel 設計原理 不要通過共享內存的方式進行通信&#xff0c;而是應該通過通信的方式共享內存。 在主流編程語言中&#xff0c;多個線程傳遞數據的方式一般都是共享內存。 Go 可以使用共享內存加互斥鎖進行通信&#xff0c;同時也提供了一種不同的并發模型&#xff0c;即通…

【嵌入式——FreeRTOS】任務

【嵌入式——FreeRTOS】任務 任務創建和刪除動態方式創建任務靜態方式創建任務 刪除任務任務切換調度器任務切換流程 任務掛起任務恢復相關API函數 任務創建和刪除 動態方式創建任務 任務的任務控制塊以及任務的棧空間所需的內存&#xff0c;均由freeRTOS從freeRTOS管理的堆中…

c#asp.net中字典的使用

字典是一個鍵值對&#xff0c;可以用來保存數據&#xff0c;再查詢&#xff1b; 下面是一個案例&#xff1a;依據多個學號查詢多個學生的姓名&#xff0c;只能到數據庫查詢一次數據&#xff01;&#xff01;&#xff01; 先在數據庫查詢學號對應的學生&#xff0c;把數據保存在…

mysql8.0.19安裝zip版本

下載地址https://downloads.mysql.com/archives/community/ 下載版本 下載后解壓&#xff0c;不包括data 和my.ini文件。其中data 文件是自動生成的【mysqld --initialize --console】&#xff0c;my.ini需要自己編寫設置。 新建my.ini文件 需要自己設置 basedirG:\soft\mysql…

內網服務器時間校正

新購買的云服務器發現內網機器和可以訪問外網的機器時間慢了三分鐘&#xff0c;導致有些訪問會報錯&#xff0c;那么我們配置一下ntp校正一下時間。外網配置起來比較簡單&#xff0c;直接下載ntp執行校正命令即可。 比當前時間慢了三分鐘 注意當前服務器是可以訪問外網的機器這…

【gitee使用教程】(創建項目倉庫并上傳代碼簡易版)

gitee使用教程&#xff0c;創建項目倉庫并上傳代碼簡易版 1.在碼云上創建一個倉庫2.將代碼克隆到本地1.復制倉庫地址2.找到你想要放置的文件位置&#xff0c;右鍵點擊更多選項&#xff0c;選擇Git Clone3.將復制的倉庫地址填入URL 3. IDEA結合GIT和Gitee的簡單使用idea需要識別…

【python】最新版抖音s逆向拿到數據,非常詳細教程(附完整代碼)

?? 歡迎大家來到景天科技苑?? ???? 養成好習慣,先贊后看哦~???? ?? 作者簡介:景天科技苑 ??《頭銜》:大廠架構師,華為云開發者社區專家博主,阿里云開發者社區專家博主,CSDN全棧領域優質創作者,掘金優秀博主,51CTO博客專家等。 ??《博客》:Python全…

Excel 宏錄制與VBA編程 ——VBA編程技巧篇一 (Union方法、Resize方法、Cells方法、UseSelect方法、With用法)

Uniom方法 使用Union方法可以將多個非連續區域連接起來成為一個區域&#xff0c;從而可以實現對多個非連續區域一起進行操作。 Resize方法 使用Range對象的Resize屬性調整指定區域的大小&#xff0c;并返回調整大小后的單元格區域。 Cells方法 Cells屬性返回一個Range對象。 Us…

Domino應用中的HTML5

大家好&#xff0c;才是真的好。 在xpages多年不見有效更新&#xff0c;前景不明的時候&#xff0c;Domino傳統Web應用開發方式還是受到了應有的青睞。畢竟&#xff0c;在Nomad Web時代&#xff0c;連最傳統的Notes CS原生應用也突然煥發了勃勃生機一樣。 但&#xff0c;對有…

什么是strcmp函數

目錄 開頭1.什么是strcmp函數2.strcmp函數里的內部結構3.strcmp函數的實際運用(這里只列舉其一)腦筋急轉彎 結尾 開頭 大家好&#xff0c;我叫這是我58。今天&#xff0c;我們要來認識一下C語言中的strcmp函數。 1.什么是strcmp函數 strcmp函數來自于C語言中的頭文件<str…