長期記憶のメモリに興味があったので、Mem0のインテグレーションを試してみました。
ChatGPTのように、会話を長期で覚えておいて、レスポンスに反映させる仕組みをどう実装するか?が興味の対象なので、まずは、チュートリアルに書いてある通りやって・・・動かんやん。結局結構時間使ったけど、次のコードは動作する。ちなみに、ドキュメントの更新が間に合ってないパターンやろな。そもそも、リンクした、サンプルUSER_ID反映されてないやん…。こういうのは物凄くストレスやな。(明日は我が身)
公式チュートリアル問題点
ちなみにどこに問題があったかというと
- USER_ID が元のチュートリアルだとどこにもわたってない
-
searchメソッドには、filtersが必要だし、limitはなくて、本当はtop_k -
addメソッドは、contentではなく、messages
なんもわからんから、チュートリアル流しているのに、最初にこれだけ違うのは辛過ぎる。(ちなみにこういう最近できたやつけは、Vibe Coding とか、GPTでも、LLMが知らんので古いコード書きがち。多分 GA するにあたって、ブレーキングチェンジを仕掛けて、公式ドキュメントアップデート忘れとかなんやろな。
You: Do you know my name?
HTTP error occurred: Client error '400 Bad Request' for url 'https://api.mem0.ai/v2/memories/search/'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400
動作するバージョン。すんません。user_id が同じように引き渡してないところが存在するし、LLM から呼ぶときに、この実装だと、user_id は不要やけど。自分で削除してな。
import os
import asyncio
import httpx
from dotenv import load_dotenv
from agents import Agent, Runner, function_tool
from mem0 import MemoryClient
load_dotenv()
mem0 = MemoryClient(api_key=os.getenv("MEM0_API_KEY"))
USER_ID = "tsuyoshi"
@function_tool
def search_memory(query: str, user_id: str) -> str:
"""Search through pas conversation and memories"""
try:
memories = mem0.search(
query=query,
user_id=USER_ID,
top_k=3,
filters={"user_id": USER_ID},
)
except httpx.HTTPStatusError as exc:
print("\033[31m[Mem0 search HTTP error]")
print(f"→ status: {exc.response.status_code}")
print(f"→ url: {exc.request.url}")
print(f"→ query: {query}")
print(f"→ body: {exc.response.text}\033[0m")
raise
except Exception as exc: # noqa: BLE001
print("\033[31m[Mem0 search unexpected error]")
print(f"→ query: {query}")
print(f"→ error: {exc!r}\033[0m")
raise
if memories and memories.get('results'):
return "\n".join([f"- {mem['memory']}" for mem in memories['results']])
return "No relevant memories found."
@function_tool
def save_memory(content: str, user_id: str) -> str:
"""Save important information to memory"""
mem0.add(
messages=[{"role": "user", "content": content}],
user_id=USER_ID,
)
return "Information saved to memory."
agent = Agent(
name="Personal Assistant",
instructions="""You are a helpful personal assistant with memory capabilities.
Use the search_memory tool to recall past conversations and user preferences.
Use the save_memory tool to store important information about the user.
Always personalize your responses based on available memory.""",
tools=[search_memory, save_memory],
model="gpt-5"
)
async def chat_with_agent(user_input: str, user_id: str) -> str:
"""
Handle user input with automatic memory integration.
Args:
user_input: The user's message
user_id: Unique identifier for the user
Returns:
The agent's response
"""
result = await Runner.run(agent, user_input)
return result.final_output
async def main():
print("=== Simple ChatBot with Agent SDK with Mem0 ===")
print("type 'exit' to quit\n")
user_id=USER_ID,
)
while True:
user_input=input("You: ")
if user_input.lower() in ["exit", "quit"]:
break
answer = await chat_with_agent(user_input, user_id=USER_ID)
print("\n\033[36m" + "="*50) # Cyan color
print("Bot:", answer)
print("="*50 + "\033[0m\n") # Reset color
if __name__ == "__main__":
asyncio.run(main())
(mem0-chatbot) PS C:\repo\learning\memory\mem0-simple> python app.py
=== Simple ChatBot with Agent SDK with Mem0 ===
type 'exit' to quit
You: Do you know my name?
==================================================
Bot: Yes—your name is Tsuyoshi. If you’d like me to use a different name or nickname, just let me know and I’ll update it.
==================================================
You: I'm a programmer and I love blues.
==================================================
Bot: Love that combo—a programmer who’s into the blues! Want me to put together a coding-friendly blues playlist or some artist recs? Also, what languages or stack do you work with so I can tailor examples and tips to your setup?
==================================================
You: Especially Muddy Waters and Harrell "Young Rell" Davenport. Do you recommend some songs?
==================================================
Bot: Great taste, Tsuyoshi!
Muddy Waters – starter set
- Mannish Boy (Hard Again, 1977)
- Hoochie Coochie Man
- I Just Want to Make Love to You
- Got My Mojo Working (check the Newport ’60 live version)
- Rollin’ Stone
- I’m Ready
- Long Distance Call
- Louisiana Blues
- Honey Bee
- I Feel Like Going Home
- Trouble No More
- Champagne & Reefer
About Harrell “Young Rell” Davenport: do you mean the blues guitarist who’s a bit under-the-radar? I don’t have a clean discography match on him. If you can share a track or album you like, I’ll build you a tailored set around his sound and mix it with the Muddy cuts above. If you meant a different “Young Rell” (e.g., the hip‑hop artist), let me know and I’ll pivot the recs.
==================================================
You: Nice, I started a blues band. We have a new member who loves Little Walter. Do you have any recommended songs for our band?
==================================================
Bot: Congrats on the new band, Tsuyoshi! Since your new member loves Little Walter (and you like Muddy Waters), here’s a tight set of Walter-centric tunes that work great for a blues band, with quick notes on groove and common keys. I’ll add harp tips so your player can lock in fast.
Little Walter essentials
- My Babe – Rhumba/shuffle; commonly done in E (Walter’s cut is around Eb). Cross-harp: A harp for E (Ab for Eb). Tight hits and a signature riff—easy crowd winner.
- Juke – Instrumental feature; often in E/Eb. Cross-harp: A/Ab. Classic opener or closer to showcase harp.
- Off the Wall – Up-tempo Chicago shuffle; usually E/Eb. Cross-harp: A/Ab. Big swing feel; great band accents.
- Blues With a Feeling – Slow shuffle/ballad; commonly in C. Cross-harp: F. Spacey, dynamic—perfect for vocal/harp call-and-response.
- Mellow Down Easy – Driving shuffle; often in A (sometimes G). Cross-harp: D (or C). Simple riff everyone can lock to.
- Last Night – Slow blues with stop-time. Often in A. Cross-harp: D. Leave lots of space for vocals and harp fills.
- It Ain’t Right – Medium shuffle; often in G. Cross-harp: C. Punchy hits; tight rhythm guitar essential.
- Hate to See You Go (Sometimes I Wonder) – Driving shuffle; often in E. Cross-harp: A. Unison riff feels powerful when tight.
- Just Your Fool – Rhumba/swing; commonly in F. Cross-harp: Bb. Nice groove change-up mid-set.
- Boom Boom (Out Go the Lights) – Straight-ahead stomper; often in A. Cross-harp: D. Built-in breaks and shout sections.
Easy Muddy Waters tie-ins (Little Walter cut many sides with Muddy)
- I’m Ready – Medium shuffle; commonly in E. Cross-harp: A.
- (I’m Your) Hoochie Coochie Man – Stop-time; often in A. Cross-harp: D. Iconic and audience-friendly.
Quick arrangement tips
- Use stop-time hits on Last Night and Hoochie Coochie Man to make the vocals pop.
- Start with an instrumental (Off the Wall) to dial the mix and feature the harp.
- For My Babe and Mellow Down Easy, guitar and harp can trade the signature riff; lock kicks with the snare.
- Keep one slow blues (Blues With a Feeling) for dynamics and storytelling.
Sample 45-minute set order
- Off the Wall (instrumental)
- My Babe
- Mellow Down Easy
- Blues With a Feeling
- It Ain’t Right
- I’m Ready (Muddy tie-in)
- Just Your Fool
- Hate to See You Go
- Juke (encore)
Want me to tailor keys to your singer’s range and your harp player’s kit? Tell me:
- Your vocalist’s comfortable keys
- Which harps your player has
- Your lineup (e.g., 1 or 2 guitars, keys, horns, etc.)
I can send you transposition notes, count-ins, and a one-page chart pack.
==================================================
You: Do you know my name and preference?
==================================================
Bot: Yes—your name is Tsuyoshi. I have that you like Muddy Waters and you love programming. Is that still accurate? Anything else you want me to remember (e.g., preferred programming languages, music styles, pronouns, or tone/formality)?
==================================================
Dashboard
Dashboard があって、会話が記録されているのがわかる。

上記の反応から見るにあたって、まだコード読んでいないからわからないけど、どうも、Vector Search のラグで過去のデータを読みに行ってるっぽい。自分は、自動でサマライズして保存してくれるとか期待していたみたいだがそれは自分で実装する必要がありそう。
OpenSource
ちなみに、私が試したのは Hosted のものだけど、オープンソースのやつはいろいろなプロバイダをバックエンドに指定できそう。Azure で一番最高そうな Cosmos は実装されていないのが残念。
次のステップ
次のステップとしては、GPT と話をしながら、サマライズのアルゴリズムを考えて組み合わせてみるか。あと、Vector Search 部分の、Embedding の個所とかがどういう設定になっているのか、メタデータ化しているのかなど興味があるので実装を読んでみたい。