run_with_auth_action.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import time
  2. import logging
  3. import requests
  4. import json
  5. from app.exceptions.exception import BadRequestError
  6. from examples.prerun import client
  7. from examples.prerun import base_url
  8. from examples.prerun import api_key
  9. # To test the localhost, you can listen to a port using the shell command 'echo -e "HTTP/1.1 200 OK\r\n\r\n Success" | nc -l 9999'.
  10. # Make sure to change the URL to match your API server.
  11. auth_server_url = "http://localhost:9999/api/v1"
  12. def create_worksapce_action():
  13. """
  14. create action with actions api
  15. """
  16. openapi_schema = {
  17. "openapi_schema": {
  18. "openapi": "3.0.0",
  19. "info": {"title": "Create New Workspace", "version": "1.0.0"},
  20. "servers": [{"url": f"{auth_server_url}"}],
  21. "paths": {
  22. "/tx/v1/workspaces": {
  23. "post": {
  24. "summary": "Create a new workspace",
  25. "description": "This endpoint creates a new workspace with the provided data.",
  26. "operationId": "createWorkspace",
  27. "requestBody": {
  28. "required": True,
  29. "content": {
  30. "application/json": {
  31. "schema": {
  32. "type": "object",
  33. "properties": {
  34. "name": {"type": "string", "description": "The name of the workspace"},
  35. "description": {
  36. "type": "string",
  37. "description": "The description of the workspace",
  38. },
  39. "ui_settings": {
  40. "type": "object",
  41. "properties": {
  42. "color": {
  43. "type": "string",
  44. "description": "The color of the workspace UI",
  45. },
  46. "icon": {
  47. "type": "string",
  48. "description": "The icon of the workspace UI",
  49. },
  50. },
  51. },
  52. "tenant_id": {"type": "string", "description": "The tenant ID"},
  53. },
  54. }
  55. }
  56. },
  57. },
  58. "responses": {
  59. "200": {
  60. "description": "Workspace created successfully",
  61. "content": {"application/json": {"schema": {"type": "object", "properties": {}}}},
  62. },
  63. "401": {"description": "Unauthorized - Authentication credentials are missing or invalid"},
  64. "403": {
  65. "description": "Forbidden - The authenticated user does not have permission to perform this action"
  66. },
  67. "500": {"description": "Internal Server Error - Something went wrong on the server side"},
  68. },
  69. }
  70. }
  71. },
  72. }
  73. }
  74. openapi_schema["authentication"] = {"type": "none"}
  75. actions_url = f"{base_url}/actions"
  76. headers = {
  77. 'Content-Type': 'application/json',
  78. 'Authorization': f'Bearer {api_key}'
  79. }
  80. response = requests.request("POST", actions_url, headers=headers, data=json.dumps(openapi_schema), timeout=1000)
  81. if response.status_code != 200:
  82. raise BadRequestError(f"Failed to create action: {response.text}")
  83. return response.json()
  84. if __name__ == "__main__":
  85. [create_workspace_with_authentication] = create_worksapce_action()
  86. logging.info("=====> action: %s\n", create_workspace_with_authentication)
  87. # create a assistant with action
  88. assistant = client.beta.assistants.create(
  89. name="Assistant Demo",
  90. instructions="you are a personal assistant",
  91. tools=[{"type": "action", "id": create_workspace_with_authentication["id"]}],
  92. model="gpt-3.5-turbo-1106",
  93. )
  94. logging.info("=====> : %s\n", assistant)
  95. thread = client.beta.threads.create()
  96. logging.info("=====> : %s\n", thread)
  97. message = client.beta.threads.messages.create(
  98. thread_id=thread.id,
  99. role="user",
  100. content="在组织 63db49f7dcc8bf7b0990903c 下, 创建一个随机名字的工作空间",
  101. )
  102. logging.info("=====> : %s\n", message)
  103. # create a run with auth info
  104. run = client.beta.threads.runs.create(
  105. thread_id=thread.id,
  106. assistant_id=assistant.id,
  107. instructions="",
  108. extra_body={
  109. "extra_body": {
  110. "action_authentications": {
  111. create_workspace_with_authentication["id"]: {
  112. # auth info, change as needed
  113. "type": "bearer",
  114. "secret": "xxx",
  115. }
  116. }
  117. }
  118. },
  119. )
  120. logging.info("=====> : %s\n", run)
  121. while True:
  122. run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
  123. if run.status == "completed":
  124. messages = client.beta.threads.messages.list(thread_id=thread.id)
  125. logging.info("=====> messages:")
  126. for message in messages:
  127. assert message.content[0].type == "text"
  128. logging.info("%s", {"role": message.role, "message": message.content[0].text.value})
  129. break
  130. elif run.status == "failed":
  131. logging.error("run failed %s\n", run.last_error)
  132. break
  133. else:
  134. logging.info("in progress...\n")
  135. time.sleep(5)