File size: 8,191 Bytes
d56157f | 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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | 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() |