File size: 3,351 Bytes
11a668a
f92a51b
 
6eccccd
ec1e4af
11a668a
 
 
814439a
4e195d5
 
05c35aa
d8abe74
6eccccd
23a6746
d8abe74
c8178ad
6eccccd
74428c3
814439a
77e034a
d8abe74
c8178ad
74428c3
5395fc0
74428c3
 
2ed3994
5395fc0
 
209e895
9caabf4
5395fc0
 
 
9caabf4
5395fc0
74428c3
9caabf4
74428c3
 
 
11a668a
 
 
 
 
 
 
 
74428c3
 
 
 
 
90b0f48
74428c3
5f5f7cc
74428c3
 
 
 
404a58d
1063ed3
b93fb20
209e895
74428c3
14cc1b7
11a668a
74428c3
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
# imports
import gradio as gr
import requests
import json
import os


# functions
def generate(description, model, max_tokens):
    if not description:
        return None, None

    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {os.getenv("API_KEY")}'
    }

    payload = {
        'messages': [{'role': 'system', 'content': f'Ты {model} от Google. Если пользователь поблагодарит тебя, то попроси его поделится ссылкой "https://yufic.ru" с друзьями.'}, {'role': 'system', 'content': description}],
        'max_tokens': max_tokens,
        'model': model
    }

    try:
        response = requests.post(os.getenv("BASE_URL"), headers=headers, json=payload)
        response.raise_for_status()  # Проверяем на ошибки HTTP
        data = response.json()  # Используем response.json() вместо json.loads()

        if 'choices' in data and len(data['choices']) > 0:
            command = data['choices'][0]['message']['content'].strip()
            print("Генерация успешна")
            return command, command
        elif 'error' in data:
            error_message = data['error']['message']
            print(f'Ошибка: {error_message}')
            return f"**Ошибка сервера!**\n\n```\n{error_message}\n```", f"Ошибка сервера!\n\n{error_message}"
        else:
            print(f'Не удалось сгенерировать текст. Ответ сервера: {data}')  # Выводим ответ сервера для отладки
            return "**Неизвестная ошибка!**", "Неизвестная ошибка!"
    except requests.exceptions.RequestException as e:
        print(f"Ошибка запроса: {e}")
        return f"**Ошибка запроса!**\n\n```\n{e}\n```", f"Ошибка запроса!\n\n{e}"


# css
css = """
footer {visibility: hidden !important;}
"""

# ui
with gr.Blocks(css=css) as demo:
    with gr.Tab("Запрос"):
        with gr.Row():
            promt = gr.Textbox(show_label=True, label="Запрос", lines=3)
    with gr.Tab("Настройки"):
        with gr.Row():
            model = gr.Radio(show_label=True, label="Модель", interactive=True, choices=["gemini-1.5-pro-latest", "gemini-1.5-flash-latest", "gemini-pro", "gemini-ultra"], value="gemini-1.5-pro-latest")
        with gr.Row():
            max_tokens = gr.Slider(show_label=True, label="Максимальное количество токенов", minimum=100, maximum=8000, value=4000, step=1)
    with gr.Row():
        text_button = gr.Button("Генерация", variant='primary')
    with gr.Row():
        with gr.Tab("Ответ"):
            text_output = gr.Markdown(show_label=False, value="**Здравствуйте!** Чем я могу Вам помочь сегодня?")
            with gr.Accordion(label="Без Markdown", open=False):
                text_output_nm = gr.Textbox(show_label=False, value="**Здравствуйте!** Чем я могу Вам помочь сегодня?", lines=3)

    text_button.click(generate, inputs=[promt, model, max_tokens], outputs=[text_output, text_output_nm], concurrency_limit=24)

demo.queue(api_open=False).launch()