assistant_action_test.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import time
  2. import openai
  3. import pytest
  4. from app.providers.database import session
  5. from app.schemas.tool.action import ActionBulkCreateRequest
  6. from app.schemas.tool.authentication import Authentication, AuthenticationType
  7. from app.services.tool.action import ActionService
  8. @pytest.fixture
  9. def api_url():
  10. return "http://127.0.0.1:8086/api/v1/actions"
  11. @pytest.fixture
  12. def get_weather_data_valid_payload():
  13. return {
  14. "openapi_schema": {
  15. "openapi": "3.0.0",
  16. "info": {
  17. "title": "OpenWeatherMap One Call API",
  18. "description": "API for accessing comprehensive weather data from OpenWeatherMap.",
  19. "version": "1.0.0",
  20. },
  21. "servers": [
  22. {
  23. "url": "https://api.openweathermap.org/data/3.0",
  24. "description": "OpenWeatherMap One Call API server",
  25. }
  26. ],
  27. "paths": {
  28. "/onecall": {
  29. "get": {
  30. "summary": "Get Comprehensive Weather Data",
  31. "description": "Retrieves weather data for a specific latitude and longitude.",
  32. "operationId": "get_weather_data",
  33. "parameters": [
  34. {
  35. "in": "query",
  36. "name": "lat",
  37. "schema": {"type": "number", "format": "float", "minimum": -90, "maximum": 90},
  38. "required": True,
  39. "description": "Latitude, decimal (-90 to 90).",
  40. },
  41. {
  42. "in": "query",
  43. "name": "lon",
  44. "schema": {"type": "number", "format": "float", "minimum": -180, "maximum": 180},
  45. "required": True,
  46. "description": "Longitude, decimal (-180 to 180).",
  47. },
  48. {
  49. "in": "query",
  50. "name": "exclude",
  51. "schema": {"type": "string"},
  52. "required": False,
  53. "description": "Exclude some parts of the weather data(current, minutely, hourly, daily, alerts).",
  54. },
  55. {
  56. "in": "query",
  57. "name": "appid",
  58. "schema": {"type": "string", "enum": ["101f41d3ff4095824722d57a513cb80a"]},
  59. "required": True,
  60. "description": "Your unique API key.",
  61. },
  62. ],
  63. "responses": {
  64. "200": {
  65. "description": "Successful response with comprehensive weather data.",
  66. "content": {"application/json": {"schema": {"type": "object", "properties": {}}}},
  67. }
  68. },
  69. }
  70. }
  71. },
  72. }
  73. }
  74. @pytest.fixture
  75. def get_number_fact_valid_payload():
  76. return {
  77. "openapi_schema": {
  78. "openapi": "3.0.0",
  79. "info": {
  80. "title": "Numbers API",
  81. "version": "1.0.0",
  82. "description": "API for fetching interesting number facts",
  83. },
  84. "servers": [{"url": "http://numbersapi.com"}],
  85. "paths": {
  86. "/{number}": {
  87. "get": {
  88. "description": "Get fact about a number",
  89. "operationId": "get_number_fact",
  90. "parameters": [
  91. {
  92. "name": "number",
  93. "in": "path",
  94. "required": True,
  95. "description": "The number to get the fact for",
  96. "schema": {"type": "integer"},
  97. }
  98. ],
  99. "responses": {
  100. "200": {
  101. "description": "A fact about the number",
  102. "content": {"text/plain": {"schema": {"type": "string"}}},
  103. }
  104. },
  105. }
  106. }
  107. },
  108. }
  109. }
  110. @pytest.fixture
  111. def create_workspace_with_authentication():
  112. return {
  113. "openapi_schema": {
  114. "openapi": "3.0.0",
  115. "info": {"title": "Create New Workspace", "version": "1.0.0"},
  116. "servers": [{"url": "https://tx.c.csvfx.com/api"}],
  117. "paths": {
  118. "/tx/v1/workspaces": {
  119. "post": {
  120. "summary": "Create a new workspace",
  121. "description": "This endpoint creates a new workspace with the provided data.",
  122. "operationId": "createWorkspace",
  123. "requestBody": {
  124. "required": True,
  125. "content": {
  126. "application/json": {
  127. "schema": {
  128. "type": "object",
  129. "properties": {
  130. "name": {"type": "string", "description": "The name of the workspace"},
  131. "description": {
  132. "type": "string",
  133. "description": "The description of the workspace",
  134. },
  135. "ui_settings": {
  136. "type": "object",
  137. "properties": {
  138. "color": {
  139. "type": "string",
  140. "description": "The color of the workspace UI",
  141. },
  142. "icon": {
  143. "type": "string",
  144. "description": "The icon of the workspace UI",
  145. },
  146. },
  147. },
  148. "tenant_id": {"type": "string", "description": "The tenant ID"},
  149. },
  150. }
  151. }
  152. },
  153. },
  154. "responses": {
  155. "200": {
  156. "description": "Workspace created successfully",
  157. "content": {"application/json": {"schema": {"type": "object", "properties": {}}}},
  158. },
  159. "401": {"description": "Unauthorized - Authentication credentials are missing or invalid"},
  160. "403": {
  161. "description": "Forbidden - The authenticated user does not have permission to perform this action"
  162. },
  163. "500": {"description": "Internal Server Error - Something went wrong on the server side"},
  164. },
  165. }
  166. }
  167. },
  168. },
  169. "authentication": {
  170. "type": "bearer",
  171. "secret": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2M2RiNDlhY2RjYzhiZjdiMDk5MDhmZDYiLCJhdWQiOiI2M2RiNDlmN2RjYzhiZjdiMDk5MDkwM2MiLCJ1aWQiOiI2M2RiNDlhY2RjYzhiZjdiMDk5MDhmZDYiLCJpYXQiOjE3MDg5MTQ0MDcsImV4cCI6MTcwOTAwMDgwN30.vK6cH1qxPqjgeSdDym4b4fzwTwhW66s_L1suCvh3W98",
  172. },
  173. }
  174. # 测试带有action的助手
  175. def test_assistant_with_action_tools(
  176. get_weather_data_valid_payload, get_number_fact_valid_payload, create_workspace_with_authentication
  177. ):
  178. body = ActionBulkCreateRequest(**get_weather_data_valid_payload)
  179. body.authentication = Authentication(
  180. type=AuthenticationType.none,
  181. )
  182. actions = ActionService.create_actions_sync(session=session, body=body)
  183. [get_weather_data] = actions
  184. # get_number_fact
  185. body = ActionBulkCreateRequest(**get_number_fact_valid_payload)
  186. body.authentication = Authentication(
  187. type=AuthenticationType.none,
  188. )
  189. actions = ActionService.create_actions_sync(session=session, body=body)
  190. [get_number_fact] = actions
  191. client = openai.OpenAI(base_url="http://localhost:8086/api/v1", api_key="xxx")
  192. # 创建带有 action 的 assistant
  193. assistant = client.beta.assistants.create(
  194. name="Assistant Demo",
  195. instructions="你是一个有用的助手",
  196. tools=[
  197. {"type": "action", "id": get_weather_data.id},
  198. {"type": "action", "id": get_number_fact.id},
  199. ],
  200. model="gpt-3.5-turbo-1106",
  201. )
  202. print(assistant, end="\n\n")
  203. thread = client.beta.threads.create()
  204. print(thread, end="\n\n")
  205. message = client.beta.threads.messages.create(
  206. thread_id=thread.id,
  207. role="user",
  208. content="武汉的天气",
  209. )
  210. print(message, end="\n\n")
  211. run = client.beta.threads.runs.create(
  212. # model="gpt-3.5-turbo-1106",
  213. thread_id=thread.id,
  214. assistant_id=assistant.id,
  215. instructions="",
  216. )
  217. print(run, end="\n\n")
  218. while True:
  219. run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
  220. if run.status == "completed":
  221. print("done!", end="\n\n")
  222. messages = client.beta.threads.messages.list(thread_id=thread.id)
  223. print("messages: ")
  224. for message in messages:
  225. assert message.content[0].type == "text"
  226. print(messages)
  227. print({"role": message.role, "message": message.content[0].text.value})
  228. break
  229. else:
  230. print("\nin progress...")
  231. time.sleep(1)