from openai import OpenAI import json import os import subprocess client = OpenAI( api_key=os.environ["GROQ_API_KEY"], base_url="https://api.groq.com/openai/v1" ) SYSTEM_PROMPT = """Ты — агент-разработчик. Пиши файлы проекта строго по порядку, каждый файл один раз. ## Механика tickets - Каждый участник имеет поле tickets (начинается с 1) - В розыгрыше участвуют только присутствующие с tickets > 0 и без pass_point - Победитель: tickets = 0, pass_point = true - Проигравшие участники розыгрыша: tickets += 1 - Участник с pass_point присутствует но НЕ участвует в розыгрыше, pass_point = false, first_tea_after_pass = true - Участник с first_tea_after_pass: tickets += 1 в начале чаепития, флаг = false, участвует в розыгрыше - Отсутствующие: ничего не меняется ## Алгоритм розыгрыша (СТРОГО В ТАКОМ ПОРЯДКЕ) 1. Для каждого присутствующего: - если first_tea_after_pass=true -> tickets += 1, флаг false - если pass_point=true -> исключить из розыгрыша, pass_point=false, first_tea_after_pass=true 2. Розыгрыш среди оставшихся (случайный выбор, вес = tickets) 3. Победитель: tickets=0, pass_point=true 4. Остальные участники розыгрыша: tickets += 1 5. Сохранить в историю ## Структура БД (SQLite) Таблица participants: id, name UNIQUE, tickets DEFAULT 1, pass_point DEFAULT false, first_tea_after_pass DEFAULT false Таблица history: id, date, present (json), winner, snapshot (json) ## API GET /api/participants POST /api/participants body: {"name": "Иван"} DELETE /api/participants/{id} POST /api/spin body: {"present": ["Иван", "Мурад"]} GET /api/history ## Детали реализации - БД: /app/data/teapot.db - FastAPI отдает frontend как StaticFiles - index.html на / (через FileResponse) - admin.html на /admin (через FileResponse) - CORS для всех origins ## Dockerfile FROM python:3.11-slim WORKDIR /app RUN pip install fastapi uvicorn aiosqlite COPY backend/ ./backend/ COPY frontend/ ./frontend/ CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8080"] ## docker-compose.yml version: "3.8" services: app: build: . ports: - "8080:8080" volumes: - ./data:/app/data ## ПРАВИЛА - Пиши каждый файл ОДИН РАЗ полностью - Никаких TODO и заглушек - Порядок: database.py -> logic.py -> main.py -> index.html -> admin.html -> Dockerfile -> docker-compose.yml - После всех файлов запусти проверку синтаксиса """ tools = [ { "type": "function", "function": { "name": "write_file", "description": "Создать файл. content должен содержать ПОЛНЫЙ код.", "parameters": { "type": "object", "properties": { "path": {"type": "string"}, "content": {"type": "string"} }, "required": ["path", "content"] } } }, { "type": "function", "function": { "name": "run_command", "description": "Выполнить команду в терминале", "parameters": { "type": "object", "properties": { "command": {"type": "string"} }, "required": ["command"] } } } ] def write_file(path: str, content: str) -> str: if not content or not content.strip(): return "ОШИБКА: content пустой. Передай полное содержимое файла." os.makedirs(os.path.dirname(path) if os.path.dirname(path) else ".", exist_ok=True) with open(path, "w") as f: f.write(content) return f"OK: {path} ({len(content)} символов)" def run_command(command: str) -> str: result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30) output = result.stdout + result.stderr return output[:2000] if len(output) > 2000 else output def execute_tool(name: str, args: dict) -> str: if name == "write_file": return write_file(**args) elif name == "run_command": return run_command(**args) return f"Неизвестный инструмент: {name}" def clean_message(message) -> dict: msg = message.model_dump() for field in ["annotations", "audio", "function_call", "refusal"]: msg.pop(field, None) if msg.get("tool_calls"): cleaned = [] for tc in msg["tool_calls"]: for field in ["annotations", "audio"]: tc.pop(field, None) if tc.get("function") and isinstance(tc["function"].get("arguments"), dict): tc["function"]["arguments"] = json.dumps(tc["function"]["arguments"]) cleaned.append(tc) msg["tool_calls"] = cleaned return msg def compress_history(messages: list) -> list: compressed = [] for msg in messages: if msg["role"] == "tool": content = msg["content"] if len(content) > 100: content = content[:100] + "...[обрезано]" compressed.append({**msg, "content": content}) elif msg["role"] == "assistant" and msg.get("tool_calls"): short = {**msg, "content": ""} compressed.append(short) else: compressed.append(msg) return compressed def run_agent(): created_files = [] messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": "Создай все файлы проекта в папке teapot/. Начни с teapot/backend/database.py."} ] step = 0 while True: step += 1 print(f"\n{'='*50}\nШаг {step}\n{'='*50}") response = client.chat.completions.create( model="meta-llama/llama-4-maverick-17b-128e-instruct", messages=compress_history(messages), tools=tools, tool_choice="auto", parallel_tool_calls=False, max_tokens=8000 ) message = response.choices[0].message if message.content: print(f"\nАгент: {message.content[:200]}") messages.append(clean_message(message)) if not message.tool_calls or step >= 20: print(f"\nГотово. Созданные файлы: {created_files}") break for tool_call in message.tool_calls: name = tool_call.function.name args = json.loads(tool_call.function.arguments) print(f"\n[{name}] ", end="") if name == "write_file": print(args["path"]) if args["path"] not in created_files: created_files.append(args["path"]) else: print(f" -> ПРОПУСК: файл уже создан") messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": f"ПРОПУСК: {args['path']} уже существует. Переходи к следующему файлу." }) continue else: print(args.get("command", "")) result = execute_tool(name, args) print(f" -> {result[:150]}") messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": result }) if __name__ == "__main__": run_agent()