chlhpua commited on
Commit
3adf5ab
·
verified ·
1 Parent(s): d667555

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -24
app.py CHANGED
@@ -2,32 +2,39 @@ import os
2
  import gradio as gr
3
  from litellm import completion
4
 
5
- # встановлюємо змінну середовища для COHERE_API_KEY; мій trial ключ
6
- os.environ["COHERE_API_KEY"] = 'AbTU8gQ2cjzBDseA5SB6umXMGFFH3azjKQBQ6iq3'
7
-
8
 
9
  # Функція для отримання відповіді від Cohere
10
- def get_cohere_response(user_input):
 
 
 
 
 
 
11
 
12
- # перевіримо довжину запиту
13
- if len(user_input) < 5:
14
- return "Схоже, щось пішло не так. Спробуй перефразувати своє питання у форматі '*поняття* це?' " \
15
- "або 'що таке *поняття*?' та надішли запит ще раз.\n Looks like something went wrong. Use the " \
16
- "formulation '*concept* is?' or 'what is *concept*?' and try again."
 
17
 
18
- # вказівка щодо формату відповіді
19
- prompt = f"In other cases explain the question in simple words. Give some analogy from real life. " \
20
- f"If the text is not in English, write the answer using language of the question. " \
21
- f"Question: {user_input}"
22
 
23
- response = completion(
24
- model="command-r", # Модель "command-r"
25
- messages=[{
26
- "content": prompt,
27
- "role": "user"
28
- }]
29
- )
30
- return response.choices[0].message.content # лише відповідь-текст
 
 
 
31
 
32
 
33
  # Створюємо інтерфейс Gradio
@@ -38,6 +45,11 @@ def interface():
38
  " можливість нарешті розшифрувати їх на просту й доступну мову, доповнену аналогіями із реального "
39
  "життя. Просто введіть запит, натисніть кнопку — і отримаєте відповідь! "
40
  "<br> _*З використанням моделі [Cohere Command-R](https://cohere.com)._")
 
 
 
 
 
41
  # Вхідне текстове поле
42
  user_input = gr.Textbox(label="Введіть запит", placeholder="Що таке квантова механіка?")
43
 
@@ -48,9 +60,9 @@ def interface():
48
  submit_btn = gr.Button("Отримати відповідь")
49
 
50
  # Визначення дії при натисканні кнопки
51
- submit_btn.click(get_cohere_response, inputs=user_input, outputs=output)
52
 
53
- iface.launch()
54
 
55
 
56
- interface() # виклик інтерфейсу
 
2
  import gradio as gr
3
  from litellm import completion
4
 
 
 
 
5
 
6
  # Функція для отримання відповіді від Cohere
7
+ def get_cohere_response(user_input, api_key):
8
+ # Перевірка наявності ключа
9
+ if not api_key:
10
+ return "Схоже, ви не ввели ключ авторизації. Введіть його та спробуйте ще раз."
11
+
12
+ # Встановлюємо ключ API
13
+ os.environ["COHERE_API_KEY"] = api_key
14
 
15
+ try:
16
+ # Перевіримо довжину запиту
17
+ if len(user_input) < 5:
18
+ return "Схоже, щось пішло не так. Спробуй перефразувати своє питання у форматі '*поняття* це?' " \
19
+ "або 'що таке *поняття*?' та надішли запит ще раз.\n Looks like something went wrong. Use the " \
20
+ "formulation '*concept* is?' or 'what is *concept*?' and try again."
21
 
22
+ # Вказівка щодо формату відповіді
23
+ prompt = f"Explain the question in simple words. Give some analogy from real life. " \
24
+ f"If the text is not in English, write the answer using language of the question. " \
25
+ f"Question: {user_input}"
26
 
27
+ # Викликаємо API
28
+ response = completion(
29
+ model="command-r", # Модель "command-r"
30
+ messages=[{
31
+ "content": prompt,
32
+ "role": "user"
33
+ }]
34
+ )
35
+ return response.choices[0].message.content # лише відповідь-текст
36
+ except Exception as e:
37
+ return f"Схоже, щось пішло не так: {str(e)}. Перевірте ваш ключ і спробуйте ще раз."
38
 
39
 
40
  # Створюємо інтерфейс Gradio
 
45
  " можливість нарешті розшифрувати їх на просту й доступну мову, доповнену аналогіями із реального "
46
  "життя. Просто введіть запит, натисніть кнопку — і отримаєте відповідь! "
47
  "<br> _*З використанням моделі [Cohere Command-R](https://cohere.com)._")
48
+
49
+ # Поле для введення ключа
50
+ api_key = gr.Textbox(label="Введіть ваш Cohere API ключ", type="password",
51
+ placeholder="Введіть ключ авторизації")
52
+
53
  # Вхідне текстове поле
54
  user_input = gr.Textbox(label="Введіть запит", placeholder="Що таке квантова механіка?")
55
 
 
60
  submit_btn = gr.Button("Отримати відповідь")
61
 
62
  # Визначення дії при натисканні кнопки
63
+ submit_btn.click(get_cohere_response, inputs=[user_input, api_key], outputs=output)
64
 
65
+ iface.launch(share=True) # Додаємо share=True для створення публічного посилання
66
 
67
 
68
+ interface() # Виклик інтерфейсу