Spaces:
Runtime error
Runtime error
| import os | |
| import openai | |
| openai.api_key= os.environ.get('API_OPENAI') | |
| AIRTABLE_API_KEY = os.environ.get('API_AIRTABLE') | |
| 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") | |
| # initialize pinecone | |
| pinecone.init( | |
| api_key="078ea261-eaa8-4920-8af6-0870f7f8a096", # find at app.pinecone.io | |
| environment="eu-west4-gcp" # next to api key in console | |
| ) | |
| index_name = "yc-faq" | |
| 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) | |
| demo.launch(share=False, debug=True) |