How to use persona prompting
Quick answer
Use
persona prompting by explicitly defining the AI's role, style, and knowledge scope in the prompt or system message to guide its responses. This technique improves output relevance and tone by setting clear expectations for the AI's behavior.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the openai Python package and set your API key as an environment variable for secure access.
pip install openai>=1.0 Step by step
Define a persona in the system message to instruct the AI on its role and style. Then send user queries to get persona-aligned responses.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
system_message = {
"role": "system",
"content": "You are a friendly and concise software engineer expert specializing in Python and AI."
}
user_message = {
"role": "user",
"content": "Explain persona prompting with an example."
}
response = client.chat.completions.create(
model="gpt-4o",
messages=[system_message, user_message]
)
print(response.choices[0].message.content) output
Persona prompting is a technique where you define the AI's role and style in the system message to guide its responses. For example, setting the persona as a friendly Python expert helps the AI provide concise, expert answers tailored to that role.
Common variations
You can use persona prompting with different models like claude-3-5-sonnet-20241022 or asynchronously. Adjust the persona tone or expertise level as needed.
import anthropic
import os
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system = "You are a formal and detailed AI assistant specialized in legal advice."
messages = [{"role": "user", "content": "What is persona prompting?"}]
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=300,
system=system,
messages=messages
)
print(response.content[0].text) output
Persona prompting is a method where the AI is instructed to adopt a specific role or style, such as a formal legal advisor, to provide responses that align with that persona's expertise and tone.
Troubleshooting
If the AI ignores the persona, ensure the persona instructions are clear and placed in the system message. Avoid conflicting instructions in user messages.
Key Takeaways
- Use the system message to define the AI's persona clearly and explicitly.
- Tailor persona details like tone, expertise, and style to improve response relevance.
- Persona prompting works across models like
gpt-4oandclaude-3-5-sonnet-20241022. - Avoid contradictory instructions in user messages that can confuse the persona.
- Test and iterate persona prompts to achieve consistent AI behavior.