Update app.py
Browse files1234556 unmodified lines626364646566676869707172737465666768697770717972738174757677787980818882839091848586879495888990919210010110210310410510610710810911011111211311411511611711811912012112212393949596979899100101102103104105106107108109110111112113import osimport jsonimport gradio as grfrom huggingface_hub import InferenceClient
56 unmodified lines9. Будь точен в путях к файлам. Используй относительные пути от корня проекта."""
def respond( message, history_json, system_message, max_tokens, temperature, top_p,): import json # Парсим history из JSON строки
def respond(message: str, history_json: str, system_message: str, max_tokens: int, temperature: float, top_p: float) -> str: """Главная функция API. Принимает JSON-строку истории.""" try: history = json.loads(history_json) if history_json else [] except: except Exception: history = []
messages = [{"role": "system", "content": system_message}] messages.extend(history) for msg in history: messages.append({"role": msg["role"], "content": msg["content"]}) messages.append({"role": "user", "content": message})
response = "" try: for msg in client.chat_completion( messages, max_tokens=max_tokens, max_tokens=int(max_tokens), stream=True, temperature=temperature, top_p=top_p, temperature=float(temperature), top_p=float(top_p), ): if len(msg.choices) and msg.choices[0].delta.content: token = msg.choices[0].delta.content response += token response += msg.choices[0].delta.content return response except Exception as e: return f"<response>⚠️ Ошибка API Hugging Face: {str(e)}</response>"
with gr.Blocks(title="AI Coder Agent Backend") as demo: gr.Markdown("# 🤖 AI Coder Agent Backend") gr.Markdown("Этот Space предоставляет API для локального CLI-агента.") with gr.Row(): with gr.Column(): message = gr.Textbox(label="Message", lines=3) history_json = gr.Textbox(label="History (JSON)", lines=5, value="[]") system_message = gr.Textbox(label="System prompt", value=SYSTEM_PROMPT, lines=10) max_tokens = gr.Slider(minimum=1, maximum=8192, value=4096, step=1, label="Max new tokens") temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.2, step=0.1, label="Temperature") top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p") submit_btn = gr.Button("Send") with gr.Column(): output = gr.Textbox(label="Response", lines=20) submit_btn.click( fn=respond, inputs=[message, history_json, system_message, max_tokens, temperature, top_p], outputs=output, api_name="/respond" )
# Используем gr.Interface — он гарантированно создаёт API endpointdemo = gr.Interface( fn=respond, inputs=[ gr.Textbox(label="Message", lines=3), gr.Textbox(label="History JSON", value="[]", lines=2), gr.Textbox(label="System prompt", value=SYSTEM_PROMPT, lines=10), gr.Slider(minimum=1, maximum=8192, value=4096, step=1, label="Max new tokens"), gr.Slider(minimum=0.1, maximum=2.0, value=0.2, step=0.1, label="Temperature"), gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"), ], outputs=gr.Textbox(label="Response", lines=20), title="🤖 AI Coder Agent Backend", description="API для локального CLI-агента. Endpoint: `/predict`", api_name="respond", allow_flagging="never",)
if __name__ == "__main__": demo.launch()app.py+30-43