Chapter 02
basic prompt structures
Basic Prompt Structures Tutorial
Overview
This tutorial focuses on two fundamental types of prompt structures:
- Single-turn prompts
- Multi-turn prompts (conversations)
We'll use OpenAI's GPT model and LangChain to demonstrate these concepts.
Motivation
Understanding different prompt structures is crucial for effective communication with AI models. Single-turn prompts are useful for quick, straightforward queries, while multi-turn prompts enable more complex, context-aware interactions. Mastering these structures allows for more versatile and effective use of AI in various applications.
Key Components
- Single-turn Prompts: One-shot interactions with the language model.
- Multi-turn Prompts: Series of interactions that maintain context.
- Prompt Templates: Reusable structures for consistent prompting.
- Conversation Chains: Maintaining context across multiple interactions.
Method Details
We'll use a combination of OpenAI's API and LangChain library to demonstrate these prompt structures. The tutorial will include practical examples and comparisons of different prompt types.
Setup
First, let's import the necessary libraries and set up our environment.
import os
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from dotenv import load_dotenv
load_dotenv()
os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY') # OpenAI API key
# Initialize the language model
llm = ChatOpenAI(model="gpt-4o-mini")1. Single-turn Prompts
Single-turn prompts are one-shot interactions with the language model. They consist of a single input (prompt) and generate a single output (response).
single_turn_prompt = "What are the three primary colors?"
print(llm.invoke(single_turn_prompt).content)Output
The three primary colors are red, blue, and yellow. These colors cannot be created by mixing other colors together and are the foundation for creating a wide range of other colors through mixing. In the context of additive color mixing (like with light), the primary colors are red, green, and blue (RGB).
Now, let's use a PromptTemplate to create a more structured single-turn prompt:
structured_prompt = PromptTemplate(
input_variables=["topic"],
template="Provide a brief explanation of {topic} and list its three main components."
)
chain = structured_prompt | llm
print(chain.invoke({"topic": "color theory"}).content)Output
Color theory is a framework used to understand how colors interact, complement each other, and can be combined to create various visual effects. It is essential in fields such as art, design, and photography, helping artists and designers make informed choices about color usage to evoke emotions, communicate messages, and create harmony in their work. The three main components of color theory are: 1. **Color Wheel**: A circular diagram that shows the relationships between colors. It typically includes primary, secondary, and tertiary colors, providing a visual representation of how colors can be combined. 2. **Color Harmony**: The concept of combining colors in a pleasing way. It involves using color schemes such as complementary, analogous, and triadic to create balance and visual interest. 3. **Color Context**: This refers to how colors interact with one another and how they can change perception based on their surrounding colors. The same color can appear different depending on the colors next to it, which influences mood and interpretation.
2. Multi-turn Prompts (Conversations)
Multi-turn prompts involve a series of interactions with the language model, allowing for more complex and context-aware conversations.
conversation = ConversationChain(
llm=llm,
verbose=True,
memory=ConversationBufferMemory()
)
print(conversation.invoke(input="Hi, I'm learning about space. Can you tell me about planets?")["response"])
print(conversation.invoke(input="What's the largest planet in our solar system?")["response"])
print(conversation.invoke(input="How does its size compare to Earth?")["response"])Let's compare how single-turn and multi-turn prompts handle a series of related questions:
# Single-turn prompts
prompts = [
"What is the capital of France?",
"What is its population?",
"What is the city's most famous landmark?"
]
print("Single-turn responses:")
for prompt in prompts:
print(f"Q: {prompt}")
print(f"A: {llm.invoke(prompt).content}\n")
# Multi-turn prompts
print("Multi-turn responses:")
conversation = ConversationChain(llm=llm, memory=ConversationBufferMemory())
for prompt in prompts:
print(f"Q: {prompt}")
print(f"A: {conversation.invoke(input=prompt)['response']}\n")Conclusion
This tutorial has introduced you to the basics of single-turn and multi-turn prompt structures. We've seen how:
- Single-turn prompts are useful for quick, isolated queries.
- Multi-turn prompts maintain context across a conversation, allowing for more complex interactions.
- PromptTemplates can be used to create structured, reusable prompts.
- Conversation chains in LangChain help manage context in multi-turn interactions.
Understanding these different prompt structures allows you to choose the most appropriate approach for various tasks and create more effective interactions with AI language models.
