|
| 1 | +""" |
| 2 | +Playground UI for the LangGraph Agentic RAG Agent. |
| 3 | +
|
| 4 | +A simple Flask chat interface that proxies requests to the agent's |
| 5 | +/chat/completions endpoint with streaming support. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + # Make sure the agent is running first (default: http://localhost:8000) |
| 9 | + cd agents/langgraph/agentic_rag |
| 10 | + flask --app playground/app run --port 5001 |
| 11 | +
|
| 12 | + # Or with a custom agent URL: |
| 13 | + AGENT_URL=http://localhost:8000 flask --app playground/app run --port 5001 |
| 14 | +""" |
| 15 | + |
| 16 | +import json |
| 17 | +import logging |
| 18 | +from os import getenv |
| 19 | +from pathlib import Path |
| 20 | + |
| 21 | +import requests as http_requests |
| 22 | +from flask import ( |
| 23 | + Flask, |
| 24 | + Response, |
| 25 | + jsonify, |
| 26 | + render_template, |
| 27 | + request, |
| 28 | + send_file, |
| 29 | + stream_with_context, |
| 30 | +) |
| 31 | + |
| 32 | +logging.basicConfig(level=logging.DEBUG) |
| 33 | +logger = logging.getLogger(__name__) |
| 34 | + |
| 35 | +IMAGES_DIR = Path(__file__).resolve().parents[4] / "images" |
| 36 | + |
| 37 | +app = Flask(__name__) |
| 38 | + |
| 39 | + |
| 40 | +@app.route("/images/<path:filename>") |
| 41 | +def serve_image(filename): |
| 42 | + """Serve images from the project-level images directory.""" |
| 43 | + return send_file(IMAGES_DIR / filename) |
| 44 | + |
| 45 | + |
| 46 | +AGENT_URL = getenv("AGENT_URL", "http://localhost:8000") |
| 47 | + |
| 48 | + |
| 49 | +@app.route("/") |
| 50 | +def index(): |
| 51 | + return render_template("index.html") |
| 52 | + |
| 53 | + |
| 54 | +@app.route("/api/health", methods=["GET"]) |
| 55 | +def health(): |
| 56 | + """Check if the agent is reachable.""" |
| 57 | + try: |
| 58 | + resp = http_requests.get(f"{AGENT_URL}/health", timeout=5) |
| 59 | + return jsonify(resp.json()) |
| 60 | + except Exception as e: |
| 61 | + return jsonify({"status": "unreachable", "error": str(e)}), 503 |
| 62 | + |
| 63 | + |
| 64 | +@app.route("/api/chat", methods=["POST"]) |
| 65 | +def chat(): |
| 66 | + """Proxy chat requests to the agent with streaming.""" |
| 67 | + data = request.get_json() |
| 68 | + messages = data.get("messages", []) |
| 69 | + |
| 70 | + payload = { |
| 71 | + "messages": messages, |
| 72 | + "stream": True, |
| 73 | + } |
| 74 | + |
| 75 | + logger.info(f"Sending request to {AGENT_URL}/chat/completions") |
| 76 | + logger.info(f"Payload: {json.dumps(payload)}") |
| 77 | + |
| 78 | + def generate(): |
| 79 | + try: |
| 80 | + with http_requests.post( |
| 81 | + f"{AGENT_URL}/chat/completions", |
| 82 | + json=payload, |
| 83 | + stream=True, |
| 84 | + timeout=(10, 300), |
| 85 | + ) as resp: |
| 86 | + logger.info(f"Agent response status: {resp.status_code}") |
| 87 | + |
| 88 | + if resp.status_code != 200: |
| 89 | + error_msg = resp.text[:500] |
| 90 | + logger.error(f"Agent error: {error_msg}") |
| 91 | + error = json.dumps( |
| 92 | + { |
| 93 | + "error": { |
| 94 | + "message": f"Agent returned {resp.status_code}: {error_msg}" |
| 95 | + } |
| 96 | + } |
| 97 | + ) |
| 98 | + yield f"data: {error}\n\n" |
| 99 | + return |
| 100 | + |
| 101 | + for chunk in resp.iter_content(chunk_size=None, decode_unicode=True): |
| 102 | + if chunk: |
| 103 | + logger.debug(f"Chunk: {chunk[:200]}") |
| 104 | + yield chunk |
| 105 | + |
| 106 | + except http_requests.exceptions.ConnectionError: |
| 107 | + logger.error(f"Cannot connect to agent at {AGENT_URL}") |
| 108 | + error = json.dumps( |
| 109 | + { |
| 110 | + "error": { |
| 111 | + "message": f"Cannot connect to agent at {AGENT_URL}. Is it running?" |
| 112 | + } |
| 113 | + } |
| 114 | + ) |
| 115 | + yield f"data: {error}\n\n" |
| 116 | + except http_requests.exceptions.ReadTimeout: |
| 117 | + logger.error("Agent request timed out") |
| 118 | + error = json.dumps({"error": {"message": "Agent request timed out (300s)"}}) |
| 119 | + yield f"data: {error}\n\n" |
| 120 | + except Exception as e: |
| 121 | + logger.exception("Unexpected error in proxy") |
| 122 | + error = json.dumps({"error": {"message": str(e)}}) |
| 123 | + yield f"data: {error}\n\n" |
| 124 | + |
| 125 | + return Response( |
| 126 | + stream_with_context(generate()), |
| 127 | + content_type="text/event-stream", |
| 128 | + headers={ |
| 129 | + "Cache-Control": "no-cache", |
| 130 | + "X-Accel-Buffering": "no", |
| 131 | + "Connection": "keep-alive", |
| 132 | + }, |
| 133 | + ) |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + debug_mode = getenv("FLASK_DEBUG", "false").lower() == "true" |
| 138 | + app.run(debug=debug_mode, port=5001) |
0 commit comments