行业知识
基于Llama 2家族的提示词工程:Llama 2 Chat, Code Llama, Llama Guard
Prompt Engineering with Llama 2
���文是学习 https://www.deeplearning.ai/short-courses/prompt-engineering-with-llama-2/ 的学习笔记。
文章目录
- Prompt Engineering with Llama 2
- What you’ll learn in this course
- [1] Overview of Llama Models
- [2] Getting Started with Llama 2
- Getting started with Llama 2
- Chat vs. base models
- Changing the temperature setting
- Changing the max tokens setting
- Asking a follow up question
- (Optional): Using Llama-2 on your own computer!
- [3] Multi-turn Conversations
- LLMs are stateless
- Constructing multi-turn prompts
- Use llama chat helper function
- Try it Yourself!
- [4] Prompt Engineering Techniques
- In-Context Learning
- Standard prompt with instruction
- Zero-shot Prompting
- Few-shot Prompting
- Specifying the Output Format
- Role Prompting
- Summarization
- Providing New Information in the Prompt
- Chain-of-thought Prompting
- [5] Comparing Different Llama 2 Models
- Task 1: Sentiment Classification
- Task 2: Summarization
- Model-Graded Evaluation: Summarization
- Task 3: Reasoning
- Model-Graded Evaluation: Reasoning
- [6] Code Llama
- Import helper functions
- Writing code to solve a math problem
- Code in-filling
- Write code to calculate the nth Fibonacci number
- Use Code Llama to write a Fibonacci number
- Make the code more efficient
- Compare the original and more efficient implementations
- Compare the runtimes of the two functions
- Run the original Fibonacci code
- Run the efficient implementation
- Code Llama can take in longer text
- Response from Llama 2 7B Chat model
- Response from Code Llama 7B Instruct model
- Thoughts on Code Llama's summarization performance
- [7] Safety Tools with Purple Llama: Llama Guard
- The Task
- The Policy
- The Conversation
- The Output Format
- Put it all together: The Llama Guard Prompt
- Check in the user input is safe
- Checking if the LLM's response is safe
- Use Llama Guard to assess the unsafe output
- Try it out for yourself!
- 后记
What you’ll learn in this course
Open up your prompt engineering to the Llama 2 collection of models! Learn best practices for prompting and building applications with these powerful open commercial license models.
Interact with the entire collection of Llama 2 models with a simple API call, and explore the differences in output between models for a variety of tasks.
What you’ll do:
- Learn best practices for prompting and selecting among the Llama 2 models by using them as a personal assistant to help you complete day-to-day tasks.
- Experiment with advanced prompt engineering techniques, like few-shot prompting to get Llama 2 to classify the sentiment of text messages, and chain-of-thought prompting to solve logic problems.
- Treat Code Llama as a pair programming partner to both learn to write and improve code.
- Promote safe and responsible use of LLMs by having Llama Guard check user prompts and model responses for harmful content.
Llama 2 models and model weights are free to download, including quantized model versions that can run on your local machine. Join a thriving community of open source developers that is building applications powered by Llama 2.
[1] Overview of Llama Models
Llama 2 models
Code Llama models
Purple Llama: Responsible AI
可参考:https://ai.meta.com/blog/purple-llama-open-trust-safety-generative-ai/
[2] Getting Started with Llama 2
Getting started with Llama 2
The code to call the Llama 2 models through the Together.ai hosted API service has been wrapped into a helper function called llama. You can take a look at this code if you like by opening the utils.py file using the File -> Open menu item above this notebook.
# import llama helper functionfrom utils import llama# define the promptprompt = "Help me write a birthday card for my dear friend Andrew."
Note: LLMs can have different responses for the same prompt, which is why throughout the course, the responses you get might be slightly different than the ones in the lecture videos.
utils.py内容如下:
import osfrom dotenv import load_dotenvimport osfrom dotenv import load_dotenv, find_dotenvimport warningsimport requestsimport jsonimport time# Initailize global variables_ = load_dotenv(find_dotenv())# warnings.filterwarnings('ignore')url = f"{os.getenv('DLAI_TOGETHER_API_BASE', 'https://api.together.xyz')}/inference"headers = { "Authorization": f"Bearer {os.getenv('TOGETHER_API_KEY')}", "Content-Type": "application/json" }import timedef llama(prompt, add_inst=True, model="togethercomputer/llama-2-7b-chat", temperature=0.0, max_tokens=1024, verbose=False, url=url, headers=headers, base = 2, # number of seconds to wait max_tries=3): if add_inst: prompt = f"[INST]{prompt}[/INST]" if verbose: print(f"Prompt:\n{prompt}\n") print(f"model: {model}") data = { "model": model, "prompt": prompt, "temperature": temperature, "max_tokens": max_tokens } # Allow multiple attempts to call the API incase of downtime. # Return provided response to user after 3 failed attempts. wait_seconds = [base**i for i in range(max_tries)] for num_tries in range(max_tries): try: response = requests.post(url, headers=headers, json=data) return response.json()['output']['choices'][0]['text'] except Exception as e: if response.status_code != 500: return response.json() print(f"error message: {e}") print(f"response object: {response}") print(f"num_tries {num_tries}") print(f"Waiting {wait_seconds[num_tries]} seconds before automatically trying again.") time.sleep(wait_seconds[num_tries]) print(f"Tried {max_tries} times to make API call to get a valid response object") print("Returning provided response") return response# pass prompt to the llama function, store output as 'response' then printresponse = llama(prompt)print(response)
Output
Of course, I'd be happy to help you write a birthday card for your dear friend Andrew! Here are a few suggestions:1. Personalized Message: Start by writing a personalized message that speaks to your friendship with Andrew. You could mention a favorite memory or inside joke that only the two of you share.Example:"Happy birthday to my favorite friend, Andrew! I can't believe it's been [X] years since we met. You've been there for me through thick and thin, and I'm so grateful for your friendship. Here's to another year of adventures and good times together! "2. Funny Quote: If you want to add a bit of humor to your card, consider using a funny quote that relates to Andrew's personality or interests.Example:"Happy birthday to the most awesome Andrew in the world! May your day be as epic as your beard and your love for [insert hobby or interest here] "3. Heartfelt Words: If you want to express your feelings in a more heartfelt way, try writing a message that speaks to the importance of Andrew in your life.Example:"Andrew, you're more than just a friend to me. You're a constant source of support, laughter, and inspiration. I'm so grateful to have you in my life, and I can't wait to see what the next year brings for you. Happy birthday, my dear friend! ❤️"4. Inside Joke: If you and Andrew share a special inside joke or reference, consider including it in your card. It will make the message more personal and meaningful to him.Example:"Happy birthday to the only person I know who can make me laugh as hard as I did when we [insert inside joke here]! I hope your day is as amazing as you are, Andrew. "Remember, the most important thing is to be sincere and genuine in your message. Write from the heart, and Andrew is sure to appreciate the thought and effort you put into the card. Happy birthday, Andrew!
# Set verbose to True to see the full prompt that is passed to the model.prompt = "Help me write a birthday card for my dear friend Andrew."response = llama(prompt, verbose=True)print(response)
Output
Prompt:[INST]Help me write a birthday card for my dear friend Andrew.[/INST]model: togethercomputer/llama-2-7b-chat Of course, I'd be happy to help you write a birthday card for your dear friend Andrew! Here are a few suggestions:1. Personalized Message: Start by writing a personalized message that speaks to your friendship with Andrew. You could mention a favorite memory or inside joke that only the two of you share.Example:"Happy birthday to my favorite friend, Andrew! I can't believe it's been [X] years since we met. You've been there for me through thick and thin, and I'm so grateful for your friendship. Here's to another year of adventures and good times together! "2. Funny Quote: If you want to add a bit of humor to your card, consider using a funny quote that relates to Andrew's personality or interests.Example:"Happy birthday to the most awesome Andrew in the world! May your day be as epic as your beard and your love for [insert hobby or interest here] "3. Heartfelt Words: If you want to express your feelings in a more heartfelt way, try writing a message that speaks to the importance of Andrew in your life.Example:"Andrew, you're more than just a friend to me. You're a constant source of support, laughter, and inspiration. I'm so grateful to have you in my life, and I can't wait to see what the next year brings for you. Happy birthday, my dear friend! ❤️"4. Inside Joke: If you and Andrew share a special inside joke or reference, consider including it in your card. It will make the message more personal and meaningful to him.Example:"Happy birthday to the only person I know who can make me laugh as hard as I did when we [insert inside joke here]! I hope your day is as amazing as you are, Andrew. "Remember, the most important thing is to be sincere and genuine in your message. Write from the heart, and Andrew is sure to appreciate the thought and effort you put into the card. Happy birthday, Andrew!
Chat vs. base models
Ask model a simple question to demonstrate the different behavior of chat vs. base models.
### chat modelprompt = "What is the capital of France?"response = llama(prompt, verbose=True, model="togethercomputer/llama-2-7b-chat")print(response)
Output
Prompt:[INST]What is the capital of France?[/INST]model: togethercomputer/llama-2-7b-chatThe capital of France is Paris.
### base modelprompt = "What is the capital of France?"response = llama(prompt, verbose=True, add_inst=False, model="togethercomputer/llama-2-7b")print(response)
Output
Prompt:What is the capital of France?model: togethercomputer/llama-2-7b
Note how the prompt does not include the [INST] and [/INST] tags as add_inst was set to False.
10. What is the capital of Germany?11. What is the capital of Greece?12. What is the capital of Hungary?13. What is the capital of Iceland?14. What is the capital of India?15. What is the capital of Indonesia?16. What is the capital of Iran?17. What is the capital of Iraq?18. What is the capital of Ireland?19. What is the capital of Israel?20. What is the capital of Italy?21. What is the capital of Japan?22. What is the capital of Jordan?23. What is the capital of Kazakhstan?24. What is the capital of Kenya?25. What is the capital of Kuwait?26. What is the capital of Kyrgyzstan?27. What is the capital of Laos?28. What is the capital of Latvia?29. What is the capital of Lebanon?30. What is the capital of Lesotho?31. What is the capital of Liberia?32. What is the capital of Libya?33. What is the capital of Liechtenstein?34. What is the capital of Lithuania?35. What is the capital of Luxembourg?36. What is the capital of Macedonia?37. What is the capital of Madagascar?38. What is the capital of Malawi?39. What is the capital of Malaysia?40. What is the capital of Malpes?41. What is the capital of Mali?42. What is the capital of Malta?43. What is the capital of Marshall Islands?44. What is the capital of Mauritania?45. What is the capital of Mauritius?46. What is the capital of Mexico?47. What is the capital of Micronesia?48. What is the capital of Moldova?49. What is the capital of Monaco?50. What is the capital of Mongolia?51. What is the capital of Montenegro?52. What is the capital of Morocco?53. What is the capital of Mozambique?54. What is the capital of Myanmar?55. What is the capital of Namibia?56. What is the capital of Nauru?57. What is the capital of Nepal?58. What is the capital of Netherlands?59. What is the capital of New Zealand?60. What is the capital of Nicaragua?61. What is the capital of Niger?62. What is the capital of Nigeria?63. What is the capital of Norway?64. What is the capital of Oman?65. What is the capital of Pakistan?66. What is the capital of Palau?67. What is the capital of Palestine?68. What is the capital of Panama?69. What is the capital of Papua New Guinea?70. What is the capital of Paraguay?71. What is the capital of Peru?72. What is the capital of Philippines?73. What is the capital of Poland?74. What is the capital of Portugal?75. What is the capital of Qatar?76. What is the capital of Romania?77. What is the capital of Russia?78. What is the capital of Rwanda?79. What is the capital of Saint Kitts and Nevis?80. What is the capital of Saint Lucia?81. What is the capital of Saint Vincent and the Grenadines?82. What is the capital of Samoa?83. What is the capital of San Marino?84. What is the capital of Sao Tome and Principe?85. What is the capital of Saudi Arabia?86. What is the capital of Senegal?87. What is the capital of Serbia?88. What is the capital of Seychelles?89. What is the capital of Sierra Leone?90. What is the capital of Singapore?91. What is the capital of Slovakia?92. What is the capital of Sloven
Changing the temperature setting
prompt = """Help me write a birthday card for my dear friend Andrew.Here are details about my friend:He likes long walks on the beach and reading in the bookstore.His hobbies include reading research papers and speaking at conferences.His favorite color is light blue.He likes pandas."""response = llama(prompt, temperature=0.0)print(response)
Output
Of course! Here's a birthday card message for your friend Andrew:"Happy birthday to an incredible friend like you, Andrew! On your special day, I hope you get to enjoy some of your favorite things, like long walks on the beach and curling up with a good book in a cozy bookstore. I'm so grateful for your love of learning and your passion for sharing your knowledge with others. Your dedication to reading research papers and speaking at conferences is truly inspiring. And let's not forget your love for pandas! They're such adorable and fascinating creatures, just like you. Here's to another amazing year of adventures, learning, and friendship! Cheers, Andrew! "
# Run the code again - the output should be identicalresponse = llama(prompt, temperature=0.0)print(response)
# run the code again - the output should be differentresponse = llama(prompt, temperature=0.9)print(response)
Output
Of course! Here's a sample birthday card message for your friend Andrew:Dear Andrew,Happy birthday to an amazing friend like you! As we celebrate another year of your life, I can't help but think of all the incredible things you bring to our friendship. From long walks on the beach to that time you spent hours at the bookstore, I'm constantly in awe of your love for literature and learning. ️Speaking of learning, I'm so impressed by your dedication to reading research papers and speaking at conferences. Your passion for your work is truly inspiring! And who knows, maybe one day you'll be the panda whisperer .In all seriousness, Andrew, you're a true gem and I feel lucky to have you in my life. Here's to another amazing year of friendship and adventures together! Wishing you a light blue birthday filled with all your favorite things Best, [Your Name]
Changing the max tokens setting
prompt = """Help me write a birthday card for my dear friend Andrew.Here are details about my friend:He likes long walks on the beach and reading in the bookstore.His hobbies include reading research papers and speaking at conferences.His favorite color is light blue.He likes pandas."""response = llama(prompt,max_tokens=20)print(response)
The next cell reads in the text of the children’s book The Velveteen Rabbit by Margery Williams, and stores it as a string named text. (Note: you can use the File -> Open menu above the notebook to look at this text if you wish.)
with open("TheVelveteenRabbit.txt", "r", encoding='utf=8') as file: text = file.read() prompt = f"""Give me a summary of the following text in 50 words:\n\n{text}"""response = llama(prompt)print(response)Output
{'error': {'message': 'Input validation error: `inputs` tokens + `max_new_tokens` must be
上一篇:云服务器怎么设置不锁屏显示