Short-Term Conversation Memory › Building a Conversational Agent
Michael BrenndoerferJuly 1, 20252 min read
AI Agent HandbookAll chapters Part 6 of 15Memory and Retrieval - How Agents Remember
Short-Term Conversation Memory › Building a Conversational AgentOne section · Sections in this chapter5 / 15 ↓
Sections in this chapter15
Let's create a more complete conversational agent that manages memory automatically:
In[7]:
Codeclass ConversationalAgent:
"""
A personal assistant that remembers the conversation.
"""
def __init__(self):
self.client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
self.conversation_history = []
def chat(self, user_message: str) -> str:
"""
Send a message and get a response, maintaining conversation history.
Args:
user_message: What the user wants to say
Returns:
The agent's response
"""
# Add user message to history
self.conversation_history.append({
"role": "user",
"content": user_message
})
# Get response with full context
response = self.client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=self.conversation_history
)
# Extract and store the response
assistant_message = response.content[0].text
self.conversation_history.append({
"role": "assistant",
"content": assistant_message
})
return assistant_message
def clear_history(self):
"""Start a fresh conversation."""
self.conversation_history = []
def get_history(self) -> list:
"""Get the current conversation history."""
return self.conversation_history.copy()Now we can have natural, multi-turn conversations:
In[8]:
Code## Create the agent
agent = ConversationalAgent()
## Have a conversation
print(agent.chat("I'm planning a trip to Japan."))
## "That sounds exciting! Japan is a wonderful destination..."
print(agent.chat("What's the best time of year to visit?"))
## "For Japan, the best times to visit are typically spring (March-May)
## for cherry blossoms, or autumn (September-November) for fall foliage..."
print(agent.chat("How long should I plan to stay?"))
## "For a first trip to Japan, I'd recommend at least 10-14 days..."
print(agent.chat("What cities should I include?"))
## "Based on your trip to Japan, I'd suggest including Tokyo, Kyoto,
## and possibly Osaka or Hiroshima..."Out[8]:
Console# How exciting! I'd be happy to help you plan your trip to Japan. To give you the best suggestions, it would be helpful to know more about your plans: - **When are you planning to go?** (Season can greatly affect your experience - cherry blossoms in spring, fall foliage, winter snow, summer festivals) - **How long** will you be visiting? - **What are your interests?** (temples/culture, food, nature, cities, anime/pop culture, hiking, etc.) - **First time to Japan** or returning? - **Which cities/regions** are you considering? In the meantime, here are some general tips: **Popular first-timer destinations:** - Tokyo (modern city life) - Kyoto (traditional culture, temples) - Osaka (food scene) - Hiroshima & Miyajima - Hakone or nearby Mt. Fuji areas **Practical considerations:** - JR Pass can save money if traveling between cities - Pocket WiFi or SIM card is very useful - IC cards (Suica/Pasmo) make transport easy - Learn a few basic Japanese phrases What aspects of your trip would you like help with?
# Best Times to Visit Japan The "best" time really depends on what you're looking for, but here's a breakdown: ## 🌸 **Spring (March-May) - Most Popular** **Pros:** - Cherry blossoms (late March-early April) - truly spectacular - Comfortable temperatures (15-20°C / 59-68°F) - Clear skies, low rainfall **Cons:** - Very crowded and expensive during sakura season - Book accommodations months in advance - Popular spots can feel overwhelming ## 🍁 **Autumn (September-November) - Also Peak Season** **Pros:** - Fall foliage (mid-November) is stunning - Pleasant weather (15-22°C / 59-72°F) - Comfortable for walking/sightseeing - Many festivals **Cons:** - Crowded, especially in Kyoto during koyo (leaf viewing) - Higher prices - Early September can still be hot/humid ## ❄️ **Winter (December-February) - Underrated** **Pros:** - Fewer tourists, lower prices - Excellent skiing in Hokkaido/Nagano - Beautiful snow scenery - Clear skies (especially in Tokyo) **Cons:** - Cold (0-10°C / 32-50°F) - Some attractions close - Shorter daylight hours ## ☀️ **Summer (June-August) - Least Recommended** **Pros:** - Vibrant festivals (fireworks, bon odori) - Summer hiking season in mountains - Lavender fields in Hokkaido **Cons:** - Hot and very humid (25-35°C / 77-95°F) - Rainy season in June-July - Typhoon season (Aug-Sept) - Can be uncomfortable for sightseeing ## My Recommendation: **Late March-April or November** for the best balance of weather and scenery, but be prepared for crowds. **Winter (Jan-Feb)** if you want a more budget-friendly, authentic experience. What type of experience appeals to you most?
# How Long to Stay in Japan Here's my breakdown based on different trip lengths: ## ⏱️ **Minimum: 7-10 Days** Best for first-timers with limited time - **Tokyo**: 3-4 days - **Kyoto**: 2-3 days - **Osaka**: 1-2 days - Day trip to Nara or Hakone This gives you a taste of modern Japan (Tokyo), traditional culture (Kyoto), and great food (Osaka). ## 👍 **Ideal: 2 Weeks (14 days)** The sweet spot for most visitors - **Tokyo**: 4-5 days (including day trips to Nikko, Kamakura, or Mt. Fuji area) - **Kyoto**: 3-4 days (including day trip to Nara) - **Osaka**: 2 days - **Hiroshima**: 1-2 days (including Miyajima island) - **Plus** one wild card: Takayama, Kanazawa, Hakone, or Nagano This allows you to experience diverse regions without feeling rushed. ## 🌟 **Extended: 3-4 Weeks** For thorough exploration - All of the above PLUS: - **Hokkaido** (Sapporo, Hakodate) - **Japanese Alps** region - **Okinawa** (tropical islands) - More rural/off-beaten-path areas - Time to slow down and absorb local life ## 💡 **My Recommendation:** **Aim for at least 10-14 days** if possible. Japan has: - Excellent public transportation (easy to cover ground) - Enough variety that you won't get bored - A learning curve (language, customs) that takes a few days to adjust to **Quality over quantity:** It's better to spend 3 days truly experiencing Kyoto than rushing through in 1 day to check it off a list. How much time do you have available for your trip?
# Essential Cities & Regions for Your Japan Itinerary Here's my guide organized by priority: ## 🎯 **The Classic "Golden Route" (Must-See for First-Timers)** ### **Tokyo** (4-5 days) - Modern metropolis, endless neighborhoods to explore - Shibuya, Shinjuku, Harajuku (urban energy) - Asakusa (traditional temples) - Akihabara (anime/electronics) - Tsukiji Outer Market (food) - **Day trips:** Mt. Fuji/Hakone, Nikko, Kamakura ### **Kyoto** (3-4 days) - Japan's cultural heart, 2,000+ temples - Fushimi Inari (iconic red torii gates) - Arashiyama bamboo grove - Kinkaku-ji (Golden Pavilion) - Gion district (geisha spotting) - **Easy day trip:** Nara (deer park, giant Buddha - do this!) ### **Osaka** (1-2 days) - Food capital of Japan - Street food in Dotonbori - Osaka Castle - More casual, fun vibe than Tokyo - Great nightlife ## 🔥 **Highly Recommended Add-Ons** ### **Hiroshima** (1-2 days) - Peace Memorial & Museum (moving experience) - **Miyajima Island** - one of Japan's most scenic spots (floating torii gate) ### **Hakone** (1-2 days) - Mt. Fuji views - Hot springs (onsen) - Art museums - Scenic nature - Easy from Tokyo ## 🌟 **If You Have Extra Time (Pick 1-2)** ### **Takayama & Shirakawa-go** - Traditional mountain villages - Preserved Edo-period streets - UNESCO World Heritage gassho-zukuri houses ### **Kanazawa** - Beautiful Kenrokuen Garden - Samurai & geisha districts - Excellent seafood - Less touristy alternative to Kyoto ### **Nara** - Can be a day trip from Kyoto/Osaka - Friendly deer roaming freely - Todai-ji Temple (massive Buddha) ### **Nagano** - Snow monkeys in hot springs - Mountain temples - Winter sports ### **Hokkaido** (Sapporo, Hakodate) - Northern island - very different feel - Best in winter (skiing, snow festival) or summer (lavender) - Needs 3-5 days minimum ### **Okinawa** - Tropical islands, beaches - Distinct Ryukyu culture - Requires flight, feels like different country ## 📋 **Sample Itineraries** ### **10 Days:** - Tokyo (4 days) → Hakone (1 day) → Kyoto (3 days, with Nara day trip) → Osaka (2 days) ### **14 Days:** - Tokyo (4 days) → Hakone (1 day) → Kyoto (3 days) → Nara (1 day) → Osaka (2 days) → Hiroshima/Miyajima (2 days) → back to Tokyo or add Takayama (1 day) ### **3 Weeks:** - All of the above + Kanazawa (2 days) + Nagano (2 days) + Hokkaido (4-5 days) OR Okinawa (3-4 days) ## 💡 **My Advice:** **Don't try to see everything!** Japan rewards depth over breadth. The classic Tokyo-Kyoto-Osaka triangle is perfect for a first visit. You can always return (and you'll want to!). **Geographic logic matters:** Plan your route to avoid backtracking. Generally flow: Tokyo → Central Japan → Kyoto/Osaka → Western Japan (Hiroshima). What's your trip length looking like? That will help me suggest the best combination!
Notice how each response builds on the previous context. The agent remembers we're discussing a Japan trip and tailors its answers accordingly.