import gradio as gr import openai import json from pinecone import Pinecone pc = Pinecone(api_key='72f7d24d-c080-4ce6-a060-a489713284cb') index_name = 'serverless-index' # 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 def generate_context(text): body=json.dumps({"inputText": text}) client = OpenAI(api_key=openai.api_key) 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-0613', 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="Amazon Bedrock and Titan LLM", theme="soft", examples=[ "Who won the best music award?", "Which award did Avatar win?", "Who won the Best Actor award in a supporting role?", "Who is the lyricist for the song Natu Natu from RRR?", "How many awards did the film RRR win?", "Which was the Best International Feature Film?",], cache_examples=False, retry_btn=None, undo_btn="Delete Previous", clear_btn="Clear",) iface.launch(share=True)