LaoCzi's picture
Update app.py
bba83c2
raw
history blame
5.46 kB
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)