thoristhor's picture
Update app.py
36ed299
raw
history blame
2.75 kB
import os
from typing import Optional, Tuple
import gradio as gr
import pinecone
from langchain.vectorstores import Pinecone
# initialize pinecone
pinecone.init(
api_key="PINECONE_API_KEY", # find at app.pinecone.io
environment="PINECONE_ENV" # next to api key in console
)
vectorstore = Pinecone.from_texts(texts, embeddings, index_name="sethgodin")
from query_data import get_chain
from threading import Lock
def set_openai_api_key(api_key: str):
"""Set the api key and return chain.
If no api_key, then None is returned.
"""
if api_key:
os.environ["OPENAI_API_KEY"] = api_key
chain = get_chain(vectorstore)
return chain
class ChatWrapper:
def __init__(self):
self.lock = Lock()
def __call__(
self, api_key: str, inp: str, history: Optional[Tuple[str, str]], chain
):
"""Execute the chat functionality."""
self.lock.acquire()
try:
history = history or []
# If chain is None, that is because no API key was provided.
if chain is None:
history.append((inp, "Please paste your OpenAI key to use"))
return history, history
# Set OpenAI key
import openai
openai.api_key = api_key
# Run chain and append input.
output = chain({"question": inp, "chat_history": history})["answer"]
history.append((inp, output))
except Exception as e:
raise e
finally:
self.lock.release()
return history, history
chat = ChatWrapper()
block = gr.Blocks(css=".gradio-container {background-color: lightgray}")
with block:
with gr.Row():
chatbot = gr.Chatbot()
with gr.Row():
message = gr.Textbox(
label="What's your question?",
placeholder="Ask questions about the most recent state of the union",
lines=1,
)
submit = gr.Button(value="Send", variant="secondary").style(full_width=False)
gr.Examples(
examples=[
"Tell me a story about the bootstrapper's manifesto",
"What are the examples of ",
"What was his stance on Ukraine",
],
inputs=message,
)
gr.HTML("Demo application of a LangChain chain.")
gr.HTML(
"<center>Powered by <a href='https://github.com/hwchase17/langchain'>LangChain πŸ¦œοΈπŸ”—</a></center>"
)
state = gr.State()
agent_state = gr.State()
submit.click(chat, inputs=['OPENAI_API_KEY', message, state, agent_state], outputs=[chatbot, state])
message.submit(chat, inputs=["OPENAI_API_KEY", message, state, agent_state], outputs=[chatbot, state])
block.launch(debug=True)