|
| 1 | +import asyncio |
| 2 | + |
| 3 | +from claude_agent_sdk import ( |
| 4 | + AssistantMessage, |
| 5 | + ClaudeAgentOptions, |
| 6 | + ClaudeSDKClient, |
| 7 | + ResultMessage, |
| 8 | + TextBlock, |
| 9 | +) |
| 10 | +from memory.local.memorize import memorize |
| 11 | +from memory.local.tools import _get_todos, memu_server |
| 12 | + |
| 13 | +# Set your Anthropic API key here if it's not set in the environment variables |
| 14 | +# os.environ["ANTHROPIC_API_KEY"] = "" |
| 15 | + |
| 16 | +N_MESSAGES_MEMORIZE = 2 |
| 17 | + |
| 18 | + |
| 19 | +async def trigger_memorize(messages: list[dict[str, any]]) -> bool: |
| 20 | + """Background task to memorize conversation messages.""" |
| 21 | + try: |
| 22 | + await memorize(messages) |
| 23 | + print("\n[Background] Memorization submitted.") |
| 24 | + return True |
| 25 | + except Exception as e: |
| 26 | + print(f"\n[Background] Memorization failed: {e!r}") |
| 27 | + return False |
| 28 | + |
| 29 | + |
| 30 | +async def main(): |
| 31 | + options = ClaudeAgentOptions( |
| 32 | + mcp_servers={"memu": memu_server}, |
| 33 | + allowed_tools=[ |
| 34 | + # "mcp__memu__memu_memory", |
| 35 | + "mcp__memu__memu_todos", |
| 36 | + ], |
| 37 | + ) |
| 38 | + |
| 39 | + conversation_messages: list[dict[str, any]] = [] |
| 40 | + pending_tasks: list[asyncio.Task] = [] |
| 41 | + |
| 42 | + print("Claude Autorun") |
| 43 | + print("Type 'quit' or 'exit' to end the session.") |
| 44 | + print("-" * 40) |
| 45 | + |
| 46 | + round = 0 |
| 47 | + async with ClaudeSDKClient(options=options) as client: |
| 48 | + while True: |
| 49 | + want_user_input = False |
| 50 | + |
| 51 | + if round == 0: |
| 52 | + want_user_input = True |
| 53 | + else: |
| 54 | + todos = await _get_todos() |
| 55 | + if todos: |
| 56 | + user_input = f"Please continue with the following todos:\n{todos}" |
| 57 | + else: |
| 58 | + want_user_input = True |
| 59 | + |
| 60 | + if want_user_input: |
| 61 | + try: |
| 62 | + user_input = input("\nYou: ").strip() |
| 63 | + except EOFError: |
| 64 | + break |
| 65 | + |
| 66 | + if not user_input: |
| 67 | + continue |
| 68 | + |
| 69 | + if user_input.lower() in ("quit", "exit"): |
| 70 | + break |
| 71 | + |
| 72 | + # Record user message |
| 73 | + conversation_messages.append({"role": "user", "content": user_input}) |
| 74 | + |
| 75 | + # Send query to Claude |
| 76 | + await client.query(user_input) |
| 77 | + |
| 78 | + # Collect assistant response |
| 79 | + assistant_text_parts: list[str] = [] |
| 80 | + |
| 81 | + async for message in client.receive_response(): |
| 82 | + if isinstance(message, AssistantMessage): |
| 83 | + for block in message.content: |
| 84 | + if isinstance(block, TextBlock): |
| 85 | + print(f"Claude: {block.text}") |
| 86 | + assistant_text_parts.append(block.text) |
| 87 | + elif isinstance(message, ResultMessage): |
| 88 | + print(f"Result: {message.result}") |
| 89 | + |
| 90 | + # Record assistant message |
| 91 | + if assistant_text_parts: |
| 92 | + conversation_messages.append({"role": "assistant", "content": "\n".join(assistant_text_parts)}) |
| 93 | + |
| 94 | + # Check if we should trigger memorization |
| 95 | + if len(conversation_messages) >= N_MESSAGES_MEMORIZE: |
| 96 | + print(f"\n[Info] Reached {N_MESSAGES_MEMORIZE} messages, triggering memorization...") |
| 97 | + success = await trigger_memorize(conversation_messages.copy()) |
| 98 | + if success: |
| 99 | + conversation_messages.clear() |
| 100 | + |
| 101 | + round += 1 |
| 102 | + |
| 103 | + # User quit - memorize remaining messages if any |
| 104 | + if conversation_messages: |
| 105 | + print("\n[Info] Session ended, memorizing remaining messages...") |
| 106 | + success = await trigger_memorize(conversation_messages.copy()) |
| 107 | + |
| 108 | + # Wait for all pending memorization tasks to complete |
| 109 | + if pending_tasks: |
| 110 | + print("[Info] Waiting for memorization tasks to complete...") |
| 111 | + await asyncio.gather(*pending_tasks, return_exceptions=True) |
| 112 | + |
| 113 | + print("\nDone") |
| 114 | + |
| 115 | + |
| 116 | +if __name__ == "__main__": |
| 117 | + asyncio.run(main()) |
0 commit comments