Spaces:
Sleeping

File size: 3,922 Bytes
5a6158c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

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

@app.post("/chat")
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)