Spaces:
Sleeping
Sleeping
Download server.py from KrilinZ/neuronalis: direct link, hf CLI and curl.
- Browser
- Download file 3.92 kB
-
https://huggingface.co/spaces/KrilinZ/neuronalis/resolve/main/server.py
- Command line
-
hf download hf://spaces/KrilinZ/neuronalis/server.py
-
curl -L -o server.py https://huggingface.co/spaces/KrilinZ/neuronalis/resolve/main/server.py
3.92 kB
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from typing import List, Optional, Dict | |
| import uvicorn | |
| import os | |
| import re | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from config import Config | |
| from llm_client import LLMClient | |
| from system_prompts import SystemPrompts | |
| from tools import file_operations, code_search, bash_executor | |
| app = FastAPI() | |
| PUBLIC_DEPLOY = os.getenv("PUBLIC_DEPLOY", "0") == "1" | |
| # Enable CORS | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| class Message(BaseModel): | |
| role: str | |
| content: str | |
| class ChatRequest(BaseModel): | |
| messages: List[Message] | |
| cwd: Optional[str] = None | |
| # Tool Mapping | |
| TOOLS = { | |
| "read_file": file_operations.read_file, | |
| "write_file": file_operations.write_file, | |
| "edit_file": file_operations.edit_file, | |
| "list_files": file_operations.list_files, | |
| "grep_search": code_search.grep_search, | |
| "execute_command": bash_executor.execute_command | |
| } | |
| def execute_tool_call(call_str): | |
| if PUBLIC_DEPLOY: | |
| return "Herramientas deshabilitadas en modo público." | |
| tool_name = call_str.split('(')[0] | |
| if tool_name not in TOOLS: | |
| return f"Error: Tool {tool_name} not found." | |
| try: | |
| context = TOOLS.copy() | |
| result = eval(call_str, {"__builtins__": {}}, context) | |
| return str(result) | |
| except Exception as e: | |
| return f"Error executing {call_str}: {e}" | |
| def parse_tool_calls(text): | |
| tool_calls = [] | |
| pattern = r"```python\s+(.*?)\s+```" | |
| matches = re.findall(pattern, text, re.DOTALL) | |
| for match in matches: | |
| lines = match.strip().split('\n') | |
| for line in lines: | |
| line = line.strip() | |
| if not line: continue | |
| try: | |
| for tool_name in TOOLS: | |
| if line.startswith(tool_name + "(") and line.endswith(")"): | |
| tool_calls.append(line) | |
| break | |
| except Exception: | |
| pass | |
| return tool_calls | |
| async def chat_endpoint(request: ChatRequest): | |
| cwd = request.cwd or os.getcwd() | |
| # Ensure system prompt is present | |
| messages_data = [m.dict() for m in request.messages] | |
| if not messages_data or messages_data[0]['role'] != 'system': | |
| messages_data.insert(0, {"role": "system", "content": SystemPrompts.get_main_prompt(cwd)}) | |
| llm = LLMClient() | |
| # First LLM Call | |
| try: | |
| # Non-streaming for API simplicity in MVP | |
| response = llm.chat_completion(messages_data, stream=False) | |
| assistant_msg = response.choices[0].message.content | |
| # Check for tools | |
| tool_calls = parse_tool_calls(assistant_msg) | |
| if tool_calls: | |
| tool_outputs = [] | |
| for call in tool_calls: | |
| output = execute_tool_call(call) | |
| tool_outputs.append({ | |
| "call": call, | |
| "output": output | |
| }) | |
| # Add to history for context (simplified) | |
| messages_data.append({"role": "assistant", "content": assistant_msg}) | |
| messages_data.append({"role": "user", "content": f"Tool Output for {call}:\n{output}"}) | |
| # Second LLM Call with tool outputs | |
| second_response = llm.chat_completion(messages_data, stream=False) | |
| final_msg = second_response.choices[0].message.content | |
| return { | |
| "response": final_msg, | |
| "tool_calls": tool_outputs | |
| } | |
| else: | |
| return { | |
| "response": assistant_msg, | |
| "tool_calls": [] | |
| } | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=8000) | |