Spaces:
Sleeping
Sleeping
Update app.py
Browse filesagent inputs looping
app.py
CHANGED
|
@@ -17,14 +17,16 @@ from urllib.parse import quote
|
|
| 17 |
from multiprocessing import context
|
| 18 |
# from agents.tool import WebSearchTool
|
| 19 |
from typing_extensions import TypedDict, Any
|
| 20 |
-
from agents import Agent, FunctionTool, ImageGenerationTool, RunContextWrapper, Runner, function_tool,
|
|
|
|
| 21 |
from markdown_pdf import MarkdownPdf
|
| 22 |
from markdown_pdf import Section
|
|
|
|
| 23 |
import brave
|
| 24 |
import geo_distance
|
| 25 |
|
| 26 |
load_dotenv(override=True)
|
| 27 |
-
|
| 28 |
users = os.getenv('LOGNAME')
|
| 29 |
unames = users.split(',')
|
| 30 |
pwds = os.getenv('PASSWORD')
|
|
@@ -45,6 +47,9 @@ LOCATIONID_KEY=os.getenv('LOCATIONID_KEY')
|
|
| 45 |
# dp.mkdir(exist_ok=True)
|
| 46 |
# dataDir = '/data/'
|
| 47 |
|
|
|
|
|
|
|
|
|
|
| 48 |
@function_tool
|
| 49 |
async def make_pdf(text: str, title: str)->str:
|
| 50 |
'''Creates a pdf document based on input markdown text and title string.
|
|
@@ -109,6 +114,12 @@ async def get_distance(addr1: str, addr2: str)->float:
|
|
| 109 |
distance = geo_distance.great_circle_distance_miles(lat1, lon1, lat2, lon2)
|
| 110 |
return distance
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
def md(txt):
|
| 114 |
return str(txt).replace('```', ' ').replace(' ', ' ').replace(' ', ' ').replace(' ', ' ').replace('\n','<br>').replace('~~','~')
|
|
@@ -136,11 +147,17 @@ def updatePassword(pwd, user):
|
|
| 136 |
pwd = pwd.lower().strip()
|
| 137 |
if pwd == pwd_list[unames.index(user)]:
|
| 138 |
password = pwd
|
| 139 |
-
return [password, "*********"
|
|
|
|
|
|
|
| 140 |
else:
|
| 141 |
-
return [password, "invalid password"
|
|
|
|
|
|
|
| 142 |
else:
|
| 143 |
-
return [password, "invalid user"
|
|
|
|
|
|
|
| 144 |
|
| 145 |
def update_user(user_win):
|
| 146 |
user_win = user_win.lower().strip()
|
|
@@ -155,7 +172,7 @@ def credentials_ok(user, pwd):
|
|
| 155 |
return user in unames and pwd in pwd_list
|
| 156 |
|
| 157 |
def clean_up_files():
|
| 158 |
-
for file in glob('./document
|
| 159 |
try:
|
| 160 |
os.remove(file)
|
| 161 |
except:
|
|
@@ -166,31 +183,77 @@ def clean_up_files():
|
|
| 166 |
except:
|
| 167 |
pass
|
| 168 |
|
| 169 |
-
def load_image(image, user):
|
| 170 |
-
status = 'OK, image is ready! Enter prompt and tap submit button'
|
| 171 |
try:
|
| 172 |
with open(image, 'rb') as image_file:
|
| 173 |
base64_image = base64.b64encode(image_file.read()).decode('utf-8')
|
| 174 |
fpath = user + '_image.b64'
|
| 175 |
with open(fpath, 'wt') as fp:
|
| 176 |
fp.write(base64_image)
|
|
|
|
| 177 |
except:
|
| 178 |
-
|
| 179 |
-
return [fpath,
|
| 180 |
|
| 181 |
-
def upload_image(user, password):
|
| 182 |
if not credentials_ok(user, password):
|
| 183 |
return [gr.Image(visible=False, interactive=True), "Incorrect user name and/or password"]
|
| 184 |
-
return [gr.Image(visible=True, interactive=True),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
async def chat(prompt_window, user_window, password, history, output_window,
|
| 187 |
-
uploaded_image_file):
|
| 188 |
file_download = gr.DownloadButton(label='Download File', visible=False, value=None)
|
| 189 |
image_window = gr.Image(visible=False, value=None)
|
| 190 |
|
| 191 |
if not credentials_ok(user_window, password):
|
| 192 |
return ['Invalid Credentials', prompt_window, uploaded_image_file,
|
| 193 |
-
image_window, file_download, history]
|
| 194 |
instructions = '''
|
| 195 |
You are a helpful assistant.
|
| 196 |
You can call tools to compute straight-line distances and to search the web for
|
|
@@ -200,17 +263,58 @@ async def chat(prompt_window, user_window, password, history, output_window,
|
|
| 200 |
straight-line distance by default, and when possible use street addresses for locations.
|
| 201 |
'''
|
| 202 |
|
|
|
|
|
|
|
|
|
|
| 203 |
agent = Agent(name="Assistant",
|
| 204 |
instructions=instructions,
|
| 205 |
-
tools=[get_distance, search_web, get_news,
|
|
|
|
| 206 |
ImageGenerationTool(tool_config={"type": "image_generation", "quality": "low"},)],)
|
| 207 |
|
| 208 |
response = output_window
|
| 209 |
if not response:
|
| 210 |
response = ''
|
| 211 |
prompt = prompt_window
|
| 212 |
-
history.
|
| 213 |
-
inputs =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
image_input = ''
|
| 215 |
if uploaded_image_file != '':
|
| 216 |
with open(uploaded_image_file, 'rt') as fp:
|
|
@@ -229,42 +333,110 @@ async def chat(prompt_window, user_window, password, history, output_window,
|
|
| 229 |
}
|
| 230 |
)
|
| 231 |
inputs.append(image_input)
|
| 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 |
# outputs=[history, output_window, prompt_window, uploaded_image_file,
|
| 259 |
# image_window, file_download])
|
| 260 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
def new_session(user_window, history):
|
| 262 |
history = []
|
| 263 |
return [prompt_window, history, 'Session cleared',
|
| 264 |
gr.Image(visible=False, value=None),
|
| 265 |
gr.Image(visible=False, value=None), '',
|
| 266 |
gr.DownloadButton(label='Download File', visible=False, value=None),
|
| 267 |
-
gr.File(visible=False, label='Upload File', type='filepath')]
|
| 268 |
|
| 269 |
|
| 270 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
@@ -273,6 +445,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 273 |
uploaded_image_file = gr.State('')
|
| 274 |
uploaded_file_path = gr.State('')
|
| 275 |
history = gr.State([])
|
|
|
|
| 276 |
|
| 277 |
gr.Markdown('# GPT Agent')
|
| 278 |
gr.Markdown('Enter user name & password. Tap "Help & Hints" button for more instructions.')
|
|
@@ -283,9 +456,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 283 |
help_button = gr.Button(value='Help & Hints')
|
| 284 |
with gr.Row():
|
| 285 |
clear_button = gr.Button(value="Start New Session")
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
button_get_image = gr.Button(value='Upload Image to Analyze')
|
| 289 |
submit_button = gr.Button(value="Submit Prompt/Question")
|
| 290 |
with gr.Row():
|
| 291 |
prompt_window = gr.Textbox(label = "Prompt or Question", scale=7)
|
|
@@ -302,21 +474,25 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 302 |
file_uploader = gr.File(visible=False, label='Upload File', type='filepath')
|
| 303 |
submit_button.click(chat,
|
| 304 |
inputs=[prompt_window, user_window, password, history, output_window,
|
| 305 |
-
uploaded_image_file],
|
| 306 |
outputs=[output_window, prompt_window, uploaded_image_file,
|
| 307 |
-
image_window, file_download, history])
|
| 308 |
clear_button.click(fn=new_session, inputs=[user_window, history],
|
| 309 |
-
outputs=[prompt_window, history, output_window,
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
button_get_image.click(fn=upload_image,inputs = [user, password],
|
| 314 |
outputs = [image_window2, output_window])
|
| 315 |
-
image_window2.upload(fn=load_image, inputs=[image_window2, user
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
# demo.launch(share=True, allowed_paths=[dataDir], ssr_mode=False)
|
| 321 |
# demo.load(delete_db_files)
|
| 322 |
demo.unload(clean_up_files)
|
|
|
|
| 17 |
from multiprocessing import context
|
| 18 |
# from agents.tool import WebSearchTool
|
| 19 |
from typing_extensions import TypedDict, Any
|
| 20 |
+
from agents import Agent, FunctionTool, ImageGenerationTool, RunContextWrapper, Runner, function_tool, CodeInterpreterTool
|
| 21 |
+
from openai import OpenAI
|
| 22 |
from markdown_pdf import MarkdownPdf
|
| 23 |
from markdown_pdf import Section
|
| 24 |
+
from docx import Document
|
| 25 |
import brave
|
| 26 |
import geo_distance
|
| 27 |
|
| 28 |
load_dotenv(override=True)
|
| 29 |
+
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
|
| 30 |
users = os.getenv('LOGNAME')
|
| 31 |
unames = users.split(',')
|
| 32 |
pwds = os.getenv('PASSWORD')
|
|
|
|
| 47 |
# dp.mkdir(exist_ok=True)
|
| 48 |
# dataDir = '/data/'
|
| 49 |
|
| 50 |
+
# mimes = {'pdf': 'application/pdf', 'txt': 'text/plain',
|
| 51 |
+
# 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}
|
| 52 |
+
|
| 53 |
@function_tool
|
| 54 |
async def make_pdf(text: str, title: str)->str:
|
| 55 |
'''Creates a pdf document based on input markdown text and title string.
|
|
|
|
| 114 |
distance = geo_distance.great_circle_distance_miles(lat1, lon1, lat2, lon2)
|
| 115 |
return distance
|
| 116 |
|
| 117 |
+
def extract_text_from_docx(file_path):
|
| 118 |
+
doc = Document(file_path)
|
| 119 |
+
text = []
|
| 120 |
+
for paragraph in doc.paragraphs:
|
| 121 |
+
text.append(paragraph.text)
|
| 122 |
+
return "\n".join(text)
|
| 123 |
|
| 124 |
def md(txt):
|
| 125 |
return str(txt).replace('```', ' ').replace(' ', ' ').replace(' ', ' ').replace(' ', ' ').replace('\n','<br>').replace('~~','~')
|
|
|
|
| 147 |
pwd = pwd.lower().strip()
|
| 148 |
if pwd == pwd_list[unames.index(user)]:
|
| 149 |
password = pwd
|
| 150 |
+
return [password, "*********",
|
| 151 |
+
gr.Button(value='Upload Input File', interactive=True),
|
| 152 |
+
gr.Button(value='Upload Image to Analyze', interactive=True)]
|
| 153 |
else:
|
| 154 |
+
return [password, "invalid password",
|
| 155 |
+
gr.Button(value='Upload Input File', interactive=False),
|
| 156 |
+
gr.Button(value='Upload Image to Analyze', interactive=False)]
|
| 157 |
else:
|
| 158 |
+
return [password, "invalid user",
|
| 159 |
+
gr.Button(value='Upload Input File', interactive=False),
|
| 160 |
+
gr.Button(value='Upload Image to Analyze', interactive=False)]
|
| 161 |
|
| 162 |
def update_user(user_win):
|
| 163 |
user_win = user_win.lower().strip()
|
|
|
|
| 172 |
return user in unames and pwd in pwd_list
|
| 173 |
|
| 174 |
def clean_up_files():
|
| 175 |
+
for file in glob('./document.*'):
|
| 176 |
try:
|
| 177 |
os.remove(file)
|
| 178 |
except:
|
|
|
|
| 183 |
except:
|
| 184 |
pass
|
| 185 |
|
| 186 |
+
def load_image(image, user, output_window):
|
| 187 |
+
# status = #'OK, image is ready! Enter prompt and tap submit button'
|
| 188 |
try:
|
| 189 |
with open(image, 'rb') as image_file:
|
| 190 |
base64_image = base64.b64encode(image_file.read()).decode('utf-8')
|
| 191 |
fpath = user + '_image.b64'
|
| 192 |
with open(fpath, 'wt') as fp:
|
| 193 |
fp.write(base64_image)
|
| 194 |
+
output_window += md('\nImage loaded\n')
|
| 195 |
except:
|
| 196 |
+
output_window = 'Unable to upload image'
|
| 197 |
+
return [fpath, output_window]
|
| 198 |
|
| 199 |
+
def upload_image(user, password, output_window):
|
| 200 |
if not credentials_ok(user, password):
|
| 201 |
return [gr.Image(visible=False, interactive=True), "Incorrect user name and/or password"]
|
| 202 |
+
return [gr.Image(visible=True, interactive=True), output_window]
|
| 203 |
+
|
| 204 |
+
def upload_file(user, password, output_window):
|
| 205 |
+
if not credentials_ok(user, password):
|
| 206 |
+
return [gr.File(visible=False, label='Upload File'), 'Incorrect user and/or password']
|
| 207 |
+
return [gr.File(visible=True, label='UploadFile'), output_window]
|
| 208 |
+
|
| 209 |
+
def load_file(file_uploader, output_window):
|
| 210 |
+
path = file_uploader
|
| 211 |
+
fname = os.path.basename(path)
|
| 212 |
+
return [path, output_window + f'<BR>{fname} loaded<BR>',
|
| 213 |
+
gr.File(visible=False, label='Upload File', type='filepath', value=None) ]
|
| 214 |
+
|
| 215 |
+
def create_openai_container(name):
|
| 216 |
+
url = 'https://api.openai.com/v1/containers'
|
| 217 |
+
headers= {"Authorization": "Bearer " + OPENAI_API_KEY, "Content-Type": "application/json",}
|
| 218 |
+
json_data = {"name": name}
|
| 219 |
+
|
| 220 |
+
response = requests.post(
|
| 221 |
+
url,
|
| 222 |
+
headers=headers,
|
| 223 |
+
json=json_data
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
return json.loads(response.content)["id"]
|
| 227 |
+
|
| 228 |
+
def get_openai_file(file_id, container_id):
|
| 229 |
+
url = f'https://api.openai.com/v1/containers/{container_id}/files/{file_id}/content'
|
| 230 |
+
headers= {"Authorization": "Bearer " + OPENAI_API_KEY}
|
| 231 |
+
|
| 232 |
+
response = requests.get(
|
| 233 |
+
url,
|
| 234 |
+
headers=headers
|
| 235 |
+
)
|
| 236 |
+
return response
|
| 237 |
+
|
| 238 |
+
def list_openai_container_files(container_id):
|
| 239 |
+
url = f'https://api.openai.com/v1/containers/{container_id}/files'
|
| 240 |
+
headers= {"Authorization": "Bearer " + OPENAI_API_KEY}
|
| 241 |
+
|
| 242 |
+
response = requests.get(
|
| 243 |
+
url,
|
| 244 |
+
headers=headers
|
| 245 |
+
)
|
| 246 |
+
return response
|
| 247 |
+
|
| 248 |
|
| 249 |
async def chat(prompt_window, user_window, password, history, output_window,
|
| 250 |
+
uploaded_image_file, uploaded_file_path, prior_inputs):
|
| 251 |
file_download = gr.DownloadButton(label='Download File', visible=False, value=None)
|
| 252 |
image_window = gr.Image(visible=False, value=None)
|
| 253 |
|
| 254 |
if not credentials_ok(user_window, password):
|
| 255 |
return ['Invalid Credentials', prompt_window, uploaded_image_file,
|
| 256 |
+
image_window, file_download, history, uploaded_file_path, prior_inputs]
|
| 257 |
instructions = '''
|
| 258 |
You are a helpful assistant.
|
| 259 |
You can call tools to compute straight-line distances and to search the web for
|
|
|
|
| 263 |
straight-line distance by default, and when possible use street addresses for locations.
|
| 264 |
'''
|
| 265 |
|
| 266 |
+
|
| 267 |
+
code_container = create_openai_container('my_container')
|
| 268 |
+
|
| 269 |
agent = Agent(name="Assistant",
|
| 270 |
instructions=instructions,
|
| 271 |
+
tools=[get_distance, search_web, get_news,
|
| 272 |
+
CodeInterpreterTool(tool_config={"type": "code_interpreter","container": code_container}), # make_pdf,
|
| 273 |
ImageGenerationTool(tool_config={"type": "image_generation", "quality": "low"},)],)
|
| 274 |
|
| 275 |
response = output_window
|
| 276 |
if not response:
|
| 277 |
response = ''
|
| 278 |
prompt = prompt_window
|
| 279 |
+
# inputs = history.copy()
|
| 280 |
+
inputs = prior_inputs
|
| 281 |
+
file_input = ''
|
| 282 |
+
if uploaded_file_path != '':
|
| 283 |
+
ext = uploaded_file_path.casefold().split('.')[-1]
|
| 284 |
+
if ext == 'pdf':
|
| 285 |
+
client = OpenAI(api_key = OPENAI_API_KEY)
|
| 286 |
+
file = client.files.create(file=open(f'{uploaded_file_path}','rb'),
|
| 287 |
+
purpose='user_data',
|
| 288 |
+
expires_after={"seconds": 3600, "anchor": "created_at"})
|
| 289 |
+
file_input=(
|
| 290 |
+
{"role": "user",
|
| 291 |
+
"content": [
|
| 292 |
+
{
|
| 293 |
+
"type": "input_file",
|
| 294 |
+
"file_id": file.id,
|
| 295 |
+
}
|
| 296 |
+
]
|
| 297 |
+
}
|
| 298 |
+
)
|
| 299 |
+
inputs.append(file_input)
|
| 300 |
+
if ext in ['docx', 'txt', 'py']:
|
| 301 |
+
if ext == 'docx':
|
| 302 |
+
extracted_text = extract_text_from_docx(uploaded_file_path)
|
| 303 |
+
else:
|
| 304 |
+
with open(uploaded_file_path, 'rt') as fp:
|
| 305 |
+
extracted_text = fp.read()
|
| 306 |
+
file_input=(
|
| 307 |
+
{"role": "user",
|
| 308 |
+
"content": [
|
| 309 |
+
{
|
| 310 |
+
"type": "input_text",
|
| 311 |
+
"text": f"{extracted_text}",
|
| 312 |
+
}
|
| 313 |
+
]
|
| 314 |
+
}
|
| 315 |
+
)
|
| 316 |
+
inputs.append(file_input)
|
| 317 |
+
uploaded_file_path == ''
|
| 318 |
image_input = ''
|
| 319 |
if uploaded_image_file != '':
|
| 320 |
with open(uploaded_image_file, 'rt') as fp:
|
|
|
|
| 333 |
}
|
| 334 |
)
|
| 335 |
inputs.append(image_input)
|
| 336 |
+
history.append({"role":"user", "content":prompt})
|
| 337 |
+
inputs.append({"role":"user", "content":prompt})
|
| 338 |
+
exception_msg = ''
|
| 339 |
+
result = None
|
| 340 |
+
try:
|
| 341 |
+
result = await Runner.run(agent, max_turns=20,
|
| 342 |
+
input=inputs)
|
| 343 |
+
for item in result.new_items:
|
| 344 |
+
if (
|
| 345 |
+
item.type == "tool_call_item"
|
| 346 |
+
and item.raw_item.type == "image_generation_call"
|
| 347 |
+
and (img_result := item.raw_item.result)
|
| 348 |
+
):
|
| 349 |
+
image_out_path = f'{user_window}_out.png'
|
| 350 |
+
with open(image_out_path,'wb') as fp:
|
| 351 |
+
fp.write(base64.b64decode(img_result))
|
| 352 |
+
image_window = gr.Image(visible=True, value=image_out_path)
|
| 353 |
+
|
| 354 |
+
reply = md(result.final_output)
|
| 355 |
+
response += "\n\n***YOU***: " + prompt + "\n\n***GPT***: " + reply.replace('```','\n\n```\n\n')
|
| 356 |
+
history.append({"role":"assistant", "content":result.final_output})
|
| 357 |
+
except Exception as e:
|
| 358 |
+
exception_msg = f'Error: {e.message}'
|
| 359 |
+
response += "\n\n***YOU***: " + prompt + "\n\n***GPT***: " + exception_msg
|
| 360 |
+
if result:
|
| 361 |
+
new_inputs = result.to_input_list()
|
| 362 |
+
usage = result.context_wrapper.usage
|
| 363 |
+
response += f"\nTotal tokens: = {usage.total_tokens}"
|
| 364 |
+
loc = result.final_output.find('/mnt/data/')
|
| 365 |
+
if loc > -1:
|
| 366 |
+
ts = result.final_output[loc+10:]
|
| 367 |
+
loc2 = ts.find(')')
|
| 368 |
+
if loc2 > -1:
|
| 369 |
+
fname = ts[:loc2]
|
| 370 |
+
container_list = list_openai_container_files(code_container)
|
| 371 |
+
file_list_json = json.loads(container_list.content)
|
| 372 |
+
latest_file_time = 0
|
| 373 |
+
download_file_id = None
|
| 374 |
+
download_ext = ''
|
| 375 |
+
for item in file_list_json['data']:
|
| 376 |
+
if fname in item["path"]:
|
| 377 |
+
file_time = item["created_at"]
|
| 378 |
+
if file_time > latest_file_time:
|
| 379 |
+
latest_file_time = file_time
|
| 380 |
+
download_file_id = item["id"]
|
| 381 |
+
download_ext = fname.split('.')[-1].casefold()
|
| 382 |
+
if download_file_id:
|
| 383 |
+
fdata = get_openai_file(download_file_id, code_container).content
|
| 384 |
+
with open(f'./document.{download_ext}', 'wb') as fp:
|
| 385 |
+
fp.write(fdata)
|
| 386 |
+
file_download = gr.DownloadButton(label=f'Download {download_ext.upper()} Doc',
|
| 387 |
+
visible=True, value=f'./document.{download_ext}')
|
| 388 |
+
return [response, '', uploaded_image_file, image_window, file_download, history,
|
| 389 |
+
uploaded_file_path, new_inputs]
|
| 390 |
|
| 391 |
# outputs=[history, output_window, prompt_window, uploaded_image_file,
|
| 392 |
# image_window, file_download])
|
| 393 |
|
| 394 |
+
def show_help():
|
| 395 |
+
txt = '''
|
| 396 |
+
This is an agent using the OpenAI Python Agents SDK.
|
| 397 |
+
It has tools to:
|
| 398 |
+
* Search the Web
|
| 399 |
+
* Compute straight-line distances between locations
|
| 400 |
+
* Analyze images you upload.
|
| 401 |
+
* Create and display images you describe, which you can download
|
| 402 |
+
* Get news from the web
|
| 403 |
+
* Make PDF's based on results it generated.
|
| 404 |
+
Agents perform multiple steps using tools as necessary to satisfy a single request.
|
| 405 |
+
|
| 406 |
+
1. Gemeral:
|
| 407 |
+
1.1 Login with user name and password (not case-sensitive)
|
| 408 |
+
1.2 Type prompts (questions, instructions) into "Prompt or Question" window.
|
| 409 |
+
2. Chat:
|
| 410 |
+
2.1 Enter prompt and tap the "Submit Prompt/Question" button. The responses appear in the Dialog window.
|
| 411 |
+
2.2 Enter follow-up questions in the Prompt window. Tap "Submit Prompt/Question".
|
| 412 |
+
2.3 If topic changes or when done chatting, tap the "Start New Session" button.
|
| 413 |
+
3. Make Image:
|
| 414 |
+
3.1 Include description of desired image in prompt window.
|
| 415 |
+
3.2 Tap the "Submit Prompt/Question" button. This can take a few seconds.
|
| 416 |
+
3.3 There is a download button on the image display if your system supports file downloads.
|
| 417 |
+
3.4 When done viewing image, tap the "Start New Session" button
|
| 418 |
+
4. Analyze an Image you provide:
|
| 419 |
+
4.1 Tap the "Upload Image to Analyze" button.
|
| 420 |
+
4.2 An empty image box will appear lower left. Drag or upload image into it. It offers web cam or camera
|
| 421 |
+
input also.
|
| 422 |
+
4.3 The image should appear. This can take some time with a slow internet connection and large image.
|
| 423 |
+
4.4 Enter what you want done with the image in the "Prompt or Question" box.
|
| 424 |
+
4.5 Tap the "Submit Prompt/Question" button to start the analysis. This initiates a chat dialog and
|
| 425 |
+
you can ask follow-up questions. However, the image is not re-analyzed for follow-up dialog.
|
| 426 |
+
Hint:
|
| 427 |
+
Better results are obtained by including detailed descriptions and instructions
|
| 428 |
+
of what you want in the prompt.
|
| 429 |
+
'''
|
| 430 |
+
return str(txt).replace('```', ' ').replace(' ', ' ').replace(' ', ' ').replace(' ', ' ').replace('\n','<br>')
|
| 431 |
+
|
| 432 |
+
|
| 433 |
def new_session(user_window, history):
|
| 434 |
history = []
|
| 435 |
return [prompt_window, history, 'Session cleared',
|
| 436 |
gr.Image(visible=False, value=None),
|
| 437 |
gr.Image(visible=False, value=None), '',
|
| 438 |
gr.DownloadButton(label='Download File', visible=False, value=None),
|
| 439 |
+
gr.File(visible=False, label='Upload File', type='filepath'), [] ]
|
| 440 |
|
| 441 |
|
| 442 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
|
|
| 445 |
uploaded_image_file = gr.State('')
|
| 446 |
uploaded_file_path = gr.State('')
|
| 447 |
history = gr.State([])
|
| 448 |
+
inputs = gr.State([])
|
| 449 |
|
| 450 |
gr.Markdown('# GPT Agent')
|
| 451 |
gr.Markdown('Enter user name & password. Tap "Help & Hints" button for more instructions.')
|
|
|
|
| 456 |
help_button = gr.Button(value='Help & Hints')
|
| 457 |
with gr.Row():
|
| 458 |
clear_button = gr.Button(value="Start New Session")
|
| 459 |
+
button_upload_file = gr.Button(value='Upload Input File', interactive=False)
|
| 460 |
+
button_get_image = gr.Button(value='Upload Image to Analyze', interactive=False)
|
|
|
|
| 461 |
submit_button = gr.Button(value="Submit Prompt/Question")
|
| 462 |
with gr.Row():
|
| 463 |
prompt_window = gr.Textbox(label = "Prompt or Question", scale=7)
|
|
|
|
| 474 |
file_uploader = gr.File(visible=False, label='Upload File', type='filepath')
|
| 475 |
submit_button.click(chat,
|
| 476 |
inputs=[prompt_window, user_window, password, history, output_window,
|
| 477 |
+
uploaded_image_file, uploaded_file_path, inputs],
|
| 478 |
outputs=[output_window, prompt_window, uploaded_image_file,
|
| 479 |
+
image_window, file_download, history, uploaded_file_path, inputs])
|
| 480 |
clear_button.click(fn=new_session, inputs=[user_window, history],
|
| 481 |
+
outputs=[prompt_window, history, output_window,
|
| 482 |
+
image_window, image_window2,
|
| 483 |
+
uploaded_image_file, file_download, file_uploader, inputs])
|
| 484 |
+
help_button.click(fn=show_help, outputs=output_window)
|
| 485 |
+
button_get_image.click(fn=upload_image,inputs = [user, password, output_window],
|
| 486 |
outputs = [image_window2, output_window])
|
| 487 |
+
image_window2.upload(fn=load_image, inputs=[image_window2, user, output_window],
|
| 488 |
+
outputs=[uploaded_image_file, output_window])
|
| 489 |
+
pwd_window.blur(updatePassword,
|
| 490 |
+
inputs = [pwd_window, user],
|
| 491 |
+
outputs = [password, pwd_window, button_upload_file, button_get_image])
|
| 492 |
+
button_upload_file.click(fn=upload_file, inputs=[user, password, output_window],
|
| 493 |
+
outputs=[file_uploader, output_window])
|
| 494 |
+
file_uploader.upload(fn=load_file, inputs=[file_uploader, output_window],
|
| 495 |
+
outputs=[uploaded_file_path, output_window, file_uploader])
|
| 496 |
# demo.launch(share=True, allowed_paths=[dataDir], ssr_mode=False)
|
| 497 |
# demo.load(delete_db_files)
|
| 498 |
demo.unload(clean_up_files)
|