|
| 1 | +import asyncio |
| 2 | +from agents import Agent, Runner |
| 3 | +from openai.types.responses import ResponseTextDeltaEvent |
| 4 | +from agents.mcp import MCPServerStdio |
| 5 | +from collections import deque |
| 6 | + |
| 7 | + |
| 8 | +# Set up and create the agent |
| 9 | +async def build_agent(): |
| 10 | + # Redis MCP Server |
| 11 | + server = MCPServerStdio( |
| 12 | + params={ |
| 13 | + "command": "uv", |
| 14 | + "args": [ |
| 15 | + "--directory", "<path_to_mcp_server>/mcp-redis/src/", |
| 16 | + "run", "main.py" |
| 17 | + ], |
| 18 | + } |
| 19 | + ) |
| 20 | + |
| 21 | + await server.connect() |
| 22 | + |
| 23 | + # Create and return the agent |
| 24 | + agent = Agent( |
| 25 | + name="Redis Assistant", |
| 26 | + instructions="You are a helpful assistant capable of reading and writing to Redis.", |
| 27 | + mcp_servers=[server] |
| 28 | + ) |
| 29 | + |
| 30 | + return agent |
| 31 | + |
| 32 | + |
| 33 | +# CLI interaction |
| 34 | +async def cli(agent, max_history=30): |
| 35 | + print("🔧 Redis Assistant CLI — Ask me something (type 'exit' to quit):\n") |
| 36 | + conversation_history = deque(maxlen=max_history) |
| 37 | + |
| 38 | + while True: |
| 39 | + q = input("❓> ") |
| 40 | + if q.strip().lower() in {"exit", "quit"}: |
| 41 | + break |
| 42 | + |
| 43 | + if (len(q.strip()) > 0): |
| 44 | + # Add the user's message to history |
| 45 | + conversation_history.append({"role": "user", "content": q}) |
| 46 | + |
| 47 | + # Format the context into a single string |
| 48 | + context = "" |
| 49 | + for turn in conversation_history: |
| 50 | + prefix = "User" if turn["role"] == "user" else "Assistant" |
| 51 | + context += f"{prefix}: {turn['content']}\n" |
| 52 | + |
| 53 | + result = Runner.run_streamed(agent, context.strip()) |
| 54 | + |
| 55 | + response_text = "" |
| 56 | + async for event in result.stream_events(): |
| 57 | + if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent): |
| 58 | + print(event.data.delta, end="", flush=True) |
| 59 | + response_text += event.data.delta |
| 60 | + print("\n") |
| 61 | + |
| 62 | + # Store assistant's reply in history |
| 63 | + conversation_history.append({"role": "assistant", "content": response_text}) |
| 64 | + |
| 65 | + |
| 66 | +# Main entry point |
| 67 | +async def main(): |
| 68 | + agent = await build_agent() |
| 69 | + await cli(agent) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + asyncio.run(main()) |
0 commit comments