技术分享 | 使用 Amazon Bedrock 学习提示词工程系列分享(五)转换类提示词

Python
JSON
Amazon Bedrock
0
0
> 本文内容是上一篇《使用 [Amazon Bedrock](https://aws.amazon.com/cn/bedrock/?trk=cndc-detail) 学习提示词工程系列分享(四)推理类提示词》的延续,同样基于deeplearning.ai 的《ChatGPT Prompt Engineering for Developers》课程整理而来。 ### 代码 课程中的代码使用的是 OpenAI 的 GPT-3.5-turbo 模型, 在我们的例子中将替换为在 [Amazon Bedrock](https://aws.amazon.com/cn/bedrock/?trk=cndc-detail) 中托管的 Claude 3 Opus模型。 代码如下,您可以在 Notebook 中执行: ```js import boto3 import json bedrock = boto3.client(service_name='bedrock-runtime', region_name='us-west-2') model_id = "anthropic.claude-3-opus-20240229-v1:0" text = f""" """ prompt_data = f""" ```{text}``` """ response = bedrock.invoke_model( modelId=model_id, body=json.dumps( { "anthropic_version": "bedrock-2023-05-31", "max_tokens": 1024, "temperature": 0.1, "top_p": 0.9, "top_k": 200, "messages": [ { "role": "user", "content": [{"type": "text", "text": prompt_data}], } ], } ), ) # Process and print the response result = json.loads(response.get("body").read()) input_tokens = result["usage"]["input_tokens"] output_tokens = result["usage"]["output_tokens"] output_list = result.get("content", []) print("Invocation details:") print(f"- The input length is {input_tokens} tokens.") print(f"- The output length is {output_tokens} tokens.") print(f"- The model returned {len(output_list)} response(s):") print("\\n") for output in output_list: print(output["text"]) ``` ### 转换类提示词 大型语言模型在将输入转换为不同格式方面表现出色,例如接收一种语言的文本输入并将其转换或翻译成另一种语言,或者协助纠正拼写和语法错误,因此可以将存在语法缺陷的文本作为输入,让大语言模型帮助您进行修正,您可以通过这种方式对撰写的文章进行校对。甚至可以转换格式,如将 HTML 输入转换为 JSON 输出。 #### 1、文本翻译 首先,我们将执行一项翻译任务。大型语言模型是在来自多个来源(其中很大一部分是互联网)的大量文本数据上训练的,这些文本数据自然包含多种不同的语言。这种训练方式赋予了模型翻译的能力。这些模型能够以不同的熟练程度处理数百种语言。因此,我们将通过一些示例来展示如何利用这一能力。 第一个例子是将英文文本翻译成西班牙语。 ```js Translate the following English text to Spanish: ```Hi, I would like to order a blender``` ``` **Claude 3 Opus 输出:** ```js Here is the English text translated to Spanish: Hola, me gustaría pedir una licuadora. ``` **识别语言类型:** ```js Tell me which language this is: ```Combien coûte le lampadaire?``` ``` **Claude 3 Opus 输出:** ```js The language used in the given sentence is French. The sentence "Combien coûte le lampadaire?" translates to English as "How much does the lamp post cost?" ``` 大模型还能够同时进行多种语言的翻译。在这个例子中,我们需要将以下文本翻译成法语、西班牙语以及一种夸张的英语方言---海盗英语。待翻译的文本是:"I want to order a basketball。" ```js Translate the following text to French and Spanish and English pirate: ```I want to order a basketball``` ``` 模型生成了法语、西班牙语和海盗英语三个版本的译文。 ```js Here are the translations of "I want to order a basketball": French: Je veux commander un ballon de basket. Spanish: Quiero pedir una pelota de baloncesto. English pirate: Aye, I be wantin' to order meself a basketball, matey! ``` 在某些语言中,翻译的结果可能会因说话者与听话者之间的关系而有所不同。我们可以向大语言模型解释这一点,从而让它能够相应地进行翻译。在这个例子中,我们要求模型将文本翻译成西班牙语,并以正式和非正式两种形式呈现。此外,请注意这里我们使用了与反引号不同的分隔符。只要能够清晰地分隔,使用什么符号并不重要。 **提示词:** ```js Translate the following text to Spanish in both the formal and informal forms: 'Would you like to order a pillow?' ``` **Claude 3 Opus 输出:** 在示例的翻译结果中,我们得到了正式和非正式两种表达方式,并且 Opus 还对两种语气的区别进行了说明。 ```js Here are the Spanish translations of "Would you like to order a pillow?" in both formal and informal forms: Formal: ¿Le gustaría pedir una almohada? Informal: ¿Te gustaría pedir una almohada? The difference is that the formal version uses the pronoun "Le" while the informal uses "Te". "Le" is the formal "you" used to show respect, while "Te" is the informal "you" used with friends, family, or close acquaintances. ``` #### 2、通用翻译器 设想您是一家大型跨国电商企业的 IT 主管。全球各地的用户正在以他们的母语向您反馈 IT 问题。您的员工来自世界各地,并且只会讲各自的母语。在这种情况下,您需要一个通用翻译系统。下面是来自世界各地的用户的反馈内容,我们把这些内容放到一个列表里: ```js user_messages = [ "La performance du système est plus lente que d’habitude.", "Mi monitor tiene píxeles que no se iluminan.", "Il mio mouse non funziona", "Mój klawisz Ctrl jest zepsuty", "我的屏幕在闪烁" ] ``` **然后在程序里循环输出翻译结果:** ```js import boto3 import json bedrock = boto3.client(service_name='bedrock-runtime', region_name='us-west-2') model_id = "anthropic.claude-3-opus-20240229-v1:0" user_messages = [ "La performance du système est plus lente que d’habitude.", "Mi monitor tiene píxeles que no se iluminan.", "Il mio mouse non funziona", "Mój klawisz Ctrl jest zepsuty", "我的屏幕在闪烁" ] for issue in user_messages: prompt_data = f"Translate the following centence to English without other information: {issue}" response = bedrock.invoke_model( modelId=model_id, body=json.dumps( { "anthropic_version": "bedrock-2023-05-31", "max_tokens": 102400, "temperature": 0.1, "top_p": 0.9, "top_k": 200, "messages": [ { "role": "user", "content": [{"type": "text", "text": prompt_data}], } ], } ), ) result = json.loads(response.get("body").read()) output_list = result.get("content", []) for output in output_list: print(output["text"]) ``` **输出结果:** ```js The system performance is slower than usual. My monitor has pixels that don't light up. My mouse is not working. My Ctrl key is broken. My screen is flickering. ``` #### 3、语调转换 接下来,我们将探讨语气转换(tone transformation),例如,给同事或教授写电子邮件的方式,显然和给弟弟发短信的方式大不相同。大语言模型可以帮助进行语气转换,这种能力使得自然语言处理系统能够根据目标受众,自动调整生成文本的语气和风格。 下面的例子是将俚语翻译成商务书信。 ```js prompt_data = """ Translate the following from slang to a business letter: 'Dude, This is Joe, check out this spec on this standing lamp.' """ ``` **Claude 3 Opus 输出:** ```js Here is the business letter version: Dear Sir or Madam, I hope this letter finds you well. My name is Joe and I am writing to bring your attention to the specifications of one of our standing lamps. Please find the details enclosed for your review. If you have any questions or would like to discuss this lamp model further, please do not hesitate to contact me. Thank you for your time and consideration. Sincerely, Joe ``` #### 4、格式转换 大语言模型在转换不同格式方面表现出色,例如 JSON 到 HTML、XML,以及各种其他格式如 Markdown 等。下面是一个例子。我们有一个 JSON,其中包含了餐厅员工的姓名和电子邮件列表。然后在提示词中要求模型将这个 JSON 转换为 HTML 格式。 **json 格式的数据:** ```js json_data = { "resturant employees": [ {"name": "Shyam", "email": "shyamjaiswal@gmail.com"}, {"name": "Bob", "email": "bob32@gmail.com"}, {"name": "Jai", "email": "jai87@gmail.com"} ] } ``` 下面的提示词要求将上面的 Python 字典从 JSON 格式转换为包含列标题的 HTML 表格。 ```js prompt_data = """ Translate the following object from JSON to an HTML table with column headers and title: {data_json} """ ``` Claude 3 Opus 输出了一段转化之后的 HTML 代码,展示了所有员工的姓名和电子邮件地址,并且对关键步骤进行了说明。 ```js Here is the JSON object translated into an HTML table with column headers and a title: <table> <thead> <tr> <th colspan="2">Employee Information</th> </tr> <tr> <th>Name</th> <th>Age</th> <th>Email</th> <th>Phone</th> </tr> </thead> <tbody> <tr> <td>John Smith</td> <td>35</td> <td>john.smith@example.com</td> <td>(123) 456-7890</td> </tr> </tbody> </table> The key steps: 1. Create a <table> element to contain the table 2. Add a <thead> section for the table header 3. The first header row spans both columns and contains the table title 4. The second header row lists out the column headers matching the JSON keys 5. Add a <tbody> section for the table body 6. Create a <tr> table row for the employee data 7. Add <td> cells for each data value, pulling the values from the JSON object Let me know if you have any other questions! ``` #### 5、语法拼写检查 接下来,我们要进行的是拼写和语法检查,这是大型语言模型的一种非常流行的用途,特别是当您在使用非母语工作的时候尤其有用。 下面将展示一些常见的语法和拼写问题示例,并说明如何使用大语言模型解决这些问题。首先,准备一组包含语法或拼写错误的句子。然后,遍历这些句子,并要求模型对其进行校对和纠正。接着,获取模型的响应并进行输出。通过这种方式,模型能够纠正所有的语法错误。 下面是一个包含错误的句子的列表: ```js user_messages = [ "The girl with the black and white puppies have a ball.", "Yolanda has her notebook", "Its going to be a long day. Does the car need it’s oil changed?", "Their goes my freedom. There going to bring they’re suitcases.", "Your going to need you’re notebook.", "That medicine effects my ability to sleep. Have you heard of the butterfly affect?", "This phrase is to cherck chatGPT for speling ability" ] ``` 下面是提示词,要求大模型在输出校对后的句子之前输出原来的句子等。您可以使用前面的循环代码对上面的列表进行循环处理。 ```js Proofread and correct the following text and rewrite the corrected version. Print the oringinal text and the corrected version, separated by one line break, whout other information. If you don't find and errors, just say "No errors found". Don't use any punctuation around the text: ```{issue}``` ``` 下面是程序输出结果,原来的句子在前,校对后的句子在后。您可以使用之前讨论过的一些技术来改进提示,比如尝试修改提示词,让大模型说明错误原因。通过迭代的提示词开发,您就能找到一种每次都能可靠运行的提示词。 ```js The girl with the black and white puppies have a ball. The girl with the black and white puppies has a ball. Here is the original text: Yolanda has her notebook No errors found. Its going to be a long day. Does the car need it's oil changed? It's going to be a long day. Does the car need its oil changed? Their goes my freedom. There going to bring they're suitcases. There goes my freedom. They're going to bring their suitcases. Your going to need you're notebook. You're going to need your notebook. That medicine effects my ability to sleep. Have you heard of the butterfly affect? That medicine affects my ability to sleep. Have you heard of the butterfly effect? This phrase is to cherck chatGPT for speling ability This phrase is to check ChatGPT for spelling ability ``` 在公开发布文章之前,对文章内容进行检查总是很有必要的。接下来,我们将通过一个评论的例子来演示如何进行文章检查。这里有一篇关于毛绒熊猫的评论,我们将使用大模型对其进行校对和修正。 下面是有语法错误的评论内容: ```js user_messages = f""" Got this for my daughter for her birthday cuz she keeps taking mine from my room. Yes, adults also like pandas too. She takes it everywhere with her, and it's super soft and cute. One of the ears is a bit lower than the other, and I don't think that was designed to be asymmetrical. It's a bit small for what I paid for it though. I think there might be other options that are bigger for the same price. It arrived a day earlier than expected, so I got to play with it myself before I gave it to my daughter. """ ``` 接下来是提示词: ```js prompt_data = f""" proofread and correct this review: ```{user_messages}``` """ ``` 下面是大模型输出的校对后的版本: ```js Here is the corrected review: I got this for my daughter's birthday because she keeps taking mine from my room. Yes, adults also like pandas too. She takes it everywhere with her, and it's super soft and cute. However, one of the ears is a bit lower than the other, and I don't think that was designed to be asymmetrical. Additionally, it's a bit small for what I paid for it. I think there might be other options that are bigger for the same price. On the positive side, it arrived a day earlier than expected, so I got to play with it myself before I gave it to my daughter. ``` 以上就是转换类提示词,您可以在 notebook 中运行并调整提示词让大语言模型输出想要的内容。通过精心设计和优化的提示词,可以有效引导模型生成高质量、符合需求的文本。像前面的文章提到的,提示词的设计是一个反复迭代的过程,需要根据实际输出结果不断调整和改进,才能最终得到理想的生成效果。
0
目录
关闭