TestTesting123 commited on
Commit
29e9e80
·
verified ·
1 Parent(s): 123d726

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from openai import OpenAI
4
+
5
+ # Проверка ключа
6
+ api_key = os.getenv("OPENROUTER_API_KEY")
7
+ if not api_key:
8
+ raise ValueError("OPENROUTER_API_KEY не найден в Secrets!")
9
+
10
+ # Клиент OpenRouter
11
+ client = OpenAI(
12
+ base_url="https://openrouter.ai/api/v1",
13
+ api_key=api_key
14
+ )
15
+
16
+ def ask_ai(user_input, history=[]):
17
+ if not user_input.strip():
18
+ return history, "Введите сообщение!"
19
+ try:
20
+ messages = [{"role": "system", "content": "Ты HR-бот, задавай вопросы."}]
21
+ # Берем только последние 6 сообщений
22
+ for h in history[-12:]: # каждый ответ + вопрос = 2 элемента
23
+ if isinstance(h, dict) and 'role' in h and 'content' in h:
24
+ messages.append(h)
25
+ # Добавляем текущее сообщение пользователя
26
+ messages.append({"role": "user", "content": str(user_input)})
27
+
28
+ # Вызов LLM с ограничением токенов
29
+ response = client.chat.completions.create(
30
+ model="anthropic/claude-3.5-sonnet",
31
+ messages=messages,
32
+ max_tokens=1000
33
+ )
34
+
35
+ answer = response.choices[0].message.content
36
+ # Сохраняем в истории как словари
37
+ history.append({"role": "user", "content": user_input})
38
+ history.append({"role": "assistant", "content": answer})
39
+
40
+ return history, ""
41
+ except Exception as e:
42
+ return history, f"Ошибка при вызове AI: {e}"
43
+
44
+ # Gradio интерфейс
45
+ with gr.Blocks() as demo:
46
+ chat = gr.Chatbot()
47
+ msg = gr.Textbox(placeholder="Напишите сообщение...")
48
+ state = gr.State([]) # история чата
49
+ msg.submit(ask_ai, inputs=[msg, state], outputs=[chat, msg])
50
+
51
+ demo.launch()