In today’s world, multi-agent systems (MAS) are becoming increasingly popular due to their ability to handle complex tasks by distributing responsibilities across multiple intelligent agents. These agents can collaborate, validate, and provide accurate responses to user queries. In this blog post, we’ll explore how to build a multi-agent system that connects to MongoDB, retrieves data, answers user queries, and validates the responses.
We’ll create two types of agents:
- Query Agent : Responsible for fetching data from MongoDB based on user queries.
- Validation Agent : Ensures the response provided by the Query Agent is accurate and relevant to the user query.
Let’s dive into the implementation!
Prerequisites
Before we begin, ensure you have the following installed:
- Python 3.x
- MongoDB (running locally or accessible via a connection string)
- Required Python libraries:
pymongo
,langchain
(for agent logic), andflask
(for API interface).
You can install the required libraries using pip:
pip install pymongo langchain flask
Step 1: Setting Up MongoDB
First, let’s set up a simple MongoDB collection to store some sample data. For this example, we’ll use a collection named products
with documents representing product details.
Sample Data in MongoDB
[
{
"_id": "1",
"name": "Laptop",
"category": "Electronics",
"price": 1200,
"description": "A high-performance laptop with 16GB RAM and 512GB SSD."
},
{
"_id": "2",
"name": "Smartphone",
"category": "Electronics",
"price": 800,
"description": "A flagship smartphone with a 6.7-inch display and 128GB storage."
},
{
"_id": "3",
"name": "Coffee Maker",
"category": "Home Appliances",
"price": 150,
"description": "A programmable coffee maker with a built-in grinder."
}
]
You can insert this data into your MongoDB instance using the MongoDB shell or Compass.
Step 2: Building the Query Agent
The Query Agent will connect to MongoDB, retrieve data based on user queries, and pass the results to the Validation Agent.
Code for Query Agent
from pymongo import MongoClient
class QueryAgent:
def __init__(self, db_uri, db_name, collection_name):
self.client = MongoClient(db_uri)
self.db = self.client[db_name]
self.collection = self.db[collection_name]
def fetch_data(self, query):
"""
Fetch data from MongoDB based on the user query.
:param query: A dictionary representing the MongoDB query.
:return: List of matching documents.
"""
try:
results = list(self.collection.find(query))
return results
except Exception as e:
print(f"Error fetching data: {e}")
return []
Explanation
- The
QueryAgent
class initializes a connection to MongoDB using the provided URI, database name, and collection name. - The
fetch_data
method accepts a query (in dictionary format) and retrieves matching documents from the MongoDB collection.
Step 3: Building the Validation Agent
The Validation Agent ensures that the response provided by the Query Agent is accurate and relevant to the user query. It uses a simple heuristic to validate the response.
Code for Validation Agent
class ValidationAgent:
def validate_response(self, query, response):
"""
Validate the response against the user query.
:param query: The original user query.
:param response: The response from the Query Agent.
:return: Validated response or an error message.
"""
if not response:
return "No results found for your query."
# Simple validation: Check if the query keywords match the response
query_keywords = set(query.lower().split())
for item in response:
description = item.get("description", "").lower()
if any(keyword in description for keyword in query_keywords):
return item
return "The response does not match your query. Please refine your search."
Explanation
- The
ValidationAgent
class contains avalidate_response
method that checks if the response matches the user query. - It uses a simple heuristic: If any keyword from the query appears in the
description
field of the response, the response is considered valid.
Step 4: Integrating Agents with Flask API
Now, let’s integrate both agents into a Flask API so users can interact with the system via HTTP requests.
Code for Flask API
from flask import Flask, request, jsonify
app = Flask(__name__)
# Initialize agents
query_agent = QueryAgent(
db_uri="mongodb://localhost:27017/",
db_name="mydatabase",
collection_name="products"
)
validation_agent = ValidationAgent()
@app.route('/query', methods=['POST'])
def handle_query():
"""
Handle user queries and return validated responses.
"""
user_query = request.json.get("query", "")
if not user_query:
return jsonify({"error": "Query cannot be empty."}), 400
# Convert user query into a MongoDB query
query_keywords = user_query.lower().split()
mongo_query = {"$or": [{"description": {"$regex": keyword, "$options": "i"}} for keyword in query_keywords]}
# Fetch data using Query Agent
results = query_agent.fetch_data(mongo_query)
# Validate response using Validation Agent
validated_response = validation_agent.validate_response(user_query, results)
return jsonify(validated_response)
if __name__ == '__main__':
app.run(debug=True)
Explanation
- The Flask API exposes a
/query
endpoint where users can send POST requests with their queries. - The
handle_query
function processes the user query, converts it into a MongoDB query, fetches data using the Query Agent, and validates the response using the Validation Agent. - The validated response is returned to the user.
Step 5: Testing the System
You can test the system using curl
or Postman. Here’s an example using curl
:
curl -X POST http://127.0.0.1:5000/query \
-H "Content-Type: application/json" \
-d '{"query": "high-performance laptop"}'
Expected Response
If the query matches a document in the database, the API will return the validated response:
{
"_id": "1",
"name": "Laptop",
"category": "Electronics",
"price": 1200,
"description": "A high-performance laptop with 16GB RAM and 512GB SSD."
}
If no match is found, the API will return:
"No results found for your query."