CoolFace
Apppublic

Nithiyanandham15/claude_code

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
app.py100 linesDownload Raw Back to root
1import os2import subprocess3import json4import logging5from fastapi import FastAPI, HTTPException, Security, Depends6from fastapi.middleware.cors import CORSMiddleware7from fastapi.security import APIKeyHeader8from pydantic import BaseModel9import ollama10 11# Configure logging12logging.basicConfig(level=logging.INFO)13logger = logging.getLogger(__name__)14 15app = FastAPI()16 17# Enable CORS for frontend access18app.add_middleware(19    CORSMiddleware,20    allow_origins=["*"],  # Allow all origins (Hugging Face Spaces, local dev)21    allow_credentials=True,22    allow_methods=["*"],23    allow_headers=["*"],24)25 26# Security configuration27API_KEY_NAME = "Authorization"28# Default to a placeholder if not set, but warn29# Ensure you set ACCESS_TOKEN in your Space settings (Settings -> Variables and secrets)30ACCESS_TOKEN = os.environ.get("ACCESS_TOKEN")31api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)32 33# Model configuration34MODEL_NAME = os.environ.get("OLLAMA_MODEL", "qwen2.5-coder:1.5b")35 36async def verify_token(api_key: str = Security(api_key_header)):37    if not ACCESS_TOKEN:38        # If no token set, allow access (warning: insecure)39        logger.warning("ACCESS_TOKEN not set, allowing unauthenticated access")40        return "unauthenticated"41        42    if not api_key:43        raise HTTPException(status_code=403, detail="Authorization header missing")44    45    token = api_key.replace("Bearer ", "").strip()46    if token != ACCESS_TOKEN:47        raise HTTPException(status_code=403, detail="Invalid token")48    return token49 50class PromptRequest(BaseModel):51    prompt: str52    model: str = MODEL_NAME53 54@app.get("/")55def read_root():56    return {"message": f"Ollama Coding Agent API is running with model {MODEL_NAME}. Use POST /run to execute tasks."}57 58@app.post("/run")59async def run_agent(request: PromptRequest, token: str = Depends(verify_token)):60    prompt = request.prompt61    model = request.model62    63    try:64        # Check if Ollama is ready65        try:66            ollama.list()67        except Exception as e:68            return {"status": "error", "message": "Ollama server not ready", "details": str(e)}69 70        # Simple "Agent" Logic:71        # 1. Ask the model to generate a response (code or explanation)72        # 2. If the user asked to execute something, we could add tool calling here.73        #    For now, we will return the raw model output as the "agent's response".74        75        # System prompt to give it a persona76        system_prompt = """You are an expert coding assistant running inside a secure environment.77        Your goal is to help the user with programming tasks.78        Provide clear, correct, and concise code solutions.79        """80        81        response = ollama.chat(model=model, messages=[82            {'role': 'system', 'content': system_prompt},83            {'role': 'user', 'content': prompt},84        ])85        86        return {87            "status": "success",88            "model": model,89            "response": response['message']['content'],90            "full_response": response91        }92        93    except Exception as e:94        logger.error(f"Error processing request: {e}")95        raise HTTPException(status_code=500, detail=str(e))96 97if __name__ == "__main__":98    import uvicorn99    uvicorn.run(app, host="0.0.0.0", port=7860)100