main.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. import logging
  2. import os
  3. import json
  4. import re
  5. import uuid
  6. import random
  7. import openai
  8. import requests
  9. from openai import OpenAI
  10. from flask import Flask, request, jsonify, send_from_directory, url_for
  11. from convert import alpaca_to_chatgpt, csv_to_jsonl
  12. app = Flask(__name__)
  13. ssl = None
  14. # ssl =('/etc/ssl/sample.crt', '/etc/ssl/sample.pem')
  15. app.openai_key = os.environ.get("OPENAI_KEY", "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")
  16. app.openai_client = OpenAI(api_key=app.openai_key)
  17. #logging.basicConfig(level=logging.DEBUG, filename='/jkt-disk-01/app/mms/chatgpt-apache/chatgpt.log', format='%(asctime)s %(message)s')
  18. app.chat_messages = [
  19. {"role": "system",
  20. "content": "Please respond professionally and in a friendly manner, using the same language as the original request. Use emoji responsibly."}
  21. ]
  22. app.translate_messages = [
  23. {"role": "system",
  24. "content": "Please translate using the requested language."}
  25. ]
  26. app.suggest_messages = [
  27. {"role": "system",
  28. "content": "Please suggest reply messages based on the previous conversations and the user's request."}
  29. ]
  30. app.recommend_messages = [
  31. {"role": "system",
  32. "content": "Give normalized total weight of each category in json based on headlines"
  33. }
  34. ]
  35. app.summary_messages = [
  36. {"role": "system",
  37. "content": "Please summarize an article."
  38. }
  39. ]
  40. UPLOAD_FOLDER = 'files'
  41. app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
  42. @app.route('/files/<name>')
  43. def download_file(name):
  44. return send_from_directory(app.config["UPLOAD_FOLDER"], name)
  45. @app.route('/', methods=['GET', 'POST'])
  46. def test():
  47. return jsonify({"status": "0"})
  48. def roulette() -> str:
  49. roulette_arr = [(80, "gpt-4o-mini"), (20, "gpt-4o")]
  50. rand_num = random.randrange(0, 99)
  51. model_name = ""
  52. n = 0
  53. j = 0
  54. while rand_num > n:
  55. n += roulette_arr[j][0]
  56. model_name = roulette_arr[j][1]
  57. print(model_name)
  58. j += 1
  59. return model_name
  60. def recommend(headlines, category):
  61. chat_messages = app.recommend_messages.copy()
  62. try:
  63. json_payload = {
  64. "role": "user",
  65. "content": f"""{headlines}
  66. Berikan nilai berat masing-masing kategori, jumlahkan dan normalisasikan:
  67. {category}
  68. Berikan dalam bentuk json
  69. """
  70. }
  71. chat_messages.append(json_payload)
  72. json_response = app.openai_client.chat.completions.create(model="gpt-4o-mini",
  73. messages=chat_messages,
  74. response_format={"type": "json_object"}
  75. )
  76. result = {"status": "ok", "message": json.loads(json_response.choices[0].message.content)}
  77. except openai.APITimeoutError as e:
  78. app.logger.exception("error")
  79. result = {"status": "error", "message": e.message}, 408
  80. except openai.NotFoundError as e:
  81. app.logger.exception("error")
  82. result = {"status": "error", "message": json.loads(e.response.content)['error']['message']}, e.status_code
  83. except Exception as error_print:
  84. app.logger.exception("error")
  85. result = {"status": "error", "message": "Please try again"}, 405
  86. return result
  87. def vision(message, image_url=None, image_b64=None):
  88. chat_messages = app.chat_messages.copy()
  89. url = ""
  90. if image_url:
  91. url = f"{image_url}"
  92. elif image_b64:
  93. url = f"data:image/jpeg;base64,{image_b64}"
  94. try:
  95. json_payload = {
  96. "role": "user",
  97. "content": [
  98. {"type": "text", "text": message},
  99. {
  100. "type": "image_url",
  101. "image_url": {
  102. "url": url,
  103. },
  104. },
  105. ],
  106. }
  107. chat_messages.append(json_payload)
  108. json_response = app.openai_client.chat.completions.create(
  109. model="gpt-4o",
  110. messages=chat_messages,
  111. max_tokens=500
  112. )
  113. result = {"role": "assistant", "content": json_response.choices[0].message.content}
  114. except openai.APITimeoutError as e:
  115. app.logger.exception("error")
  116. result = {"status": "error", "message": e.message}, 408
  117. except openai.NotFoundError as e:
  118. app.logger.exception("error")
  119. result = {"status": "error", "message": json.loads(e.response.content)['error']['message']}, e.status_code
  120. except Exception as e:
  121. app.logger.exception("error")
  122. result = {"status": "error", "message": "Please try again"}, 405
  123. return result
  124. @app.route('/gpt', methods=['POST'])
  125. def gpt():
  126. assistant_id = ""
  127. assistant = None
  128. chat_messages = app.chat_messages.copy()
  129. chat_model = "gpt-4o-mini"
  130. use_video = False
  131. suggest = False
  132. summarize = False
  133. expression = False
  134. predict_q = 0
  135. max_char_msg = 500
  136. max_resp_token = 600
  137. category = []
  138. headlines = []
  139. image_url = ""
  140. num_choices = 1
  141. json_payload = request.get_json()
  142. if not json_payload:
  143. json_payload = []
  144. has_named_params = False
  145. if isinstance(json_payload, dict):
  146. has_named_params = 'payload' in json_payload
  147. if 'payload' in json_payload:
  148. if 'predict_q' in json_payload:
  149. predict_q = 5 if json_payload['predict_q'] > 4 else 0 if json_payload['predict_q'] < 1 else \
  150. json_payload['predict_q']
  151. if 'num_choices' in json_payload:
  152. num_choices = 5 if json_payload['num_choices'] > 4 else 1 if json_payload['num_choices'] < 2 else \
  153. json_payload['num_choices']
  154. if 'use_video' in json_payload:
  155. use_video = json_payload['use_video'] == "1"
  156. if 'chat_model' in json_payload and 'assistant_id' not in json_payload:
  157. chat_model = json_payload['chat_model']
  158. max_resp_token = 2048
  159. if 'expression' in json_payload:
  160. expression = json_payload['expression'] == "1"
  161. if 'translate' in json_payload:
  162. chat_messages = app.translate_messages.copy()
  163. json_payload['payload'][-1]['content'] = json_payload['payload'][-1][
  164. 'content'] + f" (Translate to {json_payload['translate']})"
  165. elif 'suggest' in json_payload:
  166. suggest = json_payload['suggest'] == "1"
  167. if suggest:
  168. chat_messages = app.suggest_messages.copy()
  169. else:
  170. chat_messages = app.chat_messages.copy()
  171. json_payload['payload'][-1]['content'] = json_payload['payload'][-1][
  172. 'content'] + f" What can I say to him/her?"
  173. elif 'summarize' in json_payload:
  174. summarize = json_payload['summarize'] == "1"
  175. if summarize:
  176. chat_messages = app.summary_messages.copy()
  177. max_char_msg = 2000
  178. max_resp_token = 1000
  179. else:
  180. chat_messages = app.chat_messages.copy()
  181. json_payload['payload'][-1]['content'] = f"Please summarize this article:\n" + \
  182. json_payload['payload'][-1]['content']
  183. elif 'assistant_id' in json_payload:
  184. assistant_id = json_payload['assistant_id']
  185. assistant = app.openai_client.beta.assistants.retrieve(assistant_id=assistant_id)
  186. chat_model = assistant.model
  187. else:
  188. chat_messages = app.chat_messages.copy()
  189. json_payload = json_payload['payload']
  190. if isinstance(json_payload, dict):
  191. json_payload = [json_payload]
  192. elif 'greeting' in json_payload:
  193. chat_messages = app.chat_messages.copy()
  194. company_name = json_payload['greeting']['company_name']
  195. timestamp = json_payload['greeting']['timestamp']
  196. islamic_message = f"Apakah Nama '{company_name}' terdapat unsur islami? Jawab dengan 'Ya' atau 'Tidak'"
  197. islam_messages = app.chat_messages.copy()
  198. islam_messages.append({
  199. "role": "user",
  200. "content": islamic_message
  201. })
  202. islamic_response = app.openai_client.chat.completions.create(model="gpt-4o-mini",
  203. messages=islam_messages,
  204. max_tokens=2, temperature=0.5)
  205. if 'Ya' in islamic_response.choices[0].message.content:
  206. greeting_message = f"Buatkan respons chatbot berupa greeting dari chat perusahaan bernama {company_name} pada jam {timestamp}, tidak perlu mention waktu, dan jawab dengan 'Assalamu'alaikum...' terlebih dahulu"
  207. else:
  208. greeting_message = f"Buatkan respons chatbot berupa greeting dari chat perusahaan bernama {company_name} pada jam {timestamp}, tidak perlu mention waktu"
  209. json_payload = [
  210. {
  211. "role": "user",
  212. "content": greeting_message
  213. }
  214. ]
  215. elif 'recommend' in json_payload:
  216. headlines = json_payload['recommend']['headlines']
  217. category = json_payload['recommend']['category']
  218. return recommend(headlines, category)
  219. elif 'image_url' in json_payload:
  220. image = json_payload['image_url']
  221. message = json_payload["message"] if 'message' in json_payload else "Ini gambar apa?"
  222. return vision(message, image_url=image)
  223. elif 'image_b64' in json_payload:
  224. image = json_payload['image_b64']
  225. message = json_payload["message"] if 'message' in json_payload else "Ini gambar apa?"
  226. return vision(message, image_b64=image_url)
  227. else:
  228. app.logger.info("This request use old json format")
  229. chat_messages = app.chat_messages.copy()
  230. app.logger.info("Chat Messages:")
  231. app.logger.info(str(chat_messages))
  232. json_payload = json_payload[-5:]
  233. if assistant_id:
  234. chat_messages = []
  235. for message in json_payload:
  236. if message['role'] == 'user':
  237. content = message['content'].lower()
  238. else:
  239. content = message['content']
  240. content_arr = content.split(" ")
  241. new_content_arr = content[:max_char_msg].split(" ")
  242. new_content_len = len(new_content_arr)
  243. arr = []
  244. for i in range(new_content_len):
  245. arr.append(content_arr[i])
  246. message['content'] = " ".join(arr)
  247. chat_messages.append(message)
  248. app.logger.info(chat_messages)
  249. result = {}
  250. try:
  251. n = num_choices
  252. if "gpt-3.5-turbo" or "gpt-4o-mini" in chat_model:
  253. chat_model = roulette()
  254. app.logger.info(f"Model used: {chat_model}")
  255. if assistant_id and not suggest:
  256. runs = app.openai_client.beta.threads.create_and_run_poll(
  257. assistant_id=assistant_id,
  258. thread={
  259. "messages": chat_messages
  260. }
  261. )
  262. if runs.status != "completed":
  263. result = {"role": "assistant", "content": "Maaf, saat ini saya sedang sibuk. Coba beberapa saat lagi."}
  264. else:
  265. messages = list(app.openai_client.beta.threads.messages.list(thread_id=runs.thread_id, run_id=runs.id))
  266. try:
  267. message_content = messages[0].content[0].text
  268. app.logger.info(message_content.value)
  269. pattern = re.compile(r"【\d+:\d+†\(?source\)?】")
  270. filtered_message = pattern.sub("", message_content.value)
  271. result = {"role": "assistant", "content": filtered_message}
  272. except IndexError:
  273. result = {"role": "assistant", "content": "Saat ini saya tidak memiliki informasi yang diperlukan untuk menjawab pertanyaan Anda."}
  274. else:
  275. json_response = app.openai_client.chat.completions.create(model=chat_model,
  276. messages=chat_messages,
  277. max_tokens=max_resp_token, temperature=0.7, n=n)
  278. app.logger.info(json_response.choices[0].message)
  279. if has_named_params:
  280. if suggest:
  281. choices = json_response.choices
  282. messages = [i.message for i in choices]
  283. json_formatted = []
  284. for message in messages:
  285. json_formatted.append({"role": "assistant", "content": message.content})
  286. result = {"url": "", "message": json_formatted}
  287. else:
  288. if use_video:
  289. # TODO: to be implemented
  290. result = {"url": url_for('download_file', name="test.mp4", _external=True),
  291. "message": {"role": "assistant", "content": json_response.choices[0].message.content}}
  292. else:
  293. result = {"role": "assistant", "content": json_response.choices[0].message.content}
  294. else:
  295. result = {"role": "assistant", "content": json_response.choices[0].message.content}
  296. if expression:
  297. exprr = expresso(text=result['content'])
  298. result['expression'] = exprr['expression']
  299. if predict_q:
  300. if assistant_id:
  301. query_q = {
  302. "role": "user",
  303. "content": f"Berikan {predict_q} pertanyaan random yang akan saya ajukan sesuai topik asisten dalam bentuk json array"
  304. }
  305. else:
  306. query_q = {
  307. "role": "user",
  308. "content": f"Berikan {predict_q} pertanyaan lain yang akan saya ajukan berdasarkan percakapan kali ini dalam bentuk json array"
  309. }
  310. chat_messages.append(result)
  311. chat_messages.append(query_q)
  312. if assistant_id:
  313. runs = app.openai_client.beta.threads.create_and_run_poll(
  314. assistant_id=assistant_id,
  315. thread={
  316. "messages": chat_messages
  317. },
  318. max_completion_tokens=600,
  319. max_prompt_tokens=600
  320. )
  321. messages = list(app.openai_client.beta.threads.messages.list(thread_id=runs.thread_id, run_id=runs.id))
  322. message_content = messages[0].content[0].text
  323. app.logger.info(message_content.value)
  324. pattern = re.compile(r"【\d+:\d+†\(?source\)?】")
  325. filtered_message = pattern.sub("", message_content.value)
  326. predict_q_arr = [
  327. {
  328. "role": "system",
  329. "content": assistant.instructions
  330. },
  331. {
  332. "role": "assistant",
  333. "content": filtered_message
  334. },
  335. {
  336. "role": "user",
  337. "content": f"Ekstrak {predict_q} pertanyaan tersebut dalam bentuk json array"
  338. }
  339. ]
  340. json_response_q = app.openai_client.chat.completions.create(
  341. model=chat_model,
  342. messages=predict_q_arr,
  343. temperature=0.2,
  344. response_format={"type": "json_object"}
  345. )
  346. else:
  347. json_response_q = app.openai_client.chat.completions.create(model=chat_model,
  348. messages=chat_messages,
  349. max_tokens=max_resp_token,
  350. temperature=0.2,
  351. response_format={"type": "json_object"})
  352. json_response_dict = json.loads(json_response_q.choices[0].message.content)
  353. if json_response_dict is not None:
  354. if isinstance(json_response_dict, dict):
  355. if len(json_response_dict) > 1:
  356. qs = []
  357. for q in json_response_dict.values():
  358. qs.append(q)
  359. json_response_dict = qs
  360. else:
  361. try:
  362. first_key = next(iter(json_response_dict))
  363. json_response_dict = json_response_dict[first_key]
  364. except StopIteration:
  365. json_response_dict = []
  366. elif isinstance(json_response_dict, str):
  367. json_response_dict = [json_response_dict]
  368. result["predict_q"] = json_response_dict
  369. except openai.APITimeoutError as e:
  370. app.logger.exception("error")
  371. result = {"status": "error", "message": e.message}, 408
  372. except openai.NotFoundError as e:
  373. app.logger.exception("error")
  374. result = {"status": "error", "message": json.loads(e.response.content)['error']['message']}, e.status_code
  375. except Exception:
  376. app.logger.exception("error")
  377. result = {"status": "error", "message": "Please try again"}, 405
  378. return result
  379. @app.route('/train', methods=['POST'])
  380. def train():
  381. prev_model = "gpt-3.5-turbo"
  382. instructions = None
  383. if 'job_id' in request.form:
  384. return train_with_id(job_id=request.form['job_id'])
  385. elif 'train_file' in request.files:
  386. train_file = request.files['train_file']
  387. app.logger.info({"filename": train_file.filename})
  388. if 'instructions' in request.form:
  389. instructions = request.form['instructions']
  390. openai_file = None
  391. if train_file.filename.split('.')[1] == 'jsonl':
  392. openai_file = train_file.stream.read()
  393. elif train_file.filename.split('.')[1] == 'csv':
  394. openai_file = csv_to_jsonl(train_file.stream.read(), instructions)
  395. elif train_file.filename.split('.')[1] == 'json':
  396. openai_file = alpaca_to_chatgpt(train_file, instructions)
  397. if 'prev_model' in request.form:
  398. prev_model = request.form['prev_model']
  399. app.logger.info(f"Previous model: {prev_model}")
  400. if 'mock' not in request.form:
  401. f = app.openai_client.files.create(
  402. file=openai_file,
  403. purpose="fine-tune"
  404. )
  405. job = app.openai_client.fine_tuning.jobs.create(
  406. training_file=f.id,
  407. model=prev_model,
  408. hyperparameters={
  409. "n_epochs": 5
  410. }
  411. )
  412. app.logger.info({"mock": "no", "status": job.status, "job_id": job.id})
  413. retval = {"status": job.status, "job_id": job.id}
  414. return retval
  415. else:
  416. app.logger.info({"mock": "yes", "status": "ok"})
  417. return {"status": "ok"}
  418. else:
  419. app.logger.error({"status": "error", "message": "Training file not found"})
  420. return {"status": "error", "message": "Training file not found"}
  421. def train_with_id(job_id):
  422. try:
  423. job = app.openai_client.fine_tuning.jobs.retrieve(job_id)
  424. if job.fine_tuned_model is None:
  425. app.logger.info({"job_id": job_id, "status": job.status})
  426. return {"status": job.status}
  427. else:
  428. app.logger.info({"job_id": job_id, "status": job.status, "model_name": job.fine_tuned_model})
  429. return {"status": job.status, "model_name": job.fine_tuned_model}
  430. except Exception as error_print:
  431. app.logger.exception("error")
  432. return {"status": "Could not find job from id"}
  433. @app.route('/assistant/create', methods=['POST'])
  434. def assistant_create():
  435. model_name = "gpt-4o-mini"
  436. assistant_name = "Assistant"
  437. assistant_ins = "Please respond professionally and in a friendly manner, using the same language as the original request."
  438. if request.is_json:
  439. request_form = request.json
  440. else:
  441. request_form = request.form.copy()
  442. assistant_name = request_form.pop('name', assistant_name)
  443. assistant_ins = request_form.pop('instructions', assistant_ins)
  444. model_name = request_form.pop('model_name', model_name)
  445. vector_store_id = request_form.pop('vector_store_id', "")
  446. file_batch_id = ""
  447. try:
  448. temperature = float(request_form.pop('temperature', 1.0))
  449. if temperature < 0.0:
  450. temperature = 0.0
  451. elif temperature > 1.0:
  452. temperature = 1.0
  453. except ValueError:
  454. temperature = 1.0
  455. tool_resources = {"tool_resources": {"file_search": {"vector_store_ids": [vector_store_id]}}} \
  456. if vector_store_id \
  457. else {}
  458. try:
  459. assistant = app.openai_client.beta.assistants.create(
  460. name=assistant_name,
  461. instructions=assistant_ins,
  462. model=model_name,
  463. tools=[{"type": "file_search"}],
  464. temperature=temperature,
  465. **tool_resources,
  466. **request_form
  467. )
  468. if 'attachment1' in request.files and not vector_store_id:
  469. resp_att = assistant_att()
  470. retval = {}
  471. if resp_att['status'] == 'completed':
  472. resp_upd = assistant_update(assistant.id, resp_att['vector_store_id'])
  473. assistant_updated = "1" if resp_upd['status'] == 'ok' else "0"
  474. else:
  475. assistant_updated = "0"
  476. if 'vector_store_id' in resp_att:
  477. retval['vector_store_id'] = resp_att['vector_store_id']
  478. if 'file_batch_id' in resp_att:
  479. retval['file_batch_id'] = resp_att['file_batch_id']
  480. retval['status'] = "ok"
  481. retval['assistant_id'] = assistant.id
  482. retval['assistant_updated'] = assistant_updated
  483. return retval
  484. else:
  485. return {"status": "ok", "assistant_id": assistant.id, "assistant_updated": "1" if vector_store_id else "0"}
  486. except ValueError as e:
  487. app.logger.exception("error")
  488. return {"status": "error",
  489. "message": "Failed to create assistant, please check whether your parameters are correct"}
  490. except openai.NotFoundError as e:
  491. app.logger.exception("error")
  492. return {"status": "error", "message": json.loads(e.response.content)['error']['message']}, e.status_code
  493. except Exception:
  494. app.logger.exception("error")
  495. return {"status": "error", "message": "Failed to create assistant, please try again"}, 405
  496. @app.route('/assistant/attachment', methods=['POST'])
  497. def assistant_att():
  498. vector_store_id = request.form.get('vector_store_id', '')
  499. file_batch_id = request.form.get('file_batch_id', '')
  500. attachments: list[str] = []
  501. try:
  502. if not file_batch_id:
  503. if 'attachment1' not in request.files:
  504. return {"status": "error", "message": "No file for attachments"}
  505. else:
  506. has_attachments = True
  507. n = 1
  508. while has_attachments:
  509. if f'attachment{n}' in request.files:
  510. retf = app.openai_client.files.create(
  511. file=(request.files[f'attachment{n}'].filename,
  512. request.files[f'attachment{n}'].read()),
  513. purpose="assistants"
  514. )
  515. retf.filename = request.files[f'attachment{n}'].filename
  516. attachments.append(retf.id)
  517. n = n + 1
  518. else:
  519. has_attachments = False
  520. if vector_store_id:
  521. vector_store = app.openai_client.beta.vector_stores.retrieve(vector_store_id=vector_store_id)
  522. else:
  523. vector_store = app.openai_client.beta.vector_stores.create(
  524. expires_after={
  525. "anchor": "last_active_at",
  526. "days": 365
  527. }
  528. )
  529. file_batch = app.openai_client.beta.vector_stores.file_batches.create_and_poll(
  530. vector_store_id=vector_store.id,
  531. file_ids=attachments
  532. )
  533. return {"status": file_batch.status, "vector_store_id": vector_store.id, "file_batch_id": file_batch.id}
  534. else:
  535. file_batch = app.openai_client.beta.vector_stores.file_batches.retrieve(file_batch_id,
  536. vector_store_id=vector_store_id)
  537. return {"status": file_batch.status}
  538. except Exception as e:
  539. app.logger.exception("error")
  540. return {"status": "error", "message": "Upload attachment failed, please try again"}
  541. @app.route('/assistant/update', methods=['POST'])
  542. def assistant_update(aid=None, vid=None):
  543. try:
  544. request_form = request.form.copy()
  545. if aid is not None and vid is not None:
  546. assistant_id = aid
  547. vector_store_id = vid
  548. else:
  549. assistant_id = request_form.pop('assistant_id')
  550. vector_store_id = request_form.pop('vector_store_id', None)
  551. kwargs = {"assistant_id": assistant_id}
  552. if vector_store_id is not None:
  553. kwargs['tool_resources'] = {"file_search": {"vector_store_ids": [vector_store_id]}}
  554. if 'name' in request_form:
  555. kwargs['name'] = request_form.pop('name')
  556. if 'instructions' in request_form:
  557. kwargs['instructions'] = request_form.pop('instructions')
  558. app.openai_client.beta.assistants.update(**kwargs)
  559. return {"status": "ok"}
  560. except Exception as e:
  561. app.logger.exception("error")
  562. return {"status": "error", "message": "Update assistant failed, please try again"}
  563. @app.route('/llama', methods=['POST'])
  564. def llama():
  565. max_char_msg = 500
  566. max_resp_token = 600
  567. json_payload = request.get_json()
  568. if not json_payload:
  569. json_payload = []
  570. has_named_params = False
  571. if isinstance(json_payload, dict):
  572. has_named_params = 'payload' in json_payload
  573. if 'payload' in json_payload:
  574. json_payload = json_payload['payload']
  575. if isinstance(json_payload, dict):
  576. json_payload = [json_payload]
  577. else:
  578. json_payload = [json_payload]
  579. message = json_payload[-1]
  580. content = message['content']
  581. content_arr = content.split(" ")
  582. new_content_arr = content[:max_char_msg].split(" ")
  583. new_content_len = len(new_content_arr)
  584. arr = []
  585. for i in range(new_content_len):
  586. arr.append(content_arr[i])
  587. content = " ".join(arr)
  588. content = content + " Jawab dengan Bahasa Indonesia"
  589. try:
  590. json_request = {
  591. "model": "llama3.1",
  592. "prompt": content,
  593. "stream": False
  594. }
  595. r = requests.post("http://localhost:11434/api/generate", json=json_request)
  596. if r.status_code == 200:
  597. result = {
  598. "role": "assistant",
  599. "content": r.json()["response"]
  600. }
  601. else:
  602. result = {}, r.status_code
  603. except Exception as e:
  604. app.logger.exception("error")
  605. result = {"status": "error", "message": "Please try again"}, 405
  606. return result
  607. @app.route('/speech', methods=['POST'])
  608. def speech(text=""):
  609. if not text and 'text' not in request.form:
  610. audio_file = request.files.get('audio')
  611. res = app.openai_client.audio.transcriptions.create(
  612. model="whisper-1",
  613. file=(audio_file.filename, audio_file.stream.read())
  614. )
  615. return {"status": "ok", "message": res.text}
  616. elif 'text' in request.form or text:
  617. text = request.form['text'] if 'text' in request.form else text
  618. uu_id = str(uuid.uuid4())
  619. print(text)
  620. with app.openai_client.audio.speech.with_streaming_response.create(
  621. model="tts-1-hd",
  622. voice="echo",
  623. speed=0.8,
  624. input=text
  625. ) as res:
  626. res.stream_to_file(os.path.join(app.config['UPLOAD_FOLDER'], f"{uu_id}.mp3"))
  627. return download_file(f"{uu_id}.mp3")
  628. @app.route('/expression', methods=['POST'])
  629. def expresso(text=""):
  630. if not text:
  631. if 'text' in request.form:
  632. text = request.form['text']
  633. else:
  634. return {"status": "error", "message": "No text for expression"}
  635. response = app.openai_client.chat.completions.create(
  636. model="gpt-4o-mini",
  637. messages=[
  638. {
  639. "role": "user",
  640. "content": f"What is the closest expression of this text, choose between happy, sad, indifferent, fear, anger, surprise, or disgust, output json with key 'expression':\n\n{text}\n\n"
  641. }
  642. ],
  643. response_format={"type": "json_object"}
  644. )
  645. response_message = response.choices[0].message.content
  646. return json.loads(response_message)
  647. # Press the green button in the gutter to run the script.
  648. if __name__ == '__main__':
  649. app.run(host='0.0.0.0', port=8348, debug=True, ssl_context=ssl)
  650. # See PyCharm help at https://www.jetbrains.com/help/pycharm/