create_structured_chat_agent and integrate ConversationBufferMemory to maintain context over a multi-turn conversation.
Objectives
- Configure structured chat agents that accept multiple parameters and roles.
- Integrate memory buffer contexts to enable conversational chat history.
- Manage interactive shell input loops to query the bot.
Implementation Plan
Goal
Create a conversational ReAct agent with access to Wikipedia and Time tools, preserving chat memory context across interactions in a conversational loop.Sample Input
Sample Output
An interactive bot response answering the questions.Plan
- Define a tool function
search_wikipediathat fetches summaries using thewikipediaPython package. - Initialize tools mapping
TimeandWikipediato their respective helper functions. - Pull the JSON structured chat prompt template
hwchase17/structured-chat-agentfrom the hub. - Set up a
ConversationBufferMemoryobject configured to return message objects under the keychat_history. - Create the structured chat agent using
create_structured_chat_agentand construct anAgentExecutorwith memory. - Populate the initial assistant instructions and build an interactive chat loop that registers user input and agent responses.
Step-by-Step Implementation
Step 1: Define Tools
We define functions for searching Wikipedia (limiting results to two sentences) and getting the current system time.Step 2: Configure Memory and Structured Agent
We pull the prompt designed for structured chat models and initialize the conversation memory buffer.Step 3: Initialize Executor and Loop
We wrap the agent in the executor, set system instructions, and handle the interaction loop.Complete Combined Code
Below is the complete, consolidated Python script uniting all of the steps above:Practice & Exercises
To practice setting up chat agents with memory, open the interactive notebook:Practice & Exercises
Practice initializing structured chat agents and managing ConversationBufferMemory.💻 VS Code | 🚀 Colab | 📥 Download