Skip to main content
In this section, you will build an interactive structured chat agent using create_structured_chat_agent and integrate ConversationBufferMemory to maintain context over a multi-turn conversation.

Objectives

  1. Configure structured chat agents that accept multiple parameters and roles.
  2. Integrate memory buffer contexts to enable conversational chat history.
  3. 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

  1. Define a tool function search_wikipedia that fetches summaries using the wikipedia Python package.
  2. Initialize tools mapping Time and Wikipedia to their respective helper functions.
  3. Pull the JSON structured chat prompt template hwchase17/structured-chat-agent from the hub.
  4. Set up a ConversationBufferMemory object configured to return message objects under the key chat_history.
  5. Create the structured chat agent using create_structured_chat_agent and construct an AgentExecutor with memory.
  6. 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