File size: 15,024 Bytes
a2e7a6d
 
 
 
 
2787ed2
 
 
a2e7a6d
 
bca43c4
a2e7a6d
290c3b8
 
a2e7a6d
 
 
 
 
 
 
3573bf1
 
a2e7a6d
 
 
2787ed2
231aad2
2787ed2
231aad2
2787ed2
231aad2
2787ed2
 
 
231aad2
2787ed2
231aad2
2787ed2
 
 
231aad2
2787ed2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2e7a6d
 
 
 
 
 
 
 
 
 
 
2787ed2
a2e7a6d
2787ed2
a2e7a6d
2787ed2
a2e7a6d
2787ed2
a2e7a6d
2787ed2
a2e7a6d
2787ed2
 
 
 
 
 
a2e7a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2787ed2
a2e7a6d
 
 
 
 
 
 
 
 
 
2787ed2
a2e7a6d
2787ed2
a2e7a6d
2787ed2
a2e7a6d
2787ed2
a2e7a6d
2787ed2
a2e7a6d
2787ed2
 
 
a2e7a6d
2787ed2
 
 
a2e7a6d
 
2787ed2
3573bf1
2787ed2
3573bf1
 
2787ed2
a2e7a6d
2787ed2
a2e7a6d
 
 
 
3573bf1
a2e7a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2787ed2
a2e7a6d
 
a0643c4
 
a2e7a6d
 
 
 
 
 
 
 
 
 
 
 
 
2787ed2
 
 
 
 
 
 
 
 
 
 
 
a2e7a6d
 
 
4d4fc57
 
 
 
 
231aad2
 
 
 
 
 
 
 
 
aa6fd31
a2e7a6d
4d4fc57
 
a2e7a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73d9f07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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;
# }

# <img src="paris.jpg" alt="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("<h3><center>TerenceGPT</center></h3>")

    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(
        "<center>Powered by <a href='https://github.com/hwchase17/langchain'>LangChain πŸ¦œοΈπŸ”— and Unicorn Farts πŸ¦„πŸ’¨</a></center>"
    )

    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)