-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
502 lines (478 loc) · 16.9 KB
/
app.py
File metadata and controls
502 lines (478 loc) · 16.9 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# app.py
# /// script
# dependencies = [
# "requests",
# "fastapi",
# "uvicorn",
# "python-dateutil",
# "pandas",
# "db-sqlite3",
# "scipy",
# "pybase64",
# "python-dotenv",
# "httpx",
# "markdown",
# "duckdb"
# ]
# ///
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import PlainTextResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from tasksA import *
from tasksB import *
import requests
from dotenv import load_dotenv
import os
import re
import httpx
import json
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
app = FastAPI()
load_dotenv()
# @app.get('/ask')
# def ask(prompt: str):
# """ Prompt Gemini to generate a response based on the given prompt. """
# gemini_api_key = os.getenv('gemini_api_key')
# if not gemini_api_key:
# return JSONResponse(content={"error": "GEMINI_API_KEY not set"}, status_code=500)
# # Read the contents of tasks.py
# with open('tasks.py', 'r') as file:
# tasks_content = file.read()
# # Prepare the request data
# data = {
# "contents": [{
# "parts": [
# {"text": f"Find the task function from here for the below prompt:\n{tasks_content}\n\nPrompt: {prompt}\n\n respond with the function_name and function_parameters with parameters in json format"},
# ]
# }]
# }
# url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={gemini_api_key}"
# headers = {
# "Content-Type": "application/json"
# }
# response = requests.post(url, json=data, headers=headers)
# if response.status_code == 200:
# text_reponse = response.json()["candidates"][0]["content"]["parts"][0]["text"]
# match = re.search(r'```json\n(.*?)\n```', text_reponse, re.DOTALL)
# text_reponse = match.group(1).strip() if match else text_reponse
# return json.loads(text_reponse)
# # return JSONResponse(content=response.json(), status_code=200)
# else:
# return JSONResponse(content={"error": "Failed to get response", "details": response.text}, status_code=response.status_code)
@app.get("/ask")
def ask(prompt: str):
result = get_completions(prompt)
return result
openai_api_chat = "http://aiproxy.sanand.workers.dev/openai/v1/chat/completions" # for testing
openai_api_key = os.getenv("AIPROXY_TOKEN")
headers = {
"Authorization": f"Bearer {openai_api_key}",
"Content-Type": "application/json",
}
function_definitions_llm = [
{
"name": "A1",
"description": "Run a Python script from a given URL, passing an email as the argument.",
"parameters": {
"type": "object",
"properties": {
# "filename": {"type": "string", "pattern": r"https?://.*\.py"},
# "targetfile": {"type": "string", "pattern": r".*/(.*\.py)"},
"email": {"type": "string", "pattern": r"[\w\.-]+@[\w\.-]+\.\w+"}
},
"required": ["filename", "targetfile", "email"]
}
},
{
"name": "A2",
"description": "Format a markdown file using a specified version of Prettier.",
"parameters": {
"type": "object",
"properties": {
"prettier_version": {"type": "string", "pattern": r"prettier@\d+\.\d+\.\d+"},
"filename": {"type": "string", "pattern": r".*/(.*\.md)"}
},
"required": ["prettier_version", "filename"]
}
},
{
"name": "A3",
"description": "Count the number of occurrences of a specific weekday in a date file.",
"parameters": {
"type": "object",
"properties": {
"filename": {"type": "string", "pattern": r"/data/.*dates.*\.txt"},
"targetfile": {"type": "string", "pattern": r"/data/.*/(.*\.txt)"},
"weekday": {"type": "integer", "pattern": r"(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)"}
},
"required": ["filename", "targetfile", "weekday"]
}
},
{
"name": "A4",
"description": "Sort a JSON contacts file and save the sorted version to a target file.",
"parameters": {
"type": "object",
"properties": {
"filename": {
"type": "string",
"pattern": r".*/(.*\.json)",
},
"targetfile": {
"type": "string",
"pattern": r".*/(.*\.json)",
}
},
"required": ["filename", "targetfile"]
}
},
{
"name": "A5",
"description": "Retrieve the most recent log files from a directory and save their content to an output file.",
"parameters": {
"type": "object",
"properties": {
"log_dir_path": {
"type": "string",
"pattern": r".*/logs",
"default": "/data/logs"
},
"output_file_path": {
"type": "string",
"pattern": r".*/(.*\.txt)",
"default": "/data/logs-recent.txt"
},
"num_files": {
"type": "integer",
"minimum": 1,
"default": 10
}
},
"required": ["log_dir_path", "output_file_path", "num_files"]
}
},
{
"name": "A6",
"description": "Generate an index of documents from a directory and save it as a JSON file.",
"parameters": {
"type": "object",
"properties": {
"doc_dir_path": {
"type": "string",
"pattern": r".*/docs",
"default": "/data/docs"
},
"output_file_path": {
"type": "string",
"pattern": r".*/(.*\.json)",
"default": "/data/docs/index.json"
}
},
"required": ["doc_dir_path", "output_file_path"]
}
},
{
"name": "A7",
"description": "Extract the sender's email address from a text file and save it to an output file.",
"parameters": {
"type": "object",
"properties": {
"filename": {
"type": "string",
"pattern": r".*/(.*\.txt)",
"default": "/data/email.txt"
},
"output_file": {
"type": "string",
"pattern": r".*/(.*\.txt)",
"default": "/data/email-sender.txt"
}
},
"required": ["filename", "output_file"]
}
},
{
"name": "A8",
"description": "Generate an image representation of credit card details from a text file.",
"parameters": {
"type": "object",
"properties": {
"filename": {
"type": "string",
"pattern": r".*/(.*\.txt)",
"default": "/data/credit-card.txt"
},
"image_path": {
"type": "string",
"pattern": r".*/(.*\.png)",
"default": "/data/credit-card.png"
}
},
"required": ["filename", "image_path"]
}
},
{
"name": "A9",
"description": "Find similar comments from a text file and save them to an output file.",
"parameters": {
"type": "object",
"properties": {
"filename": {
"type": "string",
"pattern": r".*/(.*\.txt)",
"default": "/data/comments.txt"
},
"output_filename": {
"type": "string",
"pattern": r".*/(.*\.txt)",
"default": "/data/comments-similar.txt"
}
},
"required": ["filename", "output_filename"]
}
},
{
"name": "A10",
"description": "Identify high-value (gold) ticket sales from a database and save them to a text file.",
"parameters": {
"type": "object",
"properties": {
"filename": {
"type": "string",
"pattern": r".*/(.*\.db)",
"default": "/data/ticket-sales.db"
},
"output_filename": {
"type": "string",
"pattern": r".*/(.*\.txt)",
"default": "/data/ticket-sales-gold.txt"
},
"query": {
"type": "string",
"pattern": "SELECT SUM(units * price) FROM tickets WHERE type = 'Gold'"
}
},
"required": ["filename", "output_filename", "query"]
}
},
{
"name": "B12",
"description": "Check if filepath starts with /data",
"parameters": {
"type": "object",
"properties": {
"filepath": {
"type": "string",
"pattern": r"^/data/.*",
# "description": "Filepath must start with /data to ensure secure access."
}
},
"required": ["filepath"]
}
},
{
"name": "B3",
"description": "Download content from a URL and save it to the specified path.",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"pattern": r"https?://.*",
"description": "URL to download content from."
},
"save_path": {
"type": "string",
"pattern": r".*/.*",
"description": "Path to save the downloaded content."
}
},
"required": ["url", "save_path"]
}
},
{
"name": "B5",
"description": "Execute a SQL query on a specified database file and save the result to an output file.",
"parameters": {
"type": "object",
"properties": {
"db_path": {
"type": "string",
"pattern": r".*/(.*\.db)",
"description": "Path to the SQLite database file."
},
"query": {
"type": "string",
"description": "SQL query to be executed on the database."
},
"output_filename": {
"type": "string",
"pattern": r".*/(.*\.txt)",
"description": "Path to the file where the query result will be saved."
}
},
"required": ["db_path", "query", "output_filename"]
}
},
{
"name": "B6",
"description": "Fetch content from a URL and save it to the specified output file.",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"pattern": r"https?://.*",
"description": "URL to fetch content from."
},
"output_filename": {
"type": "string",
"pattern": r".*/.*",
"description": "Path to the file where the content will be saved."
}
},
"required": ["url", "output_filename"]
}
},
{
"name": "B7",
"description": "Process an image by optionally resizing it and saving the result to an output path.",
"parameters": {
"type": "object",
"properties": {
"image_path": {
"type": "string",
"pattern": r".*/(.*\.(jpg|jpeg|png|gif|bmp))",
"description": "Path to the input image file."
},
"output_path": {
"type": "string",
"pattern": r".*/.*",
"description": "Path to save the processed image."
},
"resize": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
},
"minItems": 2,
"maxItems": 2,
"description": "Optional. Resize dimensions as [width, height]."
}
},
"required": ["image_path", "output_path"]
}
},
{
"name": "B9",
"description": "Convert a Markdown file to another format and save the result to the specified output path.",
"parameters": {
"type": "object",
"properties": {
"md_path": {
"type": "string",
"pattern": r".*/(.*\.md)",
"description": "Path to the Markdown file to be converted."
},
"output_path": {
"type": "string",
"pattern": r".*/.*",
"description": "Path where the converted file will be saved."
}
},
"required": ["md_path", "output_path"]
}
}
]
def get_completions(prompt: str):
with httpx.Client(timeout=20) as client:
response = client.post(
f"{openai_api_chat}",
headers=headers,
json=
{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a function classifier that extracts structured parameters from queries."},
{"role": "user", "content": prompt}
],
"tools": [
{
"type": "function",
"function": function
} for function in function_definitions_llm
],
"tool_choice": "auto"
},
)
# return response.json()
print(response.json()["choices"][0]["message"]["tool_calls"][0]["function"])
return response.json()["choices"][0]["message"]["tool_calls"][0]["function"]
# Placeholder for task execution
@app.post("/run")
async def run_task(task: str):
try:
# Placeholder logic for executing tasks
# Replace with actual logic to parse task and execute steps
# Example: Execute task and return success or error based on result
# llm_response = function_calling(tast), function_name = A1
response = get_completions(task)
print(response)
task_code = response['name']
arguments = response['arguments']
if "A1"== task_code:
A1(**json.loads(arguments))
if "A2"== task_code:
A2(**json.loads(arguments))
if "A3"== task_code:
A3(**json.loads(arguments))
if "A4"== task_code:
A4(**json.loads(arguments))
if "A5"== task_code:
A5(**json.loads(arguments))
if "A6"== task_code:
A6(**json.loads(arguments))
if "A7"== task_code:
A7(**json.loads(arguments))
if "A8"== task_code:
A8(**json.loads(arguments))
if "A9"== task_code:
A9(**json.loads(arguments))
if "A10"== task_code:
A10(**json.loads(arguments))
if "B12"== task_code:
B12(**json.loads(arguments))
if "B3" == task_code:
B3(**json.loads(arguments))
if "B5" == task_code:
B5(**json.loads(arguments))
if "B6" == task_code:
B6(**json.loads(arguments))
if "B7" == task_code:
B7(**json.loads(arguments))
if "B9" == task_code:
B9(**json.loads(arguments))
return {"message": f"{task_code} Task '{task}' executed successfully"}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
# Placeholder for file reading
@app.get("/read", response_class=PlainTextResponse)
async def read_file(path: str = Query(..., description="File path to read")):
try:
with open(path, "r") as file:
return file.read()
except FileNotFoundError:
raise HTTPException(status_code=404, detail="File not found")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)