33import os
44import random
55import uuid
6- from collections .abc import MutableSequence
7- from typing import Annotated , Any
6+ from typing import Annotated
87
9- from agent_framework import ChatAgent , ChatMessage , Context , tool
10- from agent_framework .mem0 import Mem0Provider
8+ from agent_framework import Agent , tool
9+ from agent_framework .mem0 import Mem0ContextProvider
1110from agent_framework .openai import OpenAIChatClient
1211from azure .identity .aio import DefaultAzureCredential , get_bearer_token_provider
1312from dotenv import load_dotenv
4948
5049# NOTE: approval_mode="never_require" is for sample brevity.
5150# Use "always_require" in production.
52- @tool ( approval_mode = "never_require" )
51+ @tool
5352def get_weather (
5453 city : Annotated [str , Field (description = "The city to get the weather for." )],
5554) -> str :
@@ -59,53 +58,12 @@ def get_weather(
5958 return f"The weather in { city } is { conditions [random .randint (0 , 3 )]} with a high of { random .randint (10 , 30 )} °C."
6059
6160
62- class Mem0OSSProvider (Mem0Provider ):
63- """Mem0Provider subclass that fixes search for Mem0 OSS (AsyncMemory).
64-
65- The base Mem0Provider passes user_id/agent_id inside a 'filters' dict,
66- which works for the Mem0 Platform client but not for AsyncMemory (OSS),
67- which expects them as direct keyword arguments.
68- """
69-
70- async def invoking (self , messages : ChatMessage | MutableSequence [ChatMessage ], ** kwargs : Any ) -> Context :
71- self ._validate_filters ()
72- messages_list = [messages ] if isinstance (messages , ChatMessage ) else list (messages )
73- input_text = "\n " .join (msg .text for msg in messages_list if msg and msg .text and msg .text .strip ())
74-
75- if not input_text .strip ():
76- return Context (messages = None )
77-
78- # Pass user_id/agent_id as keyword args (Mem0 OSS API)
79- search_kwargs : dict [str , Any ] = {"query" : input_text }
80- if self .user_id :
81- search_kwargs ["user_id" ] = self .user_id
82- if self .agent_id :
83- search_kwargs ["agent_id" ] = self .agent_id
84-
85- search_response = await self .mem0_client .search (** search_kwargs )
86-
87- if isinstance (search_response , list ):
88- memories = search_response
89- elif isinstance (search_response , dict ) and "results" in search_response :
90- memories = search_response ["results" ]
91- else :
92- memories = [search_response ]
93-
94- line_separated_memories = "\n " .join (memory .get ("memory" , "" ) for memory in memories )
95-
96- return Context (
97- messages = [ChatMessage (role = "user" , text = f"{ self .context_prompt } \n { line_separated_memories } " )]
98- if line_separated_memories
99- else None
100- )
101-
102-
10361async def main () -> None :
10462 """Demonstrate an agent with Mem0 OSS for long-term memory.
10563
106- Unlike RedisProvider (which stores raw messages), Mem0 uses an LLM to
64+ Unlike RedisContextProvider (which stores raw messages), Mem0 uses an LLM to
10765 extract and store distilled facts from conversations. When the agent
108- starts a new thread , Mem0 injects relevant memories as context.
66+ starts a new session , Mem0 injects relevant memories as context.
10967
11068 Mem0 OSS needs an LLM and embedder for memory extraction. This example
11169 uses Azure OpenAI when API_HOST=azure, otherwise falls back to OPENAI_API_KEY.
@@ -161,16 +119,16 @@ async def main() -> None:
161119
162120 mem0_client = await AsyncMemory .from_config (mem0_config )
163121
164- provider = Mem0OSSProvider ( user_id = user_id , mem0_client = mem0_client )
122+ provider = Mem0ContextProvider ( source_id = "mem0_memory" , user_id = user_id , mem0_client = mem0_client )
165123
166- agent = ChatAgent (
167- chat_client = client ,
124+ agent = Agent (
125+ client = client ,
168126 instructions = (
169127 "You are a helpful weather assistant. Personalize replies using provided context. "
170128 "Before answering, always check for stored context."
171129 ),
172130 tools = [get_weather ],
173- context_provider = provider ,
131+ context_providers = [ provider ] ,
174132 )
175133
176134 # Step 1: Teach the agent user preferences
@@ -179,12 +137,12 @@ async def main() -> None:
179137 response = await agent .run ("Remember that my favorite city is Tokyo and I prefer Celsius." )
180138 print (f"[green]Agent:[/green] { response .text } " )
181139
182- # Step 2: Start a new thread — Mem0 should inject remembered facts
183- print ("\n [dim]--- Step 2: New thread — recalling preferences ---[/dim]" )
140+ # Step 2: Start a new session — Mem0 should inject remembered facts
141+ print ("\n [dim]--- Step 2: New session — recalling preferences ---[/dim]" )
184142 print ("[blue]User:[/blue] What's my favorite city?" )
185143 response = await agent .run ("What's my favorite city?" )
186144 print (f"[green]Agent:[/green] { response .text } " )
187- print ("[dim]Note: Mem0 extracted and stored facts, then injected them into the new thread .[/dim]" )
145+ print ("[dim]Note: Mem0 extracted and stored facts, then injected them into the new session .[/dim]" )
188146
189147 # Step 3: Use a tool, demonstrating memory with tool outputs
190148 print ("\n [dim]--- Step 3: Tool use with memory ---[/dim]" )
0 commit comments