Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import openai | |
| import json | |
| from pinecone import Pinecone | |
| pc = Pinecone(api_key='72f7d24d-c080-4ce6-a060-a489713284cb') | |
| index_name = 'imdb-vector' | |
| # connect to index | |
| index = pc.Index(index_name) | |
| # get api key from platform.openai.com | |
| openai.api_key = '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' | |
| embed_model = "text-embedding-ada-002" | |
| from openai import OpenAI | |
| client = OpenAI(api_key=openai.api_key) | |
| def generate_context(text): | |
| body=json.dumps({"inputText": text}) | |
| res = client.embeddings.create( | |
| input=[text], | |
| model=embed_model | |
| ).data[0].embedding | |
| result = index.query(vector=res, top_k=7, include_metadata=True) | |
| contexts = [] | |
| contexts = contexts + [x['metadata']['text'] for x in result['matches']] | |
| return contexts | |
| def invoke_openai(prompt): | |
| sys_prompt = "You are a helpful assistant that always answers questions." | |
| # query text-davinci-003 | |
| res = client.chat.completions.create( | |
| model='gpt-3.5-turbo', | |
| messages=[ | |
| {"role": "system", "content": sys_prompt}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| temperature=0 | |
| ) | |
| return res.choices[0].message.content | |
| def build_prompt(message,history): | |
| context=generate_context(message) | |
| messages=[] | |
| prompt=f'Context - {context}\nBased on the above context, answer this question - {message}' | |
| print(prompt) | |
| return invoke_openai(prompt) | |
| iface = gr.ChatInterface(build_prompt, chatbot=gr.Chatbot(height=300), textbox=gr.Textbox(placeholder="Ask me a question", container=False, scale=7), title="IMDB Sentiment Data Analysis Chat", examples = ["Which is most postive review for a movie?", "What is the most reviewed movie?"], theme="soft", cache_examples=False, retry_btn=None, undo_btn="Delete Previous", clear_btn="Clear",) | |
| iface.launch(share=True) |