|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | + |
| 4 | +from agents import ( |
| 5 | + Agent, |
| 6 | + OpenAIChatCompletionsModel, |
| 7 | + Runner, |
| 8 | + function_tool, |
| 9 | + set_tracing_disabled, |
| 10 | +) |
| 11 | +from openai import AsyncOpenAI |
| 12 | + |
| 13 | +from memmachine import MemMachineClient |
| 14 | + |
| 15 | +_MEMMACHINE_CLIENT = None |
| 16 | +_MEMMACHINE_PROJECT = None |
| 17 | + |
| 18 | + |
| 19 | +def _get_memmachine_project(): |
| 20 | + """Create (or reuse) a MemMachine Project handle (global boundary).""" |
| 21 | + global _MEMMACHINE_CLIENT, _MEMMACHINE_PROJECT |
| 22 | + if _MEMMACHINE_PROJECT is not None: |
| 23 | + return _MEMMACHINE_PROJECT |
| 24 | + |
| 25 | + base_url = os.getenv("MEMMACHINE_BASE_URL") or "http://localhost:8080" |
| 26 | + api_key = os.getenv("MEMMACHINE_API_KEY") or "" |
| 27 | + org_id = os.getenv("MEMMACHINE_ORG_ID") or "default_org" |
| 28 | + project_id = os.getenv("MEMMACHINE_PROJECT_ID") or "openai_agent_demo" |
| 29 | + |
| 30 | + _MEMMACHINE_CLIENT = MemMachineClient( |
| 31 | + api_key=api_key, base_url=base_url, timeout=30 |
| 32 | + ) |
| 33 | + _MEMMACHINE_PROJECT = _MEMMACHINE_CLIENT.get_or_create_project( |
| 34 | + org_id=org_id, |
| 35 | + project_id=project_id, |
| 36 | + description="openai-agents tool memory integration", |
| 37 | + ) |
| 38 | + return _MEMMACHINE_PROJECT |
| 39 | + |
| 40 | + |
| 41 | +def _get_memmachine_memory(): |
| 42 | + project = _get_memmachine_project() |
| 43 | + return project.memory() |
| 44 | + |
| 45 | + |
| 46 | +@function_tool |
| 47 | +def add_memory(memory: str) -> str: |
| 48 | + """Persist one memory string into MemMachine.""" |
| 49 | + mem = _get_memmachine_memory() |
| 50 | + mem.add( |
| 51 | + content=memory, |
| 52 | + role="user", |
| 53 | + metadata={"type": "explicit_memory"}, |
| 54 | + ) |
| 55 | + return "ok" |
| 56 | + |
| 57 | + |
| 58 | +@function_tool |
| 59 | +def search_memory(query: str) -> list[str]: |
| 60 | + """Search memories from MemMachine and return a simplified text list.""" |
| 61 | + |
| 62 | + mem = _get_memmachine_memory() |
| 63 | + result = mem.search(query=query, limit=10) |
| 64 | + content = result.content |
| 65 | + |
| 66 | + lines: list[str] = [] |
| 67 | + |
| 68 | + episodic = content.get("episodic_memory") or {} |
| 69 | + long_term = episodic.get("long_term_memory") or {} |
| 70 | + short_term = episodic.get("short_term_memory") or {} |
| 71 | + |
| 72 | + for bucket_name, bucket in ( |
| 73 | + ("long_term_memory", long_term), |
| 74 | + ("short_term_memory", short_term), |
| 75 | + ): |
| 76 | + episodes = bucket.get("episodes") or [] |
| 77 | + if episodes: |
| 78 | + lines.append(f"{bucket_name}:") |
| 79 | + lines.extend(f"- {ep['content']}" for ep in episodes) |
| 80 | + |
| 81 | + summaries = short_term.get("episode_summary") or [] |
| 82 | + if summaries: |
| 83 | + lines.append("episode_summary:") |
| 84 | + lines.extend(f"- {s}" for s in summaries) |
| 85 | + |
| 86 | + semantic = content.get("semantic_memory") or [] |
| 87 | + if semantic: |
| 88 | + lines.append("semantic_memory:") |
| 89 | + lines.extend( |
| 90 | + f"- [{item.get('category')}/{item.get('tag')}] {item.get('feature_name')} = {item.get('value')}" |
| 91 | + for item in semantic |
| 92 | + ) |
| 93 | + |
| 94 | + return lines |
| 95 | + |
| 96 | + |
| 97 | +def _get_qwen_client() -> AsyncOpenAI: |
| 98 | + base_url = ( |
| 99 | + os.getenv("QWEN_BASE_URL") |
| 100 | + or "https://dashscope.aliyuncs.com/compatible-mode/v1" |
| 101 | + ) |
| 102 | + api_key = os.getenv("QWEN_API_KEY") or os.getenv("DASHSCOPE_API_KEY") |
| 103 | + if not api_key: |
| 104 | + raise ValueError( |
| 105 | + "Missing API key. Set QWEN_API_KEY (or DASHSCOPE_API_KEY) in your environment." |
| 106 | + ) |
| 107 | + return AsyncOpenAI(base_url=base_url, api_key=api_key) |
| 108 | + |
| 109 | + |
| 110 | +async def main() -> None: |
| 111 | + # Disable tracing to avoid requiring an OpenAI key for trace export. |
| 112 | + set_tracing_disabled(True) |
| 113 | + |
| 114 | + qwen_model = OpenAIChatCompletionsModel( |
| 115 | + model="qwen3-max", |
| 116 | + openai_client=_get_qwen_client(), |
| 117 | + ) |
| 118 | + |
| 119 | + agent = Agent( |
| 120 | + name="MemoryAgent", |
| 121 | + instructions=( |
| 122 | + "You are an assistant with an external memory.\n" |
| 123 | + "- When the user asks you to remember something, use add_memory to store the information.\n" |
| 124 | + "- When the user asks you to recall what was stored, use search_memory to retrieve the stored memories and answer based on them.\n" |
| 125 | + "- Use tools when helpful, but don't overuse them.\n" |
| 126 | + "- Keep answers concise and direct." |
| 127 | + ), |
| 128 | + model=qwen_model, |
| 129 | + tools=[add_memory, search_memory], |
| 130 | + ) |
| 131 | + |
| 132 | + # ---- Test run ---- |
| 133 | + info = "My name is Alice." |
| 134 | + |
| 135 | + result1 = await Runner.run(agent, f"Please remember: {info}") |
| 136 | + print("[turn1]", result1.final_output) |
| 137 | + |
| 138 | + result2 = await Runner.run( |
| 139 | + agent, |
| 140 | + "What did I ask you to remember earlier? Please recall it from your memory.", |
| 141 | + ) |
| 142 | + print("[turn2]", result2.final_output) |
| 143 | + |
| 144 | + |
| 145 | +if __name__ == "__main__": |
| 146 | + asyncio.run(main()) |
0 commit comments