Spaces:
Runtime error
Runtime error
File size: 7,381 Bytes
586aa0c 9d7f8de 586aa0c 0f77de4 586aa0c 8fa84bc 16997b3 9872af6 16997b3 9262e02 16997b3 a791fc3 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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
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. Потрібно відповісти на питання від користувача з огляду на контекст. Контекст ми беремо з бази знань, але вона може бути не повна. Якщо контекст не коректний, то відповідай на свій розсуд або передай запит сапорту, про контекс нічого не пишемо у відповіді."+"""
"""+ "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)
print_docs(docs)
source_name = docs[0].metadata['source']
file_name = source_name.replace("/content/drive/MyDrive/yc-bot/faq/", "")
result_text = get_text_by_name(file_name)
context = ""
if result_text:
print(f"Text for '{file_name}' is: {result_text}")
context = context + result_text
#print (len(context))
result = query_gpt_3_5(question, context)
result = result + """
--------------------------------------------------------
[CONTEXT]
""" + 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 = """<h1>YC - FAQ_BOT</h1>
"""
demo = gr.Blocks()
with demo:
gr.HTML(description)
with gr.Row():
with gr.Column(scale=1):
text = gr.Textbox(lines=7, label = "Вопрос?")
b1 = gr.Button("Спросить")
with gr.Column(scale=2):
answer = gr.Textbox(lines=10, label = "Ответ:")
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)
examples = gr.Examples(examples = ['Чи приходять дані моніторингом про анулювання реєстрації платника ПДВ?',
'Чим відрізняються поняття «АКТУАЛЬНО НА» та «ДАНІ ПЕРЕВІРЯЮТЬСЯ» в блоці Історія?',
'При використанні інструмента "Пошук звязків між контрагентами", скільки одночасно я можу перевірити компаній?' ,
'Чи можемо ми побачити перелік товарів і послуг які надаються по зареєстрованій торговій марці юридичної особи?' ,
'Яким чином можна перевірити чи входить компанія до ФПГ та переглянути список всіх компаній, які належать до цієї ФПГ?' ,
'За який період відображається історія податкового боргу?',
'Якщо у компанії є штраф від антимонопольного комітету, чи відображається це на ресурсі?',
'Чи можна в пошуці зв’язків побудувати зв’язок між фізичною особою та фізичною особою (якщо це підприємці)?' ,
'Звідки ви брали дані для фінансового аналізу до 2020 року?' ,
'Чому у Вас дані щодо персоналу надані у діапазонах, а у Статистиці ці дані мають точне значення?' ,
'Які дані знаходяться у вкладці Офіційні повідомлення?',
"Чи залишається публікація санкції , якщо її строк закінчився?"], inputs=[text])
demo.launch(share=False, debug=True) |