run_assistant_with_custom_functions.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import time
  2. import logging
  3. from app.schemas.runs import ToolOutput
  4. from examples.prerun import client
  5. if __name__ == "__main__":
  6. assistant = client.beta.assistants.create(
  7. name="Assistant Demo",
  8. instructions="you are a personal math assistant, can use calculator tool to solve math problems",
  9. model="gpt-3.5-turbo-1106",
  10. tools=[
  11. {
  12. "type": "function",
  13. "function": {
  14. "name": "calculator",
  15. "description": "can solve math problems, use this tool when you need to calculate.",
  16. "parameters": {
  17. "type": "object",
  18. "properties": {
  19. "input": {
  20. "type": "string",
  21. "description": "the arithmetic expression to be calculated.",
  22. }
  23. },
  24. "required": ["input"],
  25. },
  26. },
  27. },
  28. ]
  29. )
  30. logging.info("=====> : %s\n", assistant)
  31. thread = client.beta.threads.create()
  32. logging.info("=====> : %s\n", thread)
  33. message = client.beta.threads.messages.create(
  34. thread_id=thread.id,
  35. role="user",
  36. content="what is 1+1?",
  37. )
  38. logging.info("=====> : %s\n", message)
  39. run = client.beta.threads.runs.create(
  40. thread_id=thread.id,
  41. assistant_id=assistant.id,
  42. instructions="",
  43. )
  44. logging.info("=====> : %s\n", run)
  45. logging.info("checking assistant status. \n")
  46. while True:
  47. run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
  48. run_steps = client.beta.threads.runs.steps.list(run_id=run.id, thread_id=thread.id).data
  49. for run_step in run_steps:
  50. logging.info("=====> : %s\n", run_step)
  51. tool_calls = run_step.step_details.type == "tool_calls" and run_step.step_details.tool_calls
  52. if run.status == "requires_action" and run_step.status == "in_progress" and tool_calls:
  53. for tool_call in tool_calls:
  54. try:
  55. client.beta.threads.runs.submit_tool_outputs(
  56. run_id=run.id,
  57. thread_id=thread.id,
  58. # we submit a fake output here, you can replace it with the real output
  59. tool_outputs=[ToolOutput(output="2", tool_call_id=tool_call.id)],
  60. )
  61. except Exception:
  62. pass
  63. if run.status == "completed":
  64. messages = client.beta.threads.messages.list(thread_id=thread.id)
  65. logging.info("=====> messages:")
  66. for message in messages:
  67. assert message.content[0].type == "text"
  68. logging.info("%s", {"role": message.role, "message": message.content[0].text.value})
  69. # delete asst
  70. client.beta.assistants.delete(assistant.id)
  71. break
  72. elif run.status == "failed":
  73. logging.error("run failed %s\n", run.last_error)
  74. break
  75. else:
  76. logging.info("in progress...\n")
  77. time.sleep(5)