This notebook demonstrates how to implement a custom storage backend for CrewAI's memory system using Couchbase and vector search. Here's a breakdown of each section:
This tutorial is available as a Jupyter Notebook (.ipynb file) that you can run interactively. You can access the original notebook here.
You can either:
Create and Deploy Your Free Tier Operational cluster on Capella
Couchbase Capella Configuration When running Couchbase using Capella, the following prerequisites need to be met:
Memory in AI agents is a crucial capability that allows them to retain and utilize information across interactions, making them more effective and contextually aware. Without memory, agents would be limited to processing only the immediate input, lacking the ability to build upon past experiences or maintain continuity in conversations.
Note: This section on memory types and functionality is adapted from the CrewAI documentation.
Memory in AI agents typically involves:
In the CrewAI example, the CouchbaseStorage class implements:
In CrewAI, memory serves several important functions:
The vector-based approach (using embeddings) is particularly powerful because it allows for semantic search - finding memories that are conceptually related to the current context, not just exact keyword matches.
By implementing custom storage like Couchbase, you gain additional benefits like persistence, scalability, and the ability to leverage enterprise-grade database features for your agent memory systems.
This section installs the necessary Python packages:
crewai
: The main CrewAI frameworklangchain-couchbase
: LangChain integration for Couchbaselangchain-openai
: LangChain integration for OpenAIpython-dotenv
: For loading environment variables%pip install --quiet crewai==0.114.0 langchain-couchbase==0.3.0 langchain-openai==0.3.13 python-dotenv==1.1.0
Note: you may need to restart the kernel to use updated packages.
The script starts by importing a series of libraries required for various tasks, including handling JSON, logging, time tracking, Couchbase connections, embedding generation, and dataset loading.
from typing import Any, Dict, List, Optional
import os
import logging
from datetime import timedelta
from dotenv import load_dotenv
from crewai.memory.storage.rag_storage import RAGStorage
from crewai.memory.short_term.short_term_memory import ShortTermMemory
from crewai import Agent, Crew, Task, Process
from couchbase.cluster import Cluster
from couchbase.options import ClusterOptions
from couchbase.auth import PasswordAuthenticator
from couchbase.diagnostics import PingState, ServiceType
from langchain_couchbase.vectorstores import CouchbaseSearchVectorStore
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
import time
import json
import uuid
# Configure logging (disabled)
logging.basicConfig(level=logging.CRITICAL)
logger = logging.getLogger(__name__)
In this section, we prompt the user to input essential configuration settings needed. These settings include sensitive information like database credentials, and specific configuration names. Instead of hardcoding these details into the script, we request the user to provide them at runtime, ensuring flexibility and security.
The script uses environment variables to store sensitive information, enhancing the overall security and maintainability of your code by avoiding hardcoded values.
Note: This implementation reads configuration parameters from environment variables. Before running this notebook, you need to set the following environment variables:
OPENAI_API_KEY
: Your OpenAI API key for generating embeddingsCB_HOST
: Couchbase cluster connection string (e.g., "couchbases://cb.example.com")CB_USERNAME
: Username for Couchbase authenticationCB_PASSWORD
: Password for Couchbase authenticationCB_BUCKET_NAME
(optional): Bucket name (defaults to "vector-search-testing")SCOPE_NAME
(optional): Scope name (defaults to "shared")COLLECTION_NAME
(optional): Collection name (defaults to "crew")INDEX_NAME
(optional): Vector search index name (defaults to "vector_search_crew")You can set these variables in a
.env
file in the same directory as this notebook, or set them directly in your environment.
load_dotenv()
# Verify environment variables
required_vars = ['OPENAI_API_KEY', 'CB_HOST', 'CB_USERNAME', 'CB_PASSWORD']
for var in required_vars:
if not os.getenv(var):
raise ValueError(f"{var} environment variable is required")
This section demonstrates the implementation of a custom vector storage solution using Couchbase:
Note on Implementation: This example uses the LangChain Couchbase integration (
langchain_couchbase
) for simplicity and to demonstrate integration with the broader LangChain ecosystem. In production environments, you may want to use the Couchbase SDK directly for better performance and more control.
For more information on using the Couchbase SDK directly, refer to:
class CouchbaseStorage(RAGStorage):
"""
Extends RAGStorage to handle embeddings for memory entries using Couchbase.
"""
def __init__(self, type: str, allow_reset: bool = True, embedder_config: Optional[Dict[str, Any]] = None, crew: Optional[Any] = None):
"""Initialize CouchbaseStorage with configuration."""
super().__init__(type, allow_reset, embedder_config, crew)
self._initialize_app()
def search(
self,
query: str,
limit: int = 3,
filter: Optional[dict] = None,
score_threshold: float = 0,
) -> List[Dict[str, Any]]:
"""
Search memory entries using vector similarity.
"""
try:
# Add type filter
search_filter = {"memory_type": self.type}
if filter:
search_filter.update(filter)
# Execute search
results = self.vector_store.similarity_search_with_score(
query,
k=limit,
filter=search_filter
)
# Format results and deduplicate by content
seen_contents = set()
formatted_results = []
for i, (doc, score) in enumerate(results):
if score >= score_threshold:
content = doc.page_content
if content not in seen_contents:
seen_contents.add(content)
formatted_results.append({
"id": doc.metadata.get("memory_id", str(i)),
"metadata": doc.metadata,
"context": content,
"score": float(score)
})
logger.info(f"Found {len(formatted_results)} unique results for query: {query}")
return formatted_results
except Exception as e:
logger.error(f"Search failed: {str(e)}")
return []
def save(self, value: Any, metadata: Dict[str, Any]) -> None:
"""
Save a memory entry with metadata.
"""
try:
# Generate unique ID
memory_id = str(uuid.uuid4())
timestamp = int(time.time() * 1000)
# Prepare metadata (create a copy to avoid modifying references)
if not metadata:
metadata = {}
else:
metadata = metadata.copy() # Create a copy to avoid modifying references
# Process agent-specific information if present
agent_name = metadata.get('agent', 'unknown')
# Clean up value if it has the typical LLM response format
value_str = str(value)
if "Final Answer:" in value_str:
# Extract just the actual content - everything after "Final Answer:"
parts = value_str.split("Final Answer:", 1)
if len(parts) > 1:
value = parts[1].strip()
logger.info(f"Cleaned up response format for agent: {agent_name}")
elif value_str.startswith("Thought:"):
# Handle thought/final answer format
if "Final Answer:" in value_str:
parts = value_str.split("Final Answer:", 1)
if len(parts) > 1:
value = parts[1].strip()
logger.info(f"Cleaned up thought process format for agent: {agent_name}")
# Update metadata
metadata.update({
"memory_id": memory_id,
"memory_type": self.type,
"timestamp": timestamp,
"source": "crewai"
})
# Log memory information for debugging
value_preview = str(value)[:100] + "..." if len(str(value)) > 100 else str(value)
metadata_preview = {k: v for k, v in metadata.items() if k != "embedding"}
logger.info(f"Saving memory for Agent: {agent_name}")
logger.info(f"Memory value preview: {value_preview}")
logger.info(f"Memory metadata: {metadata_preview}")
# Convert value to string if needed
if isinstance(value, (dict, list)):
value = json.dumps(value)
elif not isinstance(value, str):
value = str(value)
# Save to vector store
self.vector_store.add_texts(
texts=[value],
metadatas=[metadata],
ids=[memory_id]
)
logger.info(f"Saved memory {memory_id}: {value[:100]}...")
except Exception as e:
logger.error(f"Save failed: {str(e)}")
raise
def reset(self) -> None:
"""Reset the memory storage if allowed."""
if not self.allow_reset:
return
try:
# Delete documents of this memory type
self.cluster.query(
f"DELETE FROM `{self.bucket_name}`.`{self.scope_name}`.`{self.collection_name}` WHERE memory_type = $type",
type=self.type
).execute()
logger.info(f"Reset memory type: {self.type}")
except Exception as e:
logger.error(f"Reset failed: {str(e)}")
raise
def _initialize_app(self):
"""Initialize Couchbase connection and vector store."""
try:
# Initialize embeddings
if self.embedder_config and self.embedder_config.get("provider") == "openai":
self.embeddings = OpenAIEmbeddings(
openai_api_key=os.getenv('OPENAI_API_KEY'),
model=self.embedder_config.get("config", {}).get("model", "text-embedding-3-small")
)
else:
self.embeddings = OpenAIEmbeddings(
openai_api_key=os.getenv('OPENAI_API_KEY'),
model="text-embedding-3-small"
)
# Connect to Couchbase
auth = PasswordAuthenticator(
os.getenv('CB_USERNAME', ''),
os.getenv('CB_PASSWORD', '')
)
options = ClusterOptions(auth)
# Initialize cluster connection
self.cluster = Cluster(os.getenv('CB_HOST', ''), options)
self.cluster.wait_until_ready(timedelta(seconds=5))
# Check search service
ping_result = self.cluster.ping()
search_available = False
for service_type, endpoints in ping_result.endpoints.items():
if service_type == ServiceType.Search:
for endpoint in endpoints:
if endpoint.state == PingState.OK:
search_available = True
logger.info(f"Search service is responding at: {endpoint.remote}")
break
break
if not search_available:
raise RuntimeError("Search/FTS service not found or not responding")
# Set up storage configuration
self.bucket_name = os.getenv('CB_BUCKET_NAME', 'vector-search-testing')
self.scope_name = os.getenv('SCOPE_NAME', 'shared')
self.collection_name = os.getenv('COLLECTION_NAME', 'crew')
self.index_name = os.getenv('INDEX_NAME', 'vector_search_crew')
# Initialize vector store
self.vector_store = CouchbaseSearchVectorStore(
cluster=self.cluster,
bucket_name=self.bucket_name,
scope_name=self.scope_name,
collection_name=self.collection_name,
embedding=self.embeddings,
index_name=self.index_name
)
logger.info(f"Initialized CouchbaseStorage for type: {self.type}")
except Exception as e:
logger.error(f"Initialization failed: {str(e)}")
raise
Test storing and retrieving a simple memory:
# Initialize storage
storage = CouchbaseStorage(
type="short_term",
embedder_config={
"provider": "openai",
"config": {"model": "text-embedding-3-small"}
}
)
# Reset storage
storage.reset()
# Test storage
test_memory = "Pep Guardiola praised Manchester City's current form, saying 'The team is playing well, we are in a good moment. The way we are training, the way we are playing - I am really pleased.'"
test_metadata = {"category": "sports", "test": "initial_memory"}
storage.save(test_memory, test_metadata)
# Test search
results = storage.search("What did Guardiola say about Manchester City?", limit=1)
for result in results:
print(f"Found: {result['context']}\nScore: {result['score']}\nMetadata: {result['metadata']}")
Found: Pep Guardiola has said Manchester City will be his final managerial job in club football before he "maybe" coaches a national team.
The former Barcelona and Bayern Munich boss has won 15 major trophies since taking charge of City in 2016.
The 53-year-old Spaniard was approached in the summer about the possibility of becoming England manager, but last month signed a two-year contract extension with City until 2027.
Speaking to celebrity chef Dani Garcia on YouTube, Guardiola did not indicate when he intends to step down at City but said he would not return to club football - in the Premier League or overseas.
"I'm not going to manage another team," he said.
"I'm not talking about the long-term future, but what I'm not going to do is leave Manchester City, go to another country, and do the same thing as now.
"I wouldn't have the energy. The thought of starting somewhere else, all the process of training and so on. No, no, no. Maybe a national team, but that's different.
"I want to leave it and go and play golf, but I can't [if he takes a club job]. I think stopping would do me good."
City have won just once since Guardiola extended his contract - and once in nine games since beating Southampton on 26 October.
That victory came at home to Nottingham Forest last Wednesday, but was followed by a 2-2 draw at Crystal Palace at the weekend.
The Blues visit Juventus next in the Champions League on Wednesday (20:00 GMT), before hosting Manchester United in the Premier League on Sunday (16:30).
"Right now we are not in the position - when we have had the results of the last seven, eight games - to talk about winning games in plural," said Guardiola at his pre-match news conference.
"We have to win the game and not look at what happens in the next one yet."
Score: 0.7207486629486084
Metadata: {}
Create agents and tasks to test memory retention:
# Initialize ShortTermMemory with our storage
memory = ShortTermMemory(storage=storage)
# Initialize language model
llm = ChatOpenAI(
model="gpt-4o",
temperature=0.7
)
# Create agents with memory
sports_analyst = Agent(
role='Sports Analyst',
goal='Analyze Manchester City performance',
backstory='Expert at analyzing football teams and providing insights on their performance',
llm=llm,
memory=True,
memory_storage=memory
)
journalist = Agent(
role='Sports Journalist',
goal='Create engaging football articles',
backstory='Experienced sports journalist who specializes in Premier League coverage',
llm=llm,
memory=True,
memory_storage=memory
)
# Create tasks
analysis_task = Task(
description='Analyze Manchester City\'s recent performance based on Pep Guardiola\'s comments: "The team is playing well, we are in a good moment. The way we are training, the way we are playing - I am really pleased."',
agent=sports_analyst,
expected_output="A comprehensive analysis of Manchester City's current form based on Guardiola's comments."
)
writing_task = Task(
description='Write a sports article about Manchester City\'s form using the analysis and Guardiola\'s comments.',
agent=journalist,
context=[analysis_task],
expected_output="An engaging sports article about Manchester City's current form and Guardiola's perspective."
)
# Create crew with memory
crew = Crew(
agents=[sports_analyst, journalist],
tasks=[analysis_task, writing_task],
process=Process.sequential,
memory=True,
short_term_memory=memory, # Explicitly pass our memory implementation
verbose=True
)
# Run the crew
result = crew.kickoff()
print("\nCrew Result:")
print("-" * 80)
print(result)
print("-" * 80)
╭──────────────────────────────────────────── Crew Execution Started ─────────────────────────────────────────────╮ │ │ │ Crew Execution Started │ │ Name: crew │ │ ID: 8246706c-6e28-4e21-8805-4b3985c3d811 │ │ │ │ │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
🚀 Crew: crew └── 📋 Task: 7dc4c834-1c24-4483-8e8b-58b49981c32d Status: Executing Task...
🚀 Crew: crew └── 📋 Task: 7dc4c834-1c24-4483-8e8b-58b49981c32d Status: Executing Task... └── 🤖 Agent: Sports Analyst Status: In Progress
# Agent: Sports Analyst
## Task: Analyze Manchester City's recent performance based on Pep Guardiola's comments: "The team is playing well, we are in a good moment. The way we are training, the way we are playing - I am really pleased."
🤖 Agent: Sports Analyst Status: In Progress └── 🧠 Thinking...
🤖 Agent: Sports Analyst Status: In Progress
# Agent: Sports Analyst
## Final Answer:
Based on Pep Guardiola's comments, Manchester City's recent performance can be described as a complex blend of challenges and optimism. Guardiola's assertion that "the team is playing well" and "we are in a good moment" highlights his satisfaction with the team's current training and playing style. However, the broader context reveals a more nuanced picture.
Guardiola's positive remarks come amid a challenging period for the team, marked by a significant downturn in results. Manchester City has experienced an unprecedented run of poor form, with nine losses in their past 12 matches. This stretch has been characterized by self-doubt, errors, and the need for significant changes within the squad. Despite these struggles, Guardiola maintains a positive outlook on the team's efforts and potential.
One of the critical issues facing the team is the absence of key midfielder Rodri, whose injury has severely impacted City's performance. The reliance on Rodri as a central figure in the team's strategy is akin to a Jenga tower losing a crucial piece, leading to a collapse in form. The injuries to other key players, such as Nathan Ake and Manuel Akanji, have compounded these challenges, leaving Guardiola with limited options in defense.
Guardiola's comments underscore his belief in the team's ability to turn things around, despite the current crisis. He has been protective of his players, refraining from public criticism and instead opting to give them time to reset and recover. This approach reflects his long-term vision for the club, as he plans to use the remaining years of his contract to rebuild and reshape the team.
The analysis of City's form within the club suggests that there have only been three matches where they deserved to lose, indicating that the team is not far off from regaining its competitive edge. However, the immediate goal has shifted to securing a top-four finish and restoring the defensive and offensive intensity that has been the hallmark of Guardiola's City.
Looking ahead, Guardiola and the club's management are preparing for a new era. This involves potential changes to the squad, with plans to replace several regular starters and bring in new talent, particularly in the holding midfielder position. The anticipated arrival of sporting director Hugo Viana and possible transfers, such as Spain's Martin Zubimendi, signal a strategic effort to revitalize the team.
In conclusion, while Guardiola's comments reflect his pleasure with the current training and playing style, the broader context reveals a team in transition. Manchester City is navigating a challenging period, but with Guardiola's leadership and forthcoming changes, there is optimism for a resurgence and a new chapter in the club's storied history.
🚀 Crew: crew └── 📋 Task: 7dc4c834-1c24-4483-8e8b-58b49981c32d Status: Executing Task... └── 🤖 Agent: Sports Analyst Status: ✅ Completed
🚀 Crew: crew └── 📋 Task: 7dc4c834-1c24-4483-8e8b-58b49981c32d Assigned to: Sports Analyst Status: ✅ Completed └── 🤖 Agent: Sports Analyst Status: ✅ Completed
╭──────────────────────────────────────────────── Task Completion ────────────────────────────────────────────────╮ │ │ │ Task Completed │ │ Name: 7dc4c834-1c24-4483-8e8b-58b49981c32d │ │ Agent: Sports Analyst │ │ │ │ │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
🚀 Crew: crew ├── 📋 Task: 7dc4c834-1c24-4483-8e8b-58b49981c32d │ Assigned to: Sports Analyst │ Status: ✅ Completed │ └── 🤖 Agent: Sports Analyst │ Status: ✅ Completed └── 📋 Task: f8a05679-fb2b-4379-8484-582aab6a99d0 Status: Executing Task...
🚀 Crew: crew ├── 📋 Task: 7dc4c834-1c24-4483-8e8b-58b49981c32d │ Assigned to: Sports Analyst │ Status: ✅ Completed │ └── 🤖 Agent: Sports Analyst │ Status: ✅ Completed └── 📋 Task: f8a05679-fb2b-4379-8484-582aab6a99d0 Status: Executing Task... └── 🤖 Agent: Sports Journalist Status: In Progress
# Agent: Sports Journalist
## Task: Write a sports article about Manchester City's form using the analysis and Guardiola's comments.
# Agent: Sports Journalist
## Final Answer:
**Manchester City: Navigating the Storm with Guardiola's Optimism and Strategic Vision**
In the annals of Premier League history, few teams have enjoyed the dominance that Manchester City has under the stewardship of Pep Guardiola. Yet, as the current season unfolds, the sky-blue juggernaut has encountered unforeseen turbulence. Guardiola's recent comments, however, reflect a blend of cautious optimism and a recognition of the challenges that lie ahead.
Guardiola, whose tactical genius has been the cornerstone of City's success, remains steadfast in his belief that "the team is playing well" and "we are in a good moment." Yet, these affirmations come during a period marked by an astonishing downturn in results. With nine losses in their last 12 matches, City finds itself in unfamiliar territory, grappling with self-doubt and uncharacteristic errors.
One cannot discuss City's recent struggles without acknowledging the absence of midfield maestro Rodri. His injury has been akin to pulling out a crucial Jenga piece, leading to a collapse in form that has left the team vulnerable. The injuries to key players such as Nathan Ake and Manuel Akanji have further exacerbated Guardiola's selection headaches, particularly in defense.
Guardiola's approach to this crisis, however, has been one of resilience and long-term planning. Rather than publicly chastising his players, he has opted for a protective stance, giving them the space to reset and recover. This reflects his vision not just for the immediate season but for the future of the club. With two years left on his contract, Guardiola is set on rebuilding and reshaping the squad, preparing for a new era at Manchester City.
The internal analysis at City suggests that only three of their recent defeats were thoroughly deserved, indicating that the team's competitive edge is not entirely lost. However, the immediate objective has shifted towards securing a top-four finish and reinstating the defensive and offensive intensity that has been synonymous with Guardiola's tenure.
Looking forward, changes are anticipated both in the squad and the club's management structure. The potential arrival of sporting director Hugo Viana and the pursuit of new talent, such as Spain's Martin Zubimendi, highlight a strategic effort to inject fresh energy and skills into the team. These moves are aimed at addressing specific weaknesses, particularly in the holding midfielder position.
In conclusion, while Manchester City is navigating a challenging period, Guardiola's comments and strategic vision offer a beacon of hope. His leadership, coupled with forthcoming squad changes, promises a resurgence and a new chapter in the club's illustrious history. The road ahead may be daunting, but with Guardiola at the helm, City supporters can remain hopeful of a return to the pinnacle of English football.
🚀 Crew: crew ├── 📋 Task: 7dc4c834-1c24-4483-8e8b-58b49981c32d │ Assigned to: Sports Analyst │ Status: ✅ Completed │ └── 🤖 Agent: Sports Analyst │ Status: ✅ Completed └── 📋 Task: f8a05679-fb2b-4379-8484-582aab6a99d0 Status: Executing Task... └── 🤖 Agent: Sports Journalist Status: ✅ Completed
🚀 Crew: crew ├── 📋 Task: 7dc4c834-1c24-4483-8e8b-58b49981c32d │ Assigned to: Sports Analyst │ Status: ✅ Completed │ └── 🤖 Agent: Sports Analyst │ Status: ✅ Completed └── 📋 Task: f8a05679-fb2b-4379-8484-582aab6a99d0 Assigned to: Sports Journalist Status: ✅ Completed └── 🤖 Agent: Sports Journalist Status: ✅ Completed
╭──────────────────────────────────────────────── Task Completion ────────────────────────────────────────────────╮ │ │ │ Task Completed │ │ Name: f8a05679-fb2b-4379-8484-582aab6a99d0 │ │ Agent: Sports Journalist │ │ │ │ │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────── Crew Completion ────────────────────────────────────────────────╮ │ │ │ Crew Execution Completed │ │ Name: crew │ │ ID: 8246706c-6e28-4e21-8805-4b3985c3d811 │ │ │ │ │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Crew Result:
--------------------------------------------------------------------------------
**Manchester City: Navigating the Storm with Guardiola's Optimism and Strategic Vision**
In the annals of Premier League history, few teams have enjoyed the dominance that Manchester City has under the stewardship of Pep Guardiola. Yet, as the current season unfolds, the sky-blue juggernaut has encountered unforeseen turbulence. Guardiola's recent comments, however, reflect a blend of cautious optimism and a recognition of the challenges that lie ahead.
Guardiola, whose tactical genius has been the cornerstone of City's success, remains steadfast in his belief that "the team is playing well" and "we are in a good moment." Yet, these affirmations come during a period marked by an astonishing downturn in results. With nine losses in their last 12 matches, City finds itself in unfamiliar territory, grappling with self-doubt and uncharacteristic errors.
One cannot discuss City's recent struggles without acknowledging the absence of midfield maestro Rodri. His injury has been akin to pulling out a crucial Jenga piece, leading to a collapse in form that has left the team vulnerable. The injuries to key players such as Nathan Ake and Manuel Akanji have further exacerbated Guardiola's selection headaches, particularly in defense.
Guardiola's approach to this crisis, however, has been one of resilience and long-term planning. Rather than publicly chastising his players, he has opted for a protective stance, giving them the space to reset and recover. This reflects his vision not just for the immediate season but for the future of the club. With two years left on his contract, Guardiola is set on rebuilding and reshaping the squad, preparing for a new era at Manchester City.
The internal analysis at City suggests that only three of their recent defeats were thoroughly deserved, indicating that the team's competitive edge is not entirely lost. However, the immediate objective has shifted towards securing a top-four finish and reinstating the defensive and offensive intensity that has been synonymous with Guardiola's tenure.
Looking forward, changes are anticipated both in the squad and the club's management structure. The potential arrival of sporting director Hugo Viana and the pursuit of new talent, such as Spain's Martin Zubimendi, highlight a strategic effort to inject fresh energy and skills into the team. These moves are aimed at addressing specific weaknesses, particularly in the holding midfielder position.
In conclusion, while Manchester City is navigating a challenging period, Guardiola's comments and strategic vision offer a beacon of hope. His leadership, coupled with forthcoming squad changes, promises a resurgence and a new chapter in the club's illustrious history. The road ahead may be daunting, but with Guardiola at the helm, City supporters can remain hopeful of a return to the pinnacle of English football.
--------------------------------------------------------------------------------
Query the stored memories to verify retention:
# Wait for memories to be stored
time.sleep(2)
# List all documents in the collection
try:
# Query to fetch all documents of this memory type
query_str = f"SELECT META().id, * FROM `{storage.bucket_name}`.`{storage.scope_name}`.`{storage.collection_name}` WHERE memory_type = $type"
query_result = storage.cluster.query(query_str, type=storage.type)
print(f"\nAll memory entries in Couchbase:")
print("-" * 80)
for i, row in enumerate(query_result, 1):
doc_id = row.get('id')
memory_id = row.get(storage.collection_name, {}).get('memory_id', 'unknown')
content = row.get(storage.collection_name, {}).get('text', '')[:100] + "..." # Truncate for readability
print(f"Entry {i}:")
print(f"ID: {doc_id}")
print(f"Memory ID: {memory_id}")
print(f"Content: {content}")
print("-" * 80)
except Exception as e:
print(f"Failed to list memory entries: {str(e)}")
# Test memory retention
memory_query = "What is Manchester City's current form according to Guardiola?"
memory_results = storage.search(
query=memory_query,
limit=5, # Increased to see more results
score_threshold=0.0 # Lower threshold to see all results
)
print("\nMemory Search Results:")
print("-" * 80)
for result in memory_results:
print(f"Context: {result['context']}")
print(f"Score: {result['score']}")
print("-" * 80)
# Try a more specific query to find agent interactions
interaction_query = "Manchester City playing style analysis tactical"
interaction_results = storage.search(
query=interaction_query,
limit=5,
score_threshold=0.0
)
print("\nAgent Interaction Memory Results:")
print("-" * 80)
for result in interaction_results:
print(f"Context: {result['context'][:200]}...") # Limit output size
print(f"Score: {result['score']}")
print("-" * 80)
All memory entries in Couchbase:
--------------------------------------------------------------------------------
Memory Search Results:
--------------------------------------------------------------------------------
Context: Based on Pep Guardiola's comments, Manchester City's recent performance can be described as a complex blend of challenges and optimism. Guardiola's assertion that "the team is playing well" and "we are in a good moment" highlights his satisfaction with the team's current training and playing style. However, the broader context reveals a more nuanced picture.
Guardiola's positive remarks come amid a challenging period for the team, marked by a significant downturn in results. Manchester City has experienced an unprecedented run of poor form, with nine losses in their past 12 matches. This stretch has been characterized by self-doubt, errors, and the need for significant changes within the squad. Despite these struggles, Guardiola maintains a positive outlook on the team's efforts and potential.
One of the critical issues facing the team is the absence of key midfielder Rodri, whose injury has severely impacted City's performance. The reliance on Rodri as a central figure in the team's strategy is akin to a Jenga tower losing a crucial piece, leading to a collapse in form. The injuries to other key players, such as Nathan Ake and Manuel Akanji, have compounded these challenges, leaving Guardiola with limited options in defense.
Guardiola's comments underscore his belief in the team's ability to turn things around, despite the current crisis. He has been protective of his players, refraining from public criticism and instead opting to give them time to reset and recover. This approach reflects his long-term vision for the club, as he plans to use the remaining years of his contract to rebuild and reshape the team.
The analysis of City's form within the club suggests that there have only been three matches where they deserved to lose, indicating that the team is not far off from regaining its competitive edge. However, the immediate goal has shifted to securing a top-four finish and restoring the defensive and offensive intensity that has been the hallmark of Guardiola's City.
Looking ahead, Guardiola and the club's management are preparing for a new era. This involves potential changes to the squad, with plans to replace several regular starters and bring in new talent, particularly in the holding midfielder position. The anticipated arrival of sporting director Hugo Viana and possible transfers, such as Spain's Martin Zubimendi, signal a strategic effort to revitalize the team.
In conclusion, while Guardiola's comments reflect his pleasure with the current training and playing style, the broader context reveals a team in transition. Manchester City is navigating a challenging period, but with Guardiola's leadership and forthcoming changes, there is optimism for a resurgence and a new chapter in the club's storied history.
Score: 0.7326797246932983
--------------------------------------------------------------------------------
Context: Pep Guardiola praised Manchester City's current form, saying 'The team is playing well, we are in a good moment. The way we are training, the way we are playing - I am really pleased.'
Score: 0.7146205306053162
--------------------------------------------------------------------------------
Context: **Manchester City: Navigating the Storm with Guardiola's Optimism and Strategic Vision**
In the annals of Premier League history, few teams have enjoyed the dominance that Manchester City has under the stewardship of Pep Guardiola. Yet, as the current season unfolds, the sky-blue juggernaut has encountered unforeseen turbulence. Guardiola's recent comments, however, reflect a blend of cautious optimism and a recognition of the challenges that lie ahead.
Guardiola, whose tactical genius has been the cornerstone of City's success, remains steadfast in his belief that "the team is playing well" and "we are in a good moment." Yet, these affirmations come during a period marked by an astonishing downturn in results. With nine losses in their last 12 matches, City finds itself in unfamiliar territory, grappling with self-doubt and uncharacteristic errors.
One cannot discuss City's recent struggles without acknowledging the absence of midfield maestro Rodri. His injury has been akin to pulling out a crucial Jenga piece, leading to a collapse in form that has left the team vulnerable. The injuries to key players such as Nathan Ake and Manuel Akanji have further exacerbated Guardiola's selection headaches, particularly in defense.
Guardiola's approach to this crisis, however, has been one of resilience and long-term planning. Rather than publicly chastising his players, he has opted for a protective stance, giving them the space to reset and recover. This reflects his vision not just for the immediate season but for the future of the club. With two years left on his contract, Guardiola is set on rebuilding and reshaping the squad, preparing for a new era at Manchester City.
The internal analysis at City suggests that only three of their recent defeats were thoroughly deserved, indicating that the team's competitive edge is not entirely lost. However, the immediate objective has shifted towards securing a top-four finish and reinstating the defensive and offensive intensity that has been synonymous with Guardiola's tenure.
Looking forward, changes are anticipated both in the squad and the club's management structure. The potential arrival of sporting director Hugo Viana and the pursuit of new talent, such as Spain's Martin Zubimendi, highlight a strategic effort to inject fresh energy and skills into the team. These moves are aimed at addressing specific weaknesses, particularly in the holding midfielder position.
In conclusion, while Manchester City is navigating a challenging period, Guardiola's comments and strategic vision offer a beacon of hope. His leadership, coupled with forthcoming squad changes, promises a resurgence and a new chapter in the club's illustrious history. The road ahead may be daunting, but with Guardiola at the helm, City supporters can remain hopeful of a return to the pinnacle of English football.
Score: 0.6574390530586243
--------------------------------------------------------------------------------
Context: Manchester City boss Pep Guardiola has won 18 trophies since he arrived at the club in 2016
Manchester City boss Pep Guardiola says he is "fine" despite admitting his sleep and diet are being affected by the worst run of results in his entire managerial career. In an interview with former Italy international Luca Toni for Amazon Prime Sport before Wednesday's Champions League defeat by Juventus, Guardiola touched on the personal impact City's sudden downturn in form has had. Guardiola said his state of mind was "ugly", that his sleep was "worse" and he was eating lighter as his digestion had suffered. City go into Sunday's derby against Manchester United at Etihad Stadium having won just one of their past 10 games. The Juventus loss means there is a chance they may not even secure a play-off spot in the Champions League. Asked to elaborate on his comments to Toni, Guardiola said: "I'm fine. "In our jobs we always want to do our best or the best as possible. When that doesn't happen you are more uncomfortable than when the situation is going well, always that happened. "In good moments I am happier but when I get to the next game I am still concerned about what I have to do. There is no human being that makes an activity and it doesn't matter how they do." Guardiola said City have to defend better and "avoid making mistakes at both ends". To emphasise his point, Guardiola referred back to the third game of City's current run, against a Sporting side managed by Ruben Amorim, who will be in the United dugout at the weekend. City dominated the first half in Lisbon, led thanks to Phil Foden's early effort and looked to be cruising. Instead, they conceded three times in 11 minutes either side of half-time as Sporting eventually ran out 4-1 winners. "I would like to play the game like we played in Lisbon on Sunday, believe me," said Guardiola, who is facing the prospect of only having three fit defenders for the derby as Nathan Ake and Manuel Akanji try to overcome injury concerns. If there is solace for City, it comes from the knowledge United are not exactly flying. Their comeback Europa League victory against Viktoria Plzen on Thursday was their third win of Amorim's short reign so far but only one of those successes has come in the Premier League, where United have lost their past two games against Arsenal and Nottingham Forest. Nevertheless, Guardiola can see improvements already on the red side of the city. "It's already there," he said. "You see all the patterns, the movements, the runners and the pace. He will do a good job at United, I'm pretty sure of that."
Guardiola says skipper Kyle Walker has been offered support by the club after the City defender highlighted the racial abuse he had received on social media in the wake of the Juventus trip. "It's unacceptable," he said. "Not because it's Kyle - for any human being. "Unfortunately it happens many times in the real world. It is not necessary to say he has the support of the entire club. It is completely unacceptable and we give our support to him."
Score: 0.6334313750267029
--------------------------------------------------------------------------------
Context: 'I am not good enough' - Guardiola faces daunting and major rebuild
This video can not be played To play this video you need to enable JavaScript in your browser. 'I am not good enough' - Guardiola says he must find a 'solution' after derby loss
Pep Guardiola says his sleep has suffered during Manchester City's deepening crisis, so he will not be helped by a nightmarish conclusion to one of the most stunning defeats of his long reign. Guardiola looked agitated, animated and on edge even after City led the Manchester derby through Josko Gvardiol's 36th-minute header, his reaction to the goal one of almost disdain that it came via a deflected cross as opposed to in his purist style. He sat alone with his eyes closed sipping from a water bottle before the resumption of the second half, then was denied even the respite of victory when Manchester United gave this largely dismal derby a dramatic conclusion it barely deserved with a remarkable late comeback. First, with 88 minutes on the clock, Matheus Nunes presented Amad Diallo with the ball before compounding his error by flattening the forward as he made an attempt to recover his mistake. Bruno Fernandes completed the formalities from the penalty spot. Worse was to come two minutes later when Lisandro Martinez's routine long ball caught City's defence inexplicably statuesque. Goalkeeper Ederson's positioning was awry, allowing the lively Diallo to pounce from an acute angle to leave Guardiola and his players stunned. It was the latest into any game, 88 minutes, that reigning Premier League champions had led then lost. It was also the first time City had lost a game they were leading so late on. And in a sign of City's previous excellence that is now being challenged, they have only lost four of 105 Premier League home games under Guardiola in which they have been ahead at half-time, winning 94 and drawing seven. Guardiola delivered a brutal self-analysis as he told Match of the Day: "I am not good enough. I am the boss. I am the manager. I have to find solutions and so far I haven't. That's the reality. "Not much else to say. No defence. Manchester United were incredibly persistent. We have not lost eight games in two seasons. We can't defend that."
Manchester City manager Pep Guardiola in despair during the derby defeat to Manchester United
Guardiola suggested the serious renewal will wait until the summer but the red flags have been appearing for weeks in the sudden and shocking decline of a team that has lost the aura of invincibility that left many opponents beaten before kick-off in previous years. He has had stated City must "survive" this season - whatever qualifies as survival for a club of such rich ambition - but the quest for a record fifth successive Premier League title is surely over as they lie nine points behind leaders Liverpool having played a game more. Their Champions League aspirations are also in jeopardy after another loss, this time against Juventus in Turin. City's squad has been allowed to grow too old together. The insatiable thirst for success seems to have gone, the scales of superiority have fallen away and opponents now sense vulnerability right until the final whistle, as United did here. The manner in which United were able, and felt able, to snatch this victory drove right to the heart of how City, and Guardiola, are allowing opponents to prey on their downfall. Guardiola has every reason to cite injuries, most significantly to Rodri and also John Stones as well as others, but this cannot be used an excuse for such a dramatic decline in standards, allied to the appearance of a soft underbelly that is so easily exploited. And City's rebuild will not be a quick fix. With every performance, every defeat, the scale of what lies in front of Guardiola becomes more obvious - and daunting. Manchester City's fans did their best to reassure Guardiola of their faith in him with a giant Barcelona-inspired banner draped from the stands before kick-off emblazoned with his image reading "Més que un entrenador" - "More Than A Coach". And Guardiola will now need to be more than a coach than at any time in his career. He will have the finances but it will be done with City's challengers also strengthening. Kevin de Bruyne, 34 in June, lasted 68 minutes here before he was substituted. Age and injuries are catching up with one of the greatest players of the Premier League era and he is unlikely to be at City next season. Mateo Kovacic, who replaced De Bruyne, is also 31 in May. Kyle Walker, 34, is being increasingly exposed. His most notable contribution here was an embarrassing collapse to the ground after the mildest head-to-head collision with Rasmus Hojlund. Ilkay Gundogan, another 34-year-old and a previous pillar of Guardiola's great successes, no longer has the legs or energy to exert influence. This looks increasingly like a season too far following his return from Barcelona. Flaws are also being exposed elsewhere, with previously reliable performers failing to hit previous standards. Phil Foden scored 27 goals and had 12 assists when he was Premier League Player of the Season last term. This year he has just three goals and two assists in 18 appearances in all competitions. He has no goals and just one assist in 11 Premier League games. Jack Grealish, who came on after 77 minutes against United, has not scored in a year for Manchester City, his last goal coming in a 2-2 draw against Crystal Palace on 16 December last year. He has, in the meantime, scored twice for England. Erling Haaland is also struggling as City lack creativity and cutting edge. He has three goals in his past 11 Premier League games after scoring 10 in his first five. And in another indication of City's impotence, and their reliance on Haaland, defender Gvardiol's goal against United was his fourth this season, making him their second highest scorer in all competitions behind the Norwegian striker, who has 18. Goalkeeper Ederson, so reliable for so long, has already been dropped once this season and did not cover himself in glory for United's winner. Guardiola, with that freshly signed two-year contract, insists he "wants it" as he treads on this alien territory of failure. He will be under no illusions about the size of the job in front of him as he placed his head in his hands in anguish after yet another damaging and deeply revealing defeat. City and Guardiola are in new, unforgiving territory.
Score: 0.6280660033226013
--------------------------------------------------------------------------------
Agent Interaction Memory Results:
--------------------------------------------------------------------------------
Context: Based on Pep Guardiola's comments, Manchester City's recent performance can be described as a complex blend of challenges and optimism. Guardiola's assertion that "the team is playing well" and "we ar...
Score: 0.6600019335746765
--------------------------------------------------------------------------------
Context: **Manchester City: Navigating the Storm with Guardiola's Optimism and Strategic Vision**
In the annals of Premier League history, few teams have enjoyed the dominance that Manchester City has under t...
Score: 0.6010371446609497
--------------------------------------------------------------------------------
Context: 'Self-doubt, errors & big changes' - inside the crisis at Man City
Pep Guardiola has not been through a moment like this in his managerial career. Manchester City have lost nine matches in their past...
Score: 0.5708299875259399
--------------------------------------------------------------------------------
Context: 'I am not good enough' - Guardiola faces daunting and major rebuild
This video can not be played To play this video you need to enable JavaScript in your browser. 'I am not good enough' - Guardiola s...
Score: 0.5522488355636597
--------------------------------------------------------------------------------
Context: Manchester City boss Pep Guardiola has won 18 trophies since he arrived at the club in 2016
Manchester City boss Pep Guardiola says he is "fine" despite admitting his sleep and diet are being affecte...
Score: 0.5451104044914246
--------------------------------------------------------------------------------