run_assistant_with_image_message_file.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import os
  2. import time
  3. import logging
  4. from pathlib import Path
  5. from examples.prerun import client
  6. if __name__ == "__main__":
  7. file_path = os.path.join(os.path.dirname(__file__) + "/../../docs/imgs/user.png")
  8. file = client.files.create(file=Path(file_path), purpose="assistants")
  9. assistant = client.beta.assistants.create(
  10. name="Assistant Demo",
  11. instructions="you are a personal assistant, file content could be retrieved to assist the conversation.",
  12. model="gpt-3.5-turbo-1106",
  13. )
  14. logging.info("=====> : %s\n", assistant)
  15. thread = client.beta.threads.create()
  16. logging.info("=====> : %s\n", thread)
  17. message = client.beta.threads.messages.create(
  18. thread_id=thread.id,
  19. role="user",
  20. content="please explain the content in the image file",
  21. attachments=[{"file_id": file.id}]
  22. )
  23. logging.info("=====> : %s\n", message)
  24. run = client.beta.threads.runs.create(
  25. thread_id=thread.id,
  26. assistant_id=assistant.id,
  27. instructions="",
  28. )
  29. logging.info("=====> : %s\n", run)
  30. logging.info("checking assistant status. \n")
  31. while True:
  32. run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
  33. run_steps = client.beta.threads.runs.steps.list(run_id=run.id, thread_id=thread.id).data
  34. for run_step in run_steps:
  35. logging.info("=====> : %s\n", run_step)
  36. if run.status == "completed":
  37. messages = client.beta.threads.messages.list(thread_id=thread.id)
  38. logging.info("=====> messages:")
  39. for message in messages:
  40. assert message.content[0].type == "text"
  41. logging.info("%s", {"role": message.role, "message": message.content[0].text.value})
  42. # delete asst
  43. client.beta.assistants.delete(assistant.id)
  44. break
  45. elif run.status == "failed":
  46. logging.error("run failed %s\n", run.last_error)
  47. break
  48. else:
  49. logging.info("in progress...\n")
  50. time.sleep(5)