Spaces:
Runtime error
Runtime error
File size: 5,460 Bytes
586aa0c 9d7f8de 586aa0c 0f77de4 586aa0c 8fa84bc 16997b3 afa7e2d 16997b3 9872af6 16997b3 9262e02 16997b3 601c6ac 16997b3 ec533d0 16997b3 cac1540 16997b3 bba83c2 16997b3 bba83c2 16997b3 67aab1a 16997b3 67aab1a 16997b3 ec533d0 16997b3 |
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
import os
import openai
import pinecone
openai.api_key= os.environ.get('API_OPENAI')
AIRTABLE_API_KEY = os.environ.get('API_AIRTABLE')
PINECONE_API_KEY = os.environ.get('API_PINECONE')
pinecone.init(
api_key=PINECONE_API_KEY, # find at app.pinecone.io
environment="eu-west4-gcp" # next to api key in console
)
import gradio as gr
import os
import csv
from langchain.vectorstores import Pinecone
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.chains import ConversationalRetrievalChain
from langchain.chat_models import ChatOpenAI
import openai
import pinecone
import datetime
from tqdm.autonotebook import tqdm
import requests
embeddings = OpenAIEmbeddings(openai_api_key=openai.api_key)
AIRTABLE_ENDPOINT = "https://api.airtable.com/v0/appv2hF1PzrseVdeW/data_m"
AIRTABLE_ENDPOINT_LOG = "https://api.airtable.com/v0/appv2hF1PzrseVdeW/log"
HEADERS = {
"Authorization": f"Bearer {AIRTABLE_API_KEY}",
"Content-Type": "application/json"
}
def get_text_by_name(name):
params = {
"filterByFormula": f"{{name}} = '{name}'"
}
response = requests.get(AIRTABLE_ENDPOINT, headers=HEADERS, params=params)
if response.status_code != 200:
print(f"Error fetching data. Status code: {response.status_code}. Content: {response.content}")
return None
records = response.json().get("records")
if not records:
print(f"No record found with name: {name}")
return None
# Assuming that names are unique, take the first record.
return records[0]["fields"].get("text")
def upload_to_airtable_log(date, question, answer, rating, comment):
data = {
"records": [{
"fields": {
"date": date,
"question": question,
"answer": answer,
"rating": rating,
"comment": comment
}
}]
}
response = requests.post(AIRTABLE_ENDPOINT_LOG, headers=HEADERS, json=data)
if response.status_code != 200:
print(f"Error uploading airtable (log ) Status code: {response.status_code}. Content: {response.content}")
else:
print(f"Successfully uploaded airtable log")
def query_gpt_3_5(prompt, context):
prompt = "Instruction: Твоя роль - кваліфікований співробітник саппорту у системи YouControl. Потрібно відповісти на питання від користувача з огляду на контекст. Контекст ми беремо з бази знань, але вона може бути не повна. Якщо контекст не коректний, то відповідай на свій розсуд або передай запит сапорту, про контекс нічого не пишемо у відповіді. YouControl може писатися по різному: YC,Ю-контрол,Юконтрол, Юконтроль, Юр контроль, ЮК, UControl, Ю-контроль, YOU Kontrol, YouContro. ЗЕД - це зовнішня економічна діяльність."+"""
"""+ "question:" + prompt + """
context:""" + context + """
answer:"""
completion = openai.ChatCompletion.create(
model="gpt-4-0613",
messages=[
{"role": "user", "content": prompt}
]
)
return completion.choices[0].message.content
def print_docs(docs):
for doc in docs:
print(f"Chunk: {doc.page_content}")
print(f"Content: {doc.metadata['source']}\n")
index_name = "yc-faq-air"
vectorstore = Pinecone.from_existing_index(index_name, embeddings)
def ask_yc_bot(question):
if (len(question)<3 ): return "Не зрозумів питання"
docs = vectorstore.similarity_search(question)
source_name = docs[0].metadata['source']
context = docs[0].page_content
result = query_gpt_3_5(question, context)
return result
def comment_bot(slider_value, comment_text, question_text, answer_text):
date_d = datetime.datetime.now().date()
date_string = date_d.isoformat()
upload_to_airtable_log(date_string, question_text, answer_text, slider_value, comment_text)
return " " # Если функция должна что-то возвращать, замените это на нужный вывод
import gradio as gr
description = """<h3>Бот навчений на матеріалах академії за темою YouControl, про YC.market і YCW нічого не знає. <br> Будь ласка, оцініть його відповідь))) </h3>
"""
demo = gr.Blocks(theme=gr.themes.Glass())
with demo:
gr.HTML(description)
with gr.Row():
with gr.Column(scale=1):
text = gr.Textbox(lines=5, label = "Питання?")
with gr.Column(scale=2):
answer = gr.Textbox(lines=5, label = "Відповідь")
with gr.Row():
b1 = gr.Button("Запитати")
with gr.Row():
radio = gr.Radio(label="Рейтинг відповіді", choices=["Нема", "1", "2", "3", "4", "5"], value="Нема")
comment = gr.Textbox(lines=2, label = "Коментар")
with gr.Row():
b2 = gr.Button("Прокоментувати відповідь")
inp_2 = [radio, comment, text, answer]
b1.click(ask_yc_bot, inputs=text, outputs=answer)
b2.click(comment_bot, inputs=inp_2, outputs=comment)
demo.launch(share=False, debug=True) |