-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
app.py
197 lines (152 loc) · 5.86 KB
/
app.py
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
from langchain.cache import InMemoryCache
import langchain
from flask import Flask, send_from_directory, request, render_template
import sys
from langchain.chains import LLMChain
from langchain.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
from langchain.prompts import FewShotPromptTemplate
from langchain import OpenAI, PromptTemplate
from utils.chat_agent import ChatAgent
import logging
import json
import re
import os
langchain.llm_cache = InMemoryCache()
logger = logging.getLogger()
app = Flask(__name__, template_folder='vite/dist')
app.config.from_object(__name__)
if __name__ == '__main__':
app.run(debug=True)
@app.route('/write')
def root():
return send_from_directory('vite/dist', 'write.html')
@app.route('/')
@app.route('/chat/<id>')
def howdoi(id=None):
# return send_from_directory('./vite/dist', 'howdoi.html')
if id is None:
return render_template('howdoi.html')
# Path for the rest of the static files (JS/CSS)
@app.route('/<path:path>')
def assets(path):
return send_from_directory('./vite/dist', path)
@app.route('/editor', methods=['POST', 'GET'])
def prompt():
prompt = request.get_json(force=True)
# print the prompt to the console
print(prompt)
input = prompt.get('prompt')
instruction = prompt.get('instruction')
operation = prompt.get('operation')
llm = OpenAI(temperature=.5)
f = open('experiments/examples-generated.json')
examples = json.load(f)
example_prompt = PromptTemplate(
input_variables=["document", "operation", "instruction",
"thought", "action", "edited_document", "output"],
template="Document: {document}\nOperation: {operation}\nInstruction: {instruction}\nThought: {thought}\nAction: {action}\nEdited Document: {edited_document}\nOutput: {output}",
)
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples,
OpenAIEmbeddings(),
FAISS,
k=1
)
prompt_prefix = """
You are an AI writing assistant. You can help make additions and updates to a wide variety of documents.
Edit the document below to complete the task. If you can't complete the task, say "ERROR: I'm sorry, I can't help with this."
You should follow this format:
Document: this is the original document.
Operation: this is the operation the user wants you to perform.
Instruction: this is the instruction given by the user. Use this to guide the Operation.\
Thought: You should always think about what to do.
Action: this is the action you need to take to complete this task. Should be one of [insert, remove, update, expand, or condense].
Edited Document: The document after you have applied the action to the Action Target.
Output: Just the changed/new portion of the document (the difference between the Edited Document and the original Document). This is what you need to return.
"""
similar_prompt = FewShotPromptTemplate(
# We provide an ExampleSelector instead of examples.
example_selector=example_selector,
example_prompt=example_prompt,
prefix=prompt_prefix + "\nFor example:\n",
suffix="###\n\nDocument: {input}\nOperation: {operation}\nInstruction: {instruction}\nThought:",
input_variables=["input", "instruction", "operation"],
)
zero_shot_template = prompt_prefix + """
###
Document: {input}
Operation: {operation}
Instruction: {instruction}
Thought:
"""
zero_shot_prompt = PromptTemplate(
template=zero_shot_template,
input_variables=["input", "instruction", "operation"],
)
chain = LLMChain(llm=llm, prompt=similar_prompt, verbose=True)
# chain = LLMChain(llm=llm, prompt=zero_shot_prompt, verbose=True)
# add a try except block to catch errors
try:
completion = chain.predict(
input=input, instruction=instruction, operation=operation)
except:
completion = "I'm sorry, I can't help with this."
# # import betterprompt
# # perplexity = betterprompt.calculate_perplexity(similar_prompt.format(
# # input=input, instruction=instruction, operation=operation))
# print("\nPerplexity: ", 'blue')
# print(perplexity, 'blue')
# print('\n', 'blue')
print(completion)
# check if the last line of completion starts with Output:
if completion.split('\n')[-1].startswith("Output:"):
# if so, remove the Output: prefix
output = completion.split("Output:")[1].strip()
status = 200
else:
# otherwise, return the completion as is
output = completion
status = 500
return {
'input': input,
'text': output
}, status
@ app.route('/chat', methods=['POST', 'GET'])
def chat():
json = request.get_json(force=True)
history_array = json.get('history')
input = json.get('prompt')
print("\n\n#### INPUT ####\n")
print(input)
print("\n\n#### INPUT ####\n")
chat_agent = ChatAgent(history_array=history_array)
try:
reply = chat_agent.agent_executor.run(input=input)
except ValueError as inst:
print('ValueError:\n')
import traceback
trace = str(traceback.format_exc())
print(inst)
print(trace)
reply = "Sorry, there was an error processing your request."
print("\n\n#### REPLY ####\n")
print(reply)
print("\n\n#### REPLY ####\n")
pattern = r'\(([a-z]{2}-[A-Z]{2})\)'
# Search for the local pattern in the string
match = re.search(pattern, reply)
language = 'en-US' # defaut
if match:
# Get the language code
language = match.group(1)
# Remove the language code from the reply
reply = re.sub(pattern, '', reply)
print("LANG: ", language)
sys.stdout.flush()
return {
'input': input,
'text': reply.strip(),
'language': language
}