run_assistant_with_retrieval.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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__) + "/../../README.md")
  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. tools=[
  14. {"type": "file_search"},
  15. ],
  16. tool_resources={
  17. "file_search": {
  18. "vector_stores": [{
  19. "file_ids": [file.id]
  20. }]
  21. }
  22. }
  23. )
  24. logging.info("=====> : %s\n", assistant)
  25. thread = client.beta.threads.create()
  26. logging.info("=====> : %s\n", thread)
  27. message = client.beta.threads.messages.create(
  28. thread_id=thread.id,
  29. role="user",
  30. content="what open assistant api is?",
  31. )
  32. logging.info("=====> : %s\n", message)
  33. run = client.beta.threads.runs.create(
  34. thread_id=thread.id,
  35. assistant_id=assistant.id,
  36. instructions="",
  37. )
  38. logging.info("=====> : %s\n", run)
  39. logging.info("checking assistant status. \n")
  40. while True:
  41. run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
  42. run_steps = client.beta.threads.runs.steps.list(run_id=run.id, thread_id=thread.id).data
  43. for run_step in run_steps:
  44. logging.info("=====> : %s\n", run_step)
  45. if run.status == "completed":
  46. messages = client.beta.threads.messages.list(thread_id=thread.id)
  47. logging.info("=====> messages:")
  48. for message in messages:
  49. assert message.content[0].type == "text"
  50. logging.info("%s", {"role": message.role, "message": message.content[0].text.value})
  51. # delete asst
  52. client.beta.assistants.delete(assistant.id)
  53. break
  54. elif run.status == "failed":
  55. logging.error("run failed %s\n", run.last_error)
  56. break
  57. else:
  58. logging.info("in progress...\n")
  59. time.sleep(5)