見出し画像

mem0aiで0.1.20からのoutput_format(v1.1)に対応する

# pip install openai mem0ai
import json
import os
import re
from datetime import datetime
from openai import OpenAI
from mem0 import MemoryClient

# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = "************************************"

system_content = f"""あなたは優秀なAIアシスタントです。質問に答えて下さい。
現在時刻は{datetime.now()}です。"""

class PersonalAssistant:
    def __init__(self):
        self.client = OpenAI()
        self.memory = MemoryClient(api_key="******************************************")
        self.messages = [{"role": "system", "content": system_content}]

    def ask_question(self, question, user_id):
        # Fetch previous related memories
        previous_memories = self.search_memories(question, user_id=user_id)
        prompt = question
        if previous_memories:
            prompt = f"User input: {question}\n Previous memories: {previous_memories}"
        self.messages.append({"role": "user", "content": prompt})

        # Generate response using GPT-4o
        resp = self.client.chat.completions.create(
            model="gpt-4o-mini",
            messages=self.messages,
            max_tokens=300,
        )
        answer = resp.choices[0].message.content
        self.messages.append({"role": "assistant", "content": answer})

        # Store the question in memory
        self.memory.add(question, user_id=user_id,output_format="v1.1")
        return answer

    def get_memories(self, user_id):
        memories = self.memory.get_all(user_id=user_id,output_format="v1.1")
        tom = ""
        for mem in memories["results"]:
            tom += mem["memory"]
            tom += "\n"
        return tom
    def search_memories(self, query, user_id):
        memories = self.memory.search(query, user_id=user_id, output_format="v1.1")
        tom = ""
        for mem in memories["results"]:
            tom += mem["memory"]
            tom += "\n"
        return tom

# Usage example
user_id = "user123"
ai = PersonalAssistant()
def main():
    while True:
        question = input("You: ")
        if not question:
            print("Exit...")
            break
        answer = ai.ask_question(question, user_id=user_id)
        print(f" chatbot: {answer}")
        # memories = ai.get_memories(user_id=user_id)
        # print(f"Memory: {memories}")

if __name__ == "__main__":
    main()

output_format="v1.1"にするとmemoriesのパースが少々変わるので
対応しました。

いいなと思ったら応援しよう!