Spaces:
Running
Running
| import os | |
| import gradio as gr | |
| from openai import OpenAI | |
| # Проверка ключа | |
| api_key = os.getenv("OPENROUTER_API_KEY") | |
| if not api_key: | |
| raise ValueError("OPENROUTER_API_KEY не найден в Secrets!") | |
| # Клиент OpenRouter | |
| client = OpenAI( | |
| base_url="https://openrouter.ai/api/v1", | |
| api_key=api_key | |
| ) | |
| # Функция обработки сообщений | |
| def ask_ai(user_input, role, history=[]): | |
| if not user_input.strip(): | |
| return history, "Введите сообщение!" | |
| try: | |
| # Системный промпт в зависимости от выбранной роли | |
| system_prompt = f"Ты бот-собеседователь. Роль: {role}. Задавай вопросы и оценивай ответы." | |
| messages = [{"role": "system", "content": system_prompt}] | |
| # Берем последние 6 сообщений (экономим токены) | |
| for h in history[-12:]: | |
| if isinstance(h, dict) and 'role' in h and 'content' in h: | |
| messages.append(h) | |
| # Добавляем текущее сообщение пользователя | |
| messages.append({"role": "user", "content": str(user_input)}) | |
| # Вызов LLM с ограничением токенов | |
| response = client.chat.completions.create( | |
| model="anthropic/claude-3.5-sonnet", | |
| messages=messages, | |
| max_tokens=1000 | |
| ) | |
| answer = response.choices[0].message.content | |
| # Сохраняем историю как словари | |
| history.append({"role": "user", "content": user_input}) | |
| history.append({"role": "assistant", "content": answer}) | |
| return history, "" | |
| except Exception as e: | |
| return history, f"Ошибка при вызове AI: {e}" | |
| # Gradio интерфейс | |
| with gr.Blocks() as demo: | |
| gr.Markdown("### 🟢 HR / Tech Interview Chatbot") | |
| with gr.Row(): | |
| role_selector = gr.Dropdown( | |
| choices=["HR", "Frontend", "Backend"], | |
| value="HR", | |
| label="Выберите роль собеседования" | |
| ) | |
| clear_btn = gr.Button("Очистить чат") | |
| chat = gr.Chatbot() | |
| msg = gr.Textbox(placeholder="Напишите сообщение...") | |
| state = gr.State([]) # история чата | |
| # Кнопка Clear Chat | |
| clear_btn.click(lambda: ([], ""), [], [chat, msg]) | |
| # Отправка сообщения | |
| msg.submit(ask_ai, inputs=[msg, role_selector, state], outputs=[chat, msg]) | |
| # Запуск | |
| demo.launch() |