|
| 1 | +import json |
| 2 | +import requests |
| 3 | + |
| 4 | + |
| 5 | +def add_memory(user_id: str, content: str, role: str = "user", agent_id: str = "", metadata: str = "", api_key: str = "", base_url: str = "https://api.mem0.ai/v1"): |
| 6 | + try: |
| 7 | + if not user_id: |
| 8 | + return json.dumps({"success": False, "message": "user_id 不能为空", "error": "missing_user_id"}, ensure_ascii=False) |
| 9 | + if not content: |
| 10 | + return json.dumps({"success": False, "message": "content 不能为空", "error": "missing_content"}, ensure_ascii=False) |
| 11 | + if not api_key: |
| 12 | + return json.dumps({"success": False, "message": "api_key 不能为空", "error": "missing_api_key"}, ensure_ascii=False) |
| 13 | + |
| 14 | + payload = { |
| 15 | + "messages": [{"role": role or "user", "content": content}], |
| 16 | + "user_id": user_id, |
| 17 | + "infer": True, |
| 18 | + "version": "v2" |
| 19 | + } |
| 20 | + if agent_id: |
| 21 | + payload["agent_id"] = agent_id |
| 22 | + if metadata: |
| 23 | + try: |
| 24 | + payload["metadata"] = json.loads(metadata) |
| 25 | + except Exception: |
| 26 | + return json.dumps({"success": False, "message": "metadata 必须是合法 JSON 字符串", "error": "invalid_metadata_json"}, ensure_ascii=False) |
| 27 | + |
| 28 | + rep = requests.post( |
| 29 | + url=f"{base_url.rstrip('/')}/memories/", |
| 30 | + headers={ |
| 31 | + "Content-Type": "application/json", |
| 32 | + "Authorization": f"Token {api_key}", |
| 33 | + "Accept": "application/json" |
| 34 | + }, |
| 35 | + json=payload, |
| 36 | + timeout=30 |
| 37 | + ) |
| 38 | + rep.raise_for_status() |
| 39 | + data = rep.json() |
| 40 | + return json.dumps({"success": True, "message": "记忆添加成功", "data": data}, ensure_ascii=False) |
| 41 | + except requests.exceptions.HTTPError as e: |
| 42 | + detail = None |
| 43 | + try: |
| 44 | + detail = e.response.json() |
| 45 | + except Exception: |
| 46 | + detail = e.response.text if e.response is not None else str(e) |
| 47 | + return json.dumps({ |
| 48 | + "success": False, |
| 49 | + "message": "添加记忆失败", |
| 50 | + "error": str(e), |
| 51 | + "status_code": e.response.status_code if e.response is not None else None, |
| 52 | + "details": detail |
| 53 | + }, ensure_ascii=False) |
| 54 | + except requests.exceptions.RequestException as e: |
| 55 | + return json.dumps({"success": False, "message": "添加记忆请求失败", "error": str(e)}, ensure_ascii=False) |
| 56 | + except Exception as e: |
| 57 | + return json.dumps({"success": False, "message": "处理添加记忆响应时发生错误", "error": str(e)}, ensure_ascii=False) |
0 commit comments