|
| 1 | +"""FastAPI server for RLM playground.""" |
| 2 | + |
| 3 | +import os |
| 4 | + |
| 5 | +from dotenv import load_dotenv |
| 6 | +from fastapi import FastAPI |
| 7 | +from fastapi.middleware.cors import CORSMiddleware |
| 8 | + |
| 9 | +from rlm import RLM |
| 10 | +from rlm.logger import RLMLogger |
| 11 | + |
| 12 | +from playground.models import RunRequest, RunResponse |
| 13 | + |
| 14 | +# Load environment variables |
| 15 | +load_dotenv() |
| 16 | + |
| 17 | +# Create FastAPI app |
| 18 | +app = FastAPI( |
| 19 | + title="RLM Playground API", |
| 20 | + description="API for running RLM completions via web interface", |
| 21 | + version="0.1.0", |
| 22 | +) |
| 23 | + |
| 24 | +# Configure CORS |
| 25 | +app.add_middleware( |
| 26 | + CORSMiddleware, |
| 27 | + allow_origins=[ |
| 28 | + "http://localhost:3000", # Next.js dev server |
| 29 | + "http://localhost:3001", # Alternative Next.js port |
| 30 | + "http://127.0.0.1:3000", |
| 31 | + "http://127.0.0.1:3001", |
| 32 | + ], |
| 33 | + allow_credentials=True, |
| 34 | + allow_methods=["*"], |
| 35 | + allow_headers=["*"], |
| 36 | +) |
| 37 | + |
| 38 | + |
| 39 | +@app.get("/") |
| 40 | +def root(): |
| 41 | + """Health check endpoint.""" |
| 42 | + return {"status": "ok", "message": "RLM Playground API"} |
| 43 | + |
| 44 | + |
| 45 | +@app.post("/api/run", response_model=RunResponse) |
| 46 | +def run_rlm(request: RunRequest) -> RunResponse: |
| 47 | + """ |
| 48 | + Run an RLM completion with the provided configuration. |
| 49 | +
|
| 50 | + This endpoint creates an RLM instance, runs a completion, and returns the result. |
| 51 | + """ |
| 52 | + try: |
| 53 | + # Setup logger if enabled |
| 54 | + logger = None |
| 55 | + if request.enable_logging: |
| 56 | + log_dir = os.getenv("RLM_LOG_DIR", "./logs") |
| 57 | + logger = RLMLogger(log_dir=log_dir) |
| 58 | + |
| 59 | + # Create RLM instance |
| 60 | + rlm = RLM( |
| 61 | + backend=request.backend, |
| 62 | + backend_kwargs=request.backend_kwargs or {}, |
| 63 | + environment=request.environment, |
| 64 | + environment_kwargs=request.environment_kwargs or {}, |
| 65 | + max_depth=request.max_depth, |
| 66 | + max_iterations=request.max_iterations, |
| 67 | + other_backends=request.other_backends, |
| 68 | + other_backend_kwargs=request.other_backend_kwargs, |
| 69 | + logger=logger, |
| 70 | + verbose=False, # Disable console output in API |
| 71 | + ) |
| 72 | + |
| 73 | + # Run completion |
| 74 | + result = rlm.completion( |
| 75 | + prompt=request.prompt, |
| 76 | + root_prompt=request.root_prompt, |
| 77 | + ) |
| 78 | + |
| 79 | + # Extract response - handle both string and tuple (type, content) formats |
| 80 | + response_text = result.response |
| 81 | + if isinstance(response_text, tuple): |
| 82 | + # If it's a tuple from find_final_answer, extract the content |
| 83 | + # Format: (type, content) where type is "FINAL" or "FINAL_VAR" |
| 84 | + answer_type, answer_content = response_text |
| 85 | + if answer_type == "FINAL": |
| 86 | + # For FINAL, use the content directly |
| 87 | + response_text = answer_content.strip().strip('"').strip("'") |
| 88 | + elif answer_type == "FINAL_VAR": |
| 89 | + # For FINAL_VAR, the content is the variable name |
| 90 | + # We can't look it up here since we don't have access to the environment |
| 91 | + # So we'll return a message indicating the variable name |
| 92 | + variable_name = answer_content.strip().strip('"').strip("'") |
| 93 | + response_text = f"[FINAL_VAR: {variable_name}]" |
| 94 | + else: |
| 95 | + # Fallback: just use the content |
| 96 | + response_text = ( |
| 97 | + answer_content if isinstance(answer_content, str) else str(answer_content) |
| 98 | + ) |
| 99 | + |
| 100 | + # Convert result to response |
| 101 | + return RunResponse( |
| 102 | + success=True, |
| 103 | + response=str(response_text) if response_text else None, |
| 104 | + root_model=result.root_model, |
| 105 | + execution_time=result.execution_time, |
| 106 | + usage_summary=result.usage_summary.to_dict(), |
| 107 | + error=None, |
| 108 | + ) |
| 109 | + |
| 110 | + except Exception as e: |
| 111 | + # Return error response |
| 112 | + return RunResponse( |
| 113 | + success=False, |
| 114 | + response=None, |
| 115 | + root_model=None, |
| 116 | + execution_time=None, |
| 117 | + usage_summary=None, |
| 118 | + error=str(e), |
| 119 | + ) |
0 commit comments