import openai
# Set up your OpenAI API key (replace 'your-api-key' with your actual key securely)
openai.api_key = 'your-api-key'
def generate_response(prompt, temperature=0.7, max_tokens=150):
"""
Function to generate a response using OpenAI API with best practices for prompt engineering.
"""
try:
# Sending a request to OpenAI's GPT model
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=temperature,
max_tokens=max_tokens
)
# Extracting and returning the response text
return response['choices'][0]['message']['content'].strip()
except Exception as e:
return f"Error occurred: {e}"
# 1. Clear and Specific Prompt Example
prompt_1 = "Explain the process of photosynthesis in 100 words."
response_1 = generate_response(prompt_1)
print("Response for Prompt 1:\n", response_1)
# 2. Provide Context and Structure
prompt_2 = "List the steps involved in writing a good research paper. Provide a detailed explanation for each step in bullet points."
response_2 = generate_response(prompt_2)
print("\nResponse for Prompt 2:\n", response_2)
# 3. Using Constraints (Word Count and Format)
prompt_3 = "Describe artificial intelligence in 50 words or less. Keep the tone formal and precise."
response_3 = generate_response(prompt_3, temperature=0.5, max_tokens=60)
print("\nResponse for Prompt 3:\n", response_3)
# 4. Experiment with Variations of Phrasing
prompt_4 = "What are the benefits of machine learning in healthcare?"
response_4 = generate_response(prompt_4)
print("\nResponse for Prompt 4:\n", response_4)
prompt_5 = "How is machine learning transforming the healthcare industry?"
response_5 = generate_response(prompt_5)
print("\nResponse for Prompt 5:\n", response_5)
# 5. Few-Shot Learning Example (Provide Examples)
prompt_6 = """
Translate the following English sentences to Spanish:
1. "How are you?" -> "¿Cómo estás?"
2. "Good morning!" -> "¡Buenos días!"
Now, translate: "Where is the nearest hospital?"
"""
response_6 = generate_response(prompt_6, temperature=0.3, max_tokens=60)
print("\nResponse for Prompt 6:\n", response_6)
# 6. Testing Temperature and Max Tokens
prompt_7 = "Write a creative and imaginative story about a lost astronaut."
response_7 = generate_response(prompt_7, temperature=0.9, max_tokens=200)
print("\nResponse for Prompt 7 (Creative Story):\n", response_7)
prompt_8 = "Write a concise description of the process of photosynthesis."
response_8 = generate_response(prompt_8, temperature=0.3, max_tokens=60)
print("\nResponse for Prompt 8 (Concise Description):\n", response_8)