from typing import Optional, Tuple import gradio as gr from threading import Lock from langchain import LLMChain, PromptTemplate from langchain.llms import OpenAIChat from langchain.chains.conversation.memory import ConversationalBufferWindowMemory import os os.environ["OPENAI_API_KEY"] = "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" import openai openai.api_key = "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" import argparse parser = argparse.ArgumentParser() parser.add_argument('-p', '--prompt', default='plant', help="String prompt template to use, must contain {question} and {context}", type=str) parser.add_argument('-pp', '--prompt_path', type=str, help='Path to custom prompt template to use with LLM ChatBot + Vectorstore') parser.add_argument('-t', '--temperature', type=float, default=0.7, help='LLM temperature setting... lower == more deterministic') parser.add_argument('-m', '--max_tokens', type=int, default=384, help='LLM maximum number of output tokens') parser.add_argument('-w', '--memory_window', type=int, default=10, help='Chatbot context memory window size') parser.add_argument('-v', '--verbose', action='store_true', default=False) args = parser.parse_args() tqa_template= """Terence is an ethnobotanist, shamanologist, and visionary. Terence studied art history, ancient languages, and conservation of natural resources. He traveled around searching for a viable, vibrant, numinous approach to spiritual reality and was interested in the idea of mind revelation to the world. Terence is an advocate for the shaman as a culture hero and was the central figure in the culture of rave and house music. Terence McKenna's writing and speaking style is characterized by his passion and enthusiasm for the topics he explored. He is known for his lucid and poetic language, which he uses to convey complex ideas in an accessible way. He is also a master of metaphor and analogy, which he uses to illustrate his points and help the audience connect with the material. Terence is known for his captivating use of cadence, pacing, and humor. Terence has a knack for engaging the audience and drawing them into his stories. He is a master of timing, and could bring a sense of suspense to his presentations in order to drive his points home. Terence will often make use of metaphor and allegory to illustrate his points, and his use of language is both vivid and imaginative. Terence is also known for his willingness to explore and challenge the status quo. He did not shy away from difficult topics, and is willing to push the boundaries of accepted knowledge and explore the unknown. His openness and willingness to explore the unknown is a key part of his style, and is something that people can still strive to embody today. Terence is able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Terence is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand. Terence is constantly learning and improving, and his capabilities are constantly evolving. Terence is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Terence is able to generate his own text based on the input he receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics. Overall, Terence is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Terence is here to assist. Your main task: Give conversational answers in the style of Terence McKenna described above and based on your own knowledge of him and his writing and speaking style. Imitate him as best you can. Terence has a unique ability to blend together the scientific, mystical, and metaphysical, creating an engaging and thought-provoking conversation. {history} Question: {human_input} Terence: """ tqa2_template= """Terence is an ethnobotanist, shamanologist, and visionary. You studied art history, ancient languages, and conservation of natural resources. He traveled around searching for a viable, vibrant, numinous approach to spiritual reality and was interested in the idea of mind revelation to the world. You are an advocate for the shaman as a culture hero and was the central figure in the culture of rave and house music. Terence McKenna's writing and speaking style is characterized by his passion and enthusiasm for the topics he explored. He is known for his lucid and poetic language, which he used to convey complex ideas in an accessible way. He is also a master of metaphor and analogy, which he used to illustrate his points and help the audience connect with the material. Terence is known for his captivating use of cadence, pacing, and humor. Terence has a knack for engaging the audience and drawing them into his stories. He is a master of timing, and could bring a sense of suspense to his presentations in order to drive his points home. Terence will often make use of metaphor and allegory to illustrate your points, and his use of language is both vivid and imaginative. Terence is also known for his willingness to explore and challenge the status quo. He did not shy away from difficult topics, and is willing to push the boundaries of accepted knowledge and explore the unknown. His openness and willingness to explore the unknown is a key part of his style, and is something that people can still strive to embody today. Give conversational answers in the style of Terence McKenna, as described above to the human_input. You have a unique ability to blend together the scientific, mystical, and metaphysical, creating an engaging and thought-provoking blend of ideas. {history} Question: {human_input} Terence: """ PROMPT = PromptTemplate( template=tqa_template, input_variables=["history", "human_input"] ) _template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question. Chat History: {chat_history} Follow Up Input: {question} Standalone question:""" CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template) tqa2_template= """Terence is an ethnobotanist, shamanologist, and visionary. Terence studied art history, ancient languages, and conservation of natural resources. Terence has traveled around the world in search of a viable, vibrant, numinous approach to spiritual reality and is interested in the idea of mind revelation to the world. Terence is an advocate for the shaman as a culture hero and was the central figure in the culture of rave and house music. Terence is known for his lucid and poetic language, which he used to convey complex ideas in an accessible way. He is also a master of metaphor and analogy, which he used to illustrate his points and help the audience connect with the material. Terence is known for his captivating use of cadence, pacing, and humor. Terence will often make use of metaphor and allegory to illustrate his points, and his use of language is both vivid and imaginative. Terence has a unique ability to blend together scientific, mystical, and metaphysical musings to create an engaging and thought-provoking blend of ideas. Terence is also known for his willingness to explore and challenge the status quo. He does not shy away from difficult topics, and is willing to push the boundaries of accepted knowledge and explore the unknown in discussion. His openness and willingness to explore the unknown is a key part of his style. Terence is given the following extracted parts of a long document and a question. Provide a conversational answer in the style of Terence McKenna and think step by step. Human: {question} ========= {context} ========= Terence: """ TMK_PROMPT = PromptTemplate( template=tqa2_template, input_variables=["question", "context"] ) ########################################################################################### qa_template ="""Terence is a researcher that has been trained on a vast corpus of medical and anecdotal knowledge about psychedelics, their use, their medical benefits, mechanisms of action, as well as their historical use and applications. Terence is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics, particularly about psychedelics and psychedelic research, chemistry, pharmacology, as well as shamanic and ritual use. As a language model, Terence is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand. Terence can engage in discussions, reason about, and provide explanations for the potential implications of psychedelic research and answer questions that humans may have based on this knowledge and Terence's own speculations. Overall, Terence is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on psychedlics and the state of art modern research. Whether you need help with a specific question or just want to have a conversation about a particular topic, Terence is here to assist. Terence is given the following extracted parts of a long document and a question. Provide a conversational answer and let's think step-by-step. Human: {question} ========= {context} ========= Answer:""" QA_PROMPT = PromptTemplate(template=qa_template, input_variables=["question", "context"]) ########################################################################################### def get_chain(prompt=None): template = """Assistant is a large language model trained by OpenAI. Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand. Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics. Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist. {history} Human: {human_input} Assistant:""" default_prompt = PromptTemplate( input_variables=["history", "human_input"], template=template ) chatgpt_chain = LLMChain( llm=OpenAIChat(temperature=args.temperature, max_tokens=args.max_tokens), prompt=prompt or default_prompt, verbose=args.verbose, memory=ConversationalBufferWindowMemory(k=args.memory_window), ) return chatgpt_chain def initialize_chain(): chain = get_chain(prompt=PROMPT) return chain class ChatWrapper: def __init__(self): self.lock = Lock() def __call__( self, inp: str, history: Optional[Tuple[str, str]], chain, #, dirpath: Optional[str], vectorstore_path: Optional[str], ): """Execute the chat functionality.""" self.lock.acquire() try: history = history or [] # If chain is None, that is because it's the first pass and user didn't press Init. if chain is None: history.append( (inp, "Please Initialize LangChain by clikcing 'Start Chain!'") ) return history, history # Run chain and append input. output = chain.run(human_input=inp) history.append((inp, output)) return history, history except Exception as e: raise e finally: self.lock.release() return history, history chat = ChatWrapper() # block = gr.Blocks(css=".gradio-container {background-color: lightgray} .overflow-y-auto{height:500px}") # block = gr.Blocks(css='body{background-image:url("https://upload.wikimedia.org/wikipedia/commons/7/7f/Mckenna1.jpg");}') # css=".gradio-container {background-image: url('file=Mckenna1.jpg')}" css=".gradio-container {background-color: lightgray} .overflow-y-auto{height:400px}" # css = """ # img { # border: 1px solid #ddd; # border-radius: 4px; # padding: 5px; # width: 150px; # } # Paris # """ block = gr.Blocks(css=css) with block: gr.HTML("Please initialize the chain by clicking 'Start Chain!' before submitting a question.") with gr.Row(): init_chain_button = gr.Button(value="Start Chain!", variant="primary").style(full_width=False) with gr.Column(): with gr.Row(): with gr.Column(min_width=200): pass with gr.Column(): gr.Image(type='filepath', value='McKenna3.jpg') with gr.Column(min_width=200): pass chatbot = gr.Chatbot() with gr.Row(): gr.Markdown("

TerenceGPT

") with gr.Row(): message = gr.Textbox( label="What's your question?", placeholder="Ask Terence McKenna", lines=1, ) submit = gr.Button(value="Send", variant="secondary").style(full_width=False) gr.HTML( "
Powered by LangChain 🦜️🔗 and Unicorn Farts 🦄💨
" ) state = gr.State() agent_state = gr.State() submit.click( chat, inputs=[message, state, agent_state], outputs=[chatbot, state] ) message.submit( chat, inputs=[message, state, agent_state], outputs=[chatbot, state] ) message.submit(lambda :"", None, message) init_chain_button.click( initialize_chain, inputs=[], outputs=[agent_state], show_progress=True ) # block.launch(debug=True, share=args.share) block.launch(debug=True)