-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
200 lines (178 loc) · 9 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
198
199
200
import json
import math
import os
import asyncio
import aiohttp
import time
import re as r
from datetime import datetime
from abc import abstractmethod
from typing import List
import httpx
import openai
from sympy import *
from dotenv import load_dotenv
load_dotenv()
from wp_debugger import debug #can be replaced by print()
#Add this Keys to your .env
openai.api_key = os.getenv('OPENAI_API_KEY')
if os.getenv('OPENAI_API_BASE'): openai.api_base = os.getenv('OPENAI_API_BASE') #only for azure endpoints
SERPAPI_KEY = os.getenv('SERPAPI_API_KEY') #you can use Analog Search Engine (find below)
OPENAI_MODEL = os.getenv('OPENAI_MODEL')
# --------------------- History Manager --------------------- #
class HistoryManager:
def __init__(self):
self._history = []
@property
def history(self) -> List[dict[str, str, int]]: #role, content, tokens length
return self._history
@property
def dict_to_history(self) -> List[dict[str, str]]:
return [{k: d[k] for k in ['role','content'] if k in d} for d in self._history]
def get_total_tokens(self) -> int:
return sum(key['tokens'] for key in self.history)
def add_to_history(self, info: List[dict[str, str, int]]):
if isinstance(info, dict): self._history.append(info)
else: raise TypeError('Expected dictionary')
def trim_history(self):
sum_tokens = self.get_total_tokens()
if sum_tokens >= 4096:
while sum_tokens >= 4096:
tokens = self._history[0]['tokens']
sum_tokens -= int(tokens)
del self._history[0]
print(f'[TOOL] History is pruned to {str(sum_tokens)} tokens')
# --------------------- Utils Handlers --------------------- #
class Utils:
@staticmethod
def get_value(string, startswith):
return next((line[len(startswith):] for line in string.split('\n') if line.startswith(startswith)), None)
def prepare(text):
return '\n'.join(line for line in text.split('\n') if line.strip())
last_request_time = datetime.min
def timeout(THRESHOLD_SECONDS):
time_diff = (datetime.now() - Utils.last_request_time).total_seconds()
if time_diff < THRESHOLD_SECONDS: time.sleep(THRESHOLD_SECONDS - time_diff)
Utils.last_request_time = datetime.now()
class OpenAIUtils:
@staticmethod
async def request_openai(prompt:str, historyHook:bool, template:str = '', model:str = '') -> str:
if not model: model = OPENAI_MODEL
Utils.timeout(20)
data = history_manager.dict_to_history if historyHook else []
if template: data.append({'role': 'system', 'content': template})
data.append({'role': 'user', 'content': prompt})
try:
response = openai.ChatCompletion.create(
model=model,
messages=data,
temperature=0.7,
stream=False,
stop=['Tool Result:']
)
model = response.model
p_tokens = response.usage.prompt_tokens-319
data = {
'p_tokens': p_tokens,
'c_tokens': response.usage.completion_tokens,
'content': response.choices[0].message.content
}
return data
except openai.error.APIError as e:
if hasattr(e, 'response') and 'detail' in e.response: error_message = e.response['detail']
else: error_message = str(e)
print(error_message)
# --------------------- AITools Handlers --------------------- #
class Tool:
description: str
@abstractmethod
async def execute(self, input:str):
pass
class Expert(Tool):
description = "Useful for answering any questions and completing tasks. The input to this tool should be a question provide full information and can't be None."
async def execute(self, input:str) -> str:
debug(f'[TOOL] Expert: {input}')
data = await OpenAIUtils.request_openai(f"Question: {input}\nSkeleton:", True, sot_skeletonTemplate)
skeleton = Utils.prepare(data['content'])
debug(f'[TOOL] Expert Skeleton: {skeleton}')
data = await OpenAIUtils.request_openai('Write a text based on the Skeleton points provided. Write each point **very briefly** in 1∼3 sentences as best you can. End with a final conclusion if required.', True, sot_resultTemplate.replace("${question}", input).replace("${skeleton}", skeleton))
response = Utils.prepare(data['content'])
debug(f'[TOOL] Expert Response: {response}')
return response
class Calculator(Tool):
description = 'Useful for getting the result of a math expression. Input should be a valid mathematical expression that could be executed by a simple calculator.'
async def execute(self, input:str) -> str:
if '=' in input: input = input.split('=')[1]
parse = str(parse_expr(r.sub(r"[^0-9\-+=/:.,*]", "", input)))
result = eval(parse)
debug(f'[TOOL] Calculation: {input} = {result}')
return result
# SerpAPI Search Engine
class SearchEngine(Tool):
description = 'a search engine. Useful for when you need to answer questions about current events. Input should be a search query.'
async def execute(self, input:str) -> str:
debug(f'[TOOL] Search: {input}')
params = {'api_key': SERPAPI_KEY,'q': input}
async with httpx.AsyncClient() as client: response = await client.get('https://serpapi.com/search', params=params)
return response.json().get('answer_box', {}).get('answer') or response.json().get('answer_box', {}).get('snippet') or response.json().get('organic_results', [{}])[0].get('snippet')
# # Analog Search Engine
# class SearchEngine(Tool):
# description = 'a search engine. Useful for when you need to answer questions about current events. input should be a search query.'
# async def analogSearch(self, input: str) -> str:
# debug(f'[TOOL] Search: {input}')
# async with httpx.AsyncClient() as client:
# response = await client.get('https://ddg-api.herokuapp.com/search', params={'query': input, 'region': 'ru-ru', 'limit': 3})
# blob = '\n\n'.join([f'[{index+1}] \'{result['snippet']}\'' for index, result in enumerate(response.json())])
# return blob
# --------------------- Main --------------------- #
class QuestionAssistant:
def __init__(self, history_manager: HistoryManager):
self.history_manager = history_manager
self.tools = {
'Expert': Expert(),
'Calculator': Calculator(),
'Search': SearchEngine()
}
async def complete_prompt(self, prompt: str, historyHook: bool = True) -> str:
tools_description = '\n'.join([f'{toolname}: {self.tools[toolname].description}' for toolname in self.tools.keys()])
template = f'Knowledge cutoff: 2021-09-01 Current date: {datetime.now().strftime("%Y-%m-%d")}.\n{promptTemplate.replace("${tools}", tools_description)}'
response = await OpenAIUtils.request_openai(prompt, historyHook, template)
return response
async def answer_question(self, question: str) -> str:
prompt = f'Question: {question}\nThought:'
module_history = ''
while True:
action = ''
data = await QuestionAssistant.complete_prompt(self, prompt)
if 'f_iter' not in locals():
question_tokens = data['p_tokens']
f_iter = True
response = Utils.prepare(data['content'])
len_response = len(response)
if 'Tool: ' in response:
action = Utils.get_value(response, 'Tool: ')
if action in self.tools.keys():
actionInput = Utils.get_value(response, 'Tool Input: ')
response = response.split('Tool Result:')[0]
if 'Final Answer:' in response:
result = response.split('Final Answer:')[-1].strip()
answer_tokens = math.ceil(data['c_tokens'] * (len(result) / len_response))
history_manager.add_to_history({'role': 'user','content': question, 'tokens': question_tokens})
history_manager.add_to_history({'role': 'assistant','content': result, 'tokens': answer_tokens})
history_manager.trim_history()
return f'assistant{module_history}: {result}'
prompt += '\n' + response
if action in self.tools.keys():
module_history += f'[{action}]'
result = await self.tools[action].execute(actionInput)
prompt += f'\nTool Result: {result}\nThought: '
prompt = Utils.prepare(prompt)
promptTemplate = open('prompts/prompt.txt', 'r').read()
sot_skeletonTemplate = open('prompts/sot_skeleton.txt', 'r').read()
sot_resultTemplate = open('prompts/sot_result.txt', 'r').read()
history_manager = HistoryManager()
assistant = QuestionAssistant(history_manager)
while True:
question = input('user: ')
answer = asyncio.run(assistant.answer_question(question))
print(answer)