目录
环境
代码
环境
大语言模型: gpt-40-mini
Mem0: Empower your AI applications with long-term memory and personalization
OpenAPI-Key:
Mem0-Key:
代码
import osfrom dotenv import load_dotenv
from openai import OpenAI
from mem0 import Memory
load_dotenv()
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = 'Open API Key'
from mem0 import MemoryClientclass PersonalTravelAssistant:def __init__(self):self.client = OpenAI(base_url ='https://hk.xty.app/v1')self.memory = MemoryClient(api_key="Mem0 Key")self.messages = [{"role": "system", "content": "You are a personal AI Assistant."}]def ask_question(self, question, user_id):# Fetch previous related memoriesprevious_memories = self.search_memories(question, user_id=user_id)prompt = questionif previous_memories:prompt = f"User input: {question}\n Previous memories: {previous_memories}"self.messages.append({"role": "user", "content": prompt})# Generate response using GPT-4oresponse = self.client.chat.completions.create(model="gpt-4o-mini",messages=self.messages)answer = response.choices[0].message.contentself.messages.append({"role": "assistant", "content": answer})# Store the question in memoryself.memory.add(question, user_id=user_id)return answerdef get_memories(self, user_id):memories = self.memory.get_all(user_id=user_id)return [m['memory'] for m in memories]def search_memories(self, query, user_id):memories = self.memory.search(query, user_id=user_id)return [m['memory'] for m in memories]# Usage example
user_id = "traveler_123"
ai_assistant = PersonalTravelAssistant()def main():while True:question = input("Question: ")if question.lower() in ['q', 'exit']:print("Exiting...")breakanswer = ai_assistant.ask_question(question, user_id=user_id)print(f"Answer: {answer}")memories = ai_assistant.get_memories(user_id=user_id)print("Memories:")for memory in memories:print(f"- {memory}")print("-----")if __name__ == "__main__":main()