docs: make example code fences copy-safe (#5833)

This commit is contained in:
Taranjeet Singh
2026-06-24 22:19:40 -07:00
committed by GitHub
parent ac8f862ff7
commit ac296f7534
5 changed files with 80 additions and 73 deletions
+54 -55
View File
@@ -100,12 +100,12 @@ This section:
Initialize both the ElevenLabs and Mem0 clients: Initialize both the ElevenLabs and Mem0 clients:
```python ```python
# Initialize ElevenLabs client # Initialize ElevenLabs client
client = ElevenLabs(api_key=API_KEY) client = ElevenLabs(api_key=API_KEY)
# Initialize memory client and tools # Initialize memory client and tools
client_tools = ClientTools() client_tools = ClientTools()
mem0_client = AsyncMemoryClient() mem0_client = AsyncMemoryClient()
``` ```
Here we: Here we:
@@ -118,36 +118,36 @@ Here we:
Define the two key memory functions that will be registered as tools: Define the two key memory functions that will be registered as tools:
```python ```python
# Define memory-related functions for the agent # Define memory-related functions for the agent
async def add_memories(parameters): async def add_memories(parameters):
"""Add a message to the memory store""" """Add a message to the memory store"""
message = parameters.get("message") message = parameters.get("message")
await mem0_client.add( await mem0_client.add(
messages=message, messages=message,
user_id=USER_ID user_id=USER_ID
) )
return "Memory added successfully" return "Memory added successfully"
async def retrieve_memories(parameters): async def retrieve_memories(parameters):
"""Retrieve relevant memories based on the input message""" """Retrieve relevant memories based on the input message"""
message = parameters.get("message") message = parameters.get("message")
# For Platform API, user_id goes in filters # For Platform API, user_id goes in filters
filters = {"user_id": USER_ID} filters = {"user_id": USER_ID}
# Search for relevant memories using the message as a query # Search for relevant memories using the message as a query
results = await mem0_client.search( results = await mem0_client.search(
query=message, query=message,
filters=filters filters=filters
) )
# Extract and join the memory texts # Extract and join the memory texts
memories = ' '.join([result["memory"] for result in results.get('results', [])]) memories = ' '.join([result["memory"] for result in results.get('results', [])])
print("[ Memories ]", memories) print("[ Memories ]", memories)
if memories: if memories:
return memories return memories
return "No memories found" return "No memories found"
``` ```
These functions: These functions:
@@ -171,9 +171,9 @@ These functions:
Register the memory functions with the ElevenLabs ClientTools system: Register the memory functions with the ElevenLabs ClientTools system:
```python ```python
# Register the memory functions as tools for the agent # Register the memory functions as tools for the agent
client_tools.register("addMemories", add_memories, is_async=True) client_tools.register("addMemories", add_memories, is_async=True)
client_tools.register("retrieveMemories", retrieve_memories, is_async=True) client_tools.register("retrieveMemories", retrieve_memories, is_async=True)
``` ```
This allows the ElevenLabs agent to: This allows the ElevenLabs agent to:
@@ -186,19 +186,19 @@ This allows the ElevenLabs agent to:
Configure the conversation with ElevenLabs: Configure the conversation with ElevenLabs:
```python ```python
# Initialize the conversation # Initialize the conversation
conversation = Conversation( conversation = Conversation(
client, client,
AGENT_ID, AGENT_ID,
# Assume auth is required when API_KEY is set # Assume auth is required when API_KEY is set
requires_auth=bool(API_KEY), requires_auth=bool(API_KEY),
audio_interface=DefaultAudioInterface(), audio_interface=DefaultAudioInterface(),
client_tools=client_tools, client_tools=client_tools,
callback_agent_response=lambda response: print(f"Agent: {response}"), callback_agent_response=lambda response: print(f"Agent: {response}"),
callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"), callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
callback_user_transcript=lambda transcript: print(f"User: {transcript}"), callback_user_transcript=lambda transcript: print(f"User: {transcript}"),
# callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"), # callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),
) )
``` ```
This sets up the conversation with: This sets up the conversation with:
@@ -217,16 +217,16 @@ This sets up the conversation with:
Start and manage the conversation: Start and manage the conversation:
```python ```python
# Start the conversation # Start the conversation
print(f"Starting conversation with user_id: {USER_ID}") print(f"Starting conversation with user_id: {USER_ID}")
conversation.start_session() conversation.start_session()
# Handle Ctrl+C to gracefully end the session # Handle Ctrl+C to gracefully end the session
signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session()) signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session())
# Wait for the conversation to end and get the conversation ID # Wait for the conversation to end and get the conversation ID
conversation_id = conversation.wait_for_session_end() conversation_id = conversation.wait_for_session_end()
print(f"Conversation ID: {conversation_id}") print(f"Conversation ID: {conversation_id}")
if __name__ == '__main__': if __name__ == '__main__':
@@ -445,4 +445,3 @@ By integrating ElevenLabs Conversational AI with Mem0, you can create voice agen
Create voice-first AI applications Create voice-first AI applications
</Card> </Card>
</CardGroup> </CardGroup>
+17 -9
View File
@@ -62,7 +62,8 @@ def add(
filters: dict = None, filters: dict = None,
output_format: str = None, # ❌ REMOVED output_format: str = None, # ❌ REMOVED
version: str = None # ❌ REMOVED version: str = None # ❌ REMOVED
) -> Union[List[dict], dict] ) -> Union[List[dict], dict]:
...
``` ```
#### v1.0.0 Signature #### v1.0.0 Signature
@@ -76,7 +77,8 @@ def add(
metadata: dict = None, metadata: dict = None,
filters: dict = None, filters: dict = None,
infer: bool = True # ✅ NEW: Control memory inference infer: bool = True # ✅ NEW: Control memory inference
) -> dict # Always returns dict with "results" key ) -> dict: # Always returns dict with "results" key
...
``` ```
#### Changes Summary #### Changes Summary
@@ -147,7 +149,8 @@ def search(
filters: dict = None, # Basic key-value only filters: dict = None, # Basic key-value only
output_format: str = None, # ❌ REMOVED output_format: str = None, # ❌ REMOVED
version: str = None # ❌ REMOVED version: str = None # ❌ REMOVED
) -> Union[List[dict], dict] ) -> Union[List[dict], dict]:
...
``` ```
#### v1.0.0 Signature #### v1.0.0 Signature
@@ -161,7 +164,8 @@ def search(
limit: int = 100, limit: int = 100,
filters: dict = None, # ✅ ENHANCED: Advanced operators filters: dict = None, # ✅ ENHANCED: Advanced operators
rerank: bool = True # ✅ NEW: Reranking support rerank: bool = True # ✅ NEW: Reranking support
) -> dict # Always returns dict with "results" key ) -> dict: # Always returns dict with "results" key
...
``` ```
#### Enhanced Filtering #### Enhanced Filtering
@@ -216,7 +220,8 @@ def get_all(
filters: dict = None, filters: dict = None,
output_format: str = None, # ❌ REMOVED output_format: str = None, # ❌ REMOVED
version: str = None # ❌ REMOVED version: str = None # ❌ REMOVED
) -> Union[List[dict], dict] ) -> Union[List[dict], dict]:
...
``` ```
#### v1.0.0 Signature #### v1.0.0 Signature
@@ -227,7 +232,8 @@ def get_all(
agent_id: str = None, agent_id: str = None,
run_id: str = None, run_id: str = None,
filters: dict = None # ✅ ENHANCED: Advanced operators filters: dict = None # ✅ ENHANCED: Advanced operators
) -> dict # Always returns dict with "results" key ) -> dict: # Always returns dict with "results" key
...
``` ```
### update() Method ### update() Method
@@ -239,7 +245,8 @@ def update(
self, self,
memory_id: str, memory_id: str,
data: str data: str
) -> dict ) -> dict:
...
``` ```
### delete() Method ### delete() Method
@@ -250,7 +257,8 @@ def update(
def delete( def delete(
self, self,
memory_id: str memory_id: str
) -> dict ) -> dict:
...
``` ```
### delete_all() Method ### delete_all() Method
@@ -344,7 +352,7 @@ config = {
### New Configuration Options ### New Configuration Options
#### Reranker Configuration #### Reranker Configuration
```python ```text
# Cohere reranker # Cohere reranker
"reranker": { "reranker": {
"provider": "cohere", "provider": "cohere",
@@ -117,7 +117,7 @@ results_without_criteria = client.search(
### Compare Results ### Compare Results
### Search Results (with Criteria) ### Search Results (with Criteria)
```python ```text
[ [
{"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.666, ...}, {"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.666, ...},
{"memory": "User finally has time to draw something after a long time", "score": 0.616, ...}, {"memory": "User finally has time to draw something after a long time", "score": 0.616, ...},
@@ -128,7 +128,7 @@ results_without_criteria = client.search(
``` ```
### Search Results (without Criteria) ### Search Results (without Criteria)
```python ```text
[ [
{"memory": "User is happy today", "score": 0.607, ...}, {"memory": "User is happy today", "score": 0.607, ...},
{"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.512, ...}, {"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.512, ...},
+1 -1
View File
@@ -190,7 +190,7 @@ messages = [
client.add(messages, user_id='alice') client.add(messages, user_id='alice')
``` ```
```python Memories with categories ```text Memories with categories
# Following categories will be created for the memories added # Following categories will be created for the memories added
Sometimes draws and sketches in free time (hobbies) Sometimes draws and sketches in free time (hobbies)
Is quite athletic (sports) Is quite athletic (sports)
+5 -5
View File
@@ -108,10 +108,10 @@ print(response)
```javascript JavaScript ```javascript JavaScript
// Basic Export request // Basic Export request
const filters = {"user_id": "alice"}; const basicFilters = {"user_id": "alice"};
const response = await client.createMemoryExport({ const response = await client.createMemoryExport({
schema: json_schema, schema: json_schema,
filters: filters filters: basicFilters
}); });
// Export with custom instructions and additional filters // Export with custom instructions and additional filters
@@ -124,16 +124,16 @@ const export_instructions = `
`; `;
// For create operation, using only user_id filter as requested // For create operation, using only user_id filter as requested
const filters = { const exportFilters = {
"AND": [ "AND": [
{"user_id": "alex"}, {"user_id": "alex"},
{"created_at": {"gte": "2024-01-01"}} {"created_at": {"gte": "2024-01-01"}}
] ]
} };
const responseWithInstructions = await client.createMemoryExport({ const responseWithInstructions = await client.createMemoryExport({
schema: json_schema, schema: json_schema,
filters: filters, filters: exportFilters,
exportInstructions: export_instructions exportInstructions: export_instructions
}); });