Update app.py
Browse files123456 unmodified lines616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import osimport gradio as grfrom huggingface_hub import InferenceClient56 unmodified lines9. Будь точен в путях к файлам. Используй относительные пути от корня проекта."""def respond(message,history_json,system_message,max_tokens,temperature,top_p,):import json# Парсим history из JSON строкиtry:history = json.loads(history_json) if history_json else []except:history = []messages = [{"role": "system", "content": system_message}]messages.extend(history)messages.append({"role": "user", "content": message})response = ""try:for msg in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):if len(msg.choices) and msg.choices[0].delta.content:token = msg.choices[0].delta.contentresponse += tokenreturn responseexcept 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")if __name__ == "__main__":demo.launch()1234556 unmodified lines6263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import osimport jsonimport gradio as grfrom huggingface_hub import InferenceClient56 unmodified lines9. Будь точен в путях к файлам. Используй относительные пути от корня проекта."""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 Exception:history = []messages = [{"role": "system", "content": system_message}]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=int(max_tokens),stream=True,temperature=float(temperature),top_p=float(top_p),):if len(msg.choices) and msg.choices[0].delta.content:response += msg.choices[0].delta.contentreturn responseexcept Exception as e:return f"<response>⚠️ Ошибка API Hugging Face: {str(e)}</response>"# Используем 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