Kevin Hu writinwaters commited on
Commit
f2b6717
·
1 Parent(s): 68148fe

Add user_id for third-party system to record sessions. (#4206)

Browse files

### What problem does this PR solve?


### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Documentation Update

---------

Co-authored-by: writinwaters <[email protected]>

api/apps/sdk/session.py CHANGED
@@ -47,7 +47,8 @@ def create(tenant_id, chat_id):
47
  "id": get_uuid(),
48
  "dialog_id": req["dialog_id"],
49
  "name": req.get("name", "New session"),
50
- "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}]
 
51
  }
52
  if not conv.get("name"):
53
  return get_error_data_result(message="`name` can not be empty.")
@@ -71,7 +72,7 @@ def create_agent_session(tenant_id, agent_id):
71
  return get_error_data_result("Agent not found.")
72
 
73
  if not UserCanvasService.query(user_id=tenant_id,id=agent_id):
74
- return get_error_data_result("You cannot access the agent.")
75
 
76
  if not isinstance(cvs.dsl, str):
77
  cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
@@ -197,11 +198,12 @@ def list_session(tenant_id, chat_id):
197
  page_number = int(request.args.get("page", 1))
198
  items_per_page = int(request.args.get("page_size", 30))
199
  orderby = request.args.get("orderby", "create_time")
 
200
  if request.args.get("desc") == "False" or request.args.get("desc") == "false":
201
  desc = False
202
  else:
203
  desc = True
204
- convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name)
205
  if not convs:
206
  return get_result(data=[])
207
  for conv in convs:
 
47
  "id": get_uuid(),
48
  "dialog_id": req["dialog_id"],
49
  "name": req.get("name", "New session"),
50
+ "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}],
51
+ "user_id": req.get("user_id", "")
52
  }
53
  if not conv.get("name"):
54
  return get_error_data_result(message="`name` can not be empty.")
 
72
  return get_error_data_result("Agent not found.")
73
 
74
  if not UserCanvasService.query(user_id=tenant_id,id=agent_id):
75
+ return get_error_data_result("You cannot access the agent.")
76
 
77
  if not isinstance(cvs.dsl, str):
78
  cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
 
198
  page_number = int(request.args.get("page", 1))
199
  items_per_page = int(request.args.get("page_size", 30))
200
  orderby = request.args.get("orderby", "create_time")
201
+ user_id = request.args.get("user_id")
202
  if request.args.get("desc") == "False" or request.args.get("desc") == "false":
203
  desc = False
204
  else:
205
  desc = True
206
+ convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name, user_id)
207
  if not convs:
208
  return get_result(data=[])
209
  for conv in convs:
api/db/db_models.py CHANGED
@@ -31,7 +31,6 @@ from peewee import (
31
  )
32
  from playhouse.pool import PooledMySQLDatabase, PooledPostgresqlDatabase
33
 
34
-
35
  from api.db import SerializedType, ParserType
36
  from api import settings
37
  from api import utils
@@ -926,6 +925,7 @@ class Conversation(DataBaseModel):
926
  name = CharField(max_length=255, null=True, help_text="converastion name", index=True)
927
  message = JSONField(null=True)
928
  reference = JSONField(null=True, default=[])
 
929
 
930
  class Meta:
931
  db_table = "conversation"
@@ -1070,13 +1070,13 @@ def migrate_db():
1070
  pass
1071
  try:
1072
  migrate(
1073
- migrator.add_column("tenant_llm","max_tokens",IntegerField(default=8192,index=True))
1074
  )
1075
  except Exception:
1076
  pass
1077
  try:
1078
  migrate(
1079
- migrator.add_column("api_4_conversation","dsl",JSONField(null=True, default={}))
1080
  )
1081
  except Exception:
1082
  pass
@@ -1105,3 +1105,10 @@ def migrate_db():
1105
  )
1106
  except Exception:
1107
  pass
 
 
 
 
 
 
 
 
31
  )
32
  from playhouse.pool import PooledMySQLDatabase, PooledPostgresqlDatabase
33
 
 
34
  from api.db import SerializedType, ParserType
35
  from api import settings
36
  from api import utils
 
925
  name = CharField(max_length=255, null=True, help_text="converastion name", index=True)
926
  message = JSONField(null=True)
927
  reference = JSONField(null=True, default=[])
928
+ user_id = CharField(max_length=255, null=True, help_text="user_id", index=True)
929
 
930
  class Meta:
931
  db_table = "conversation"
 
1070
  pass
1071
  try:
1072
  migrate(
1073
+ migrator.add_column("tenant_llm", "max_tokens", IntegerField(default=8192, index=True))
1074
  )
1075
  except Exception:
1076
  pass
1077
  try:
1078
  migrate(
1079
+ migrator.add_column("api_4_conversation", "dsl", JSONField(null=True, default={}))
1080
  )
1081
  except Exception:
1082
  pass
 
1105
  )
1106
  except Exception:
1107
  pass
1108
+ try:
1109
+ migrate(
1110
+ migrator.add_column("conversation", "user_id",
1111
+ CharField(max_length=255, null=True, help_text="user_id", index=True))
1112
+ )
1113
+ except Exception:
1114
+ pass
api/db/services/api_service.py CHANGED
@@ -41,11 +41,14 @@ class API4ConversationService(CommonService):
41
 
42
  @classmethod
43
  @DB.connection_context()
44
- def get_list(cls,dialog_id, tenant_id,
45
- page_number, items_per_page, orderby, desc, id):
46
- sessions = cls.model.select().where(cls.model.dialog_id ==dialog_id)
 
47
  if id:
48
  sessions = sessions.where(cls.model.id == id)
 
 
49
  if desc:
50
  sessions = sessions.order_by(cls.model.getter_by(orderby).desc())
51
  else:
 
41
 
42
  @classmethod
43
  @DB.connection_context()
44
+ def get_list(cls, dialog_id, tenant_id,
45
+ page_number, items_per_page,
46
+ orderby, desc, id, user_id=None):
47
+ sessions = cls.model.select().where(cls.model.dialog_id == dialog_id)
48
  if id:
49
  sessions = sessions.where(cls.model.id == id)
50
+ if user_id:
51
+ sessions = sessions.where(cls.model.user_id == user_id)
52
  if desc:
53
  sessions = sessions.order_by(cls.model.getter_by(orderby).desc())
54
  else:
api/db/services/conversation_service.py CHANGED
@@ -28,12 +28,14 @@ class ConversationService(CommonService):
28
 
29
  @classmethod
30
  @DB.connection_context()
31
- def get_list(cls,dialog_id,page_number, items_per_page, orderby, desc, id , name):
32
- sessions = cls.model.select().where(cls.model.dialog_id ==dialog_id)
33
  if id:
34
  sessions = sessions.where(cls.model.id == id)
35
  if name:
36
  sessions = sessions.where(cls.model.name == name)
 
 
37
  if desc:
38
  sessions = sessions.order_by(cls.model.getter_by(orderby).desc())
39
  else:
@@ -52,15 +54,16 @@ def structure_answer(conv, ans, message_id, session_id):
52
 
53
  def get_value(d, k1, k2):
54
  return d.get(k1, d.get(k2))
 
55
  chunk_list = [{
56
- "id": get_value(chunk, "chunk_id", "id"),
57
- "content": get_value(chunk, "content", "content_with_weight"),
58
- "document_id": get_value(chunk, "doc_id", "document_id"),
59
- "document_name": get_value(chunk, "docnm_kwd", "document_name"),
60
- "dataset_id": get_value(chunk, "kb_id", "dataset_id"),
61
- "image_id": get_value(chunk, "image_id", "img_id"),
62
- "positions": get_value(chunk, "positions", "position_int"),
63
- } for chunk in reference.get("chunks", [])]
64
 
65
  reference["chunks"] = chunk_list
66
  ans["id"] = message_id
@@ -88,10 +91,11 @@ def completion(tenant_id, chat_id, question, name="New session", session_id=None
88
  if not session_id:
89
  session_id = get_uuid()
90
  conv = {
91
- "id":session_id ,
92
  "dialog_id": chat_id,
93
  "name": name,
94
- "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}]
 
95
  }
96
  ConversationService.save(**conv)
97
  yield "data:" + json.dumps({"code": 0, "message": "",
@@ -226,4 +230,3 @@ def iframe_completion(dialog_id, question, session_id=None, stream=True, **kwarg
226
  API4ConversationService.append_message(conv.id, conv.to_dict())
227
  break
228
  yield answer
229
-
 
28
 
29
  @classmethod
30
  @DB.connection_context()
31
+ def get_list(cls, dialog_id, page_number, items_per_page, orderby, desc, id, name, user_id=None):
32
+ sessions = cls.model.select().where(cls.model.dialog_id == dialog_id)
33
  if id:
34
  sessions = sessions.where(cls.model.id == id)
35
  if name:
36
  sessions = sessions.where(cls.model.name == name)
37
+ if user_id:
38
+ sessions = sessions.where(cls.model.user_id == user_id)
39
  if desc:
40
  sessions = sessions.order_by(cls.model.getter_by(orderby).desc())
41
  else:
 
54
 
55
  def get_value(d, k1, k2):
56
  return d.get(k1, d.get(k2))
57
+
58
  chunk_list = [{
59
+ "id": get_value(chunk, "chunk_id", "id"),
60
+ "content": get_value(chunk, "content", "content_with_weight"),
61
+ "document_id": get_value(chunk, "doc_id", "document_id"),
62
+ "document_name": get_value(chunk, "docnm_kwd", "document_name"),
63
+ "dataset_id": get_value(chunk, "kb_id", "dataset_id"),
64
+ "image_id": get_value(chunk, "image_id", "img_id"),
65
+ "positions": get_value(chunk, "positions", "position_int"),
66
+ } for chunk in reference.get("chunks", [])]
67
 
68
  reference["chunks"] = chunk_list
69
  ans["id"] = message_id
 
91
  if not session_id:
92
  session_id = get_uuid()
93
  conv = {
94
+ "id": session_id,
95
  "dialog_id": chat_id,
96
  "name": name,
97
+ "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}],
98
+ "user_id": kwargs.get("user_id", "")
99
  }
100
  ConversationService.save(**conv)
101
  yield "data:" + json.dumps({"code": 0, "message": "",
 
230
  API4ConversationService.append_message(conv.id, conv.to_dict())
231
  break
232
  yield answer
 
docs/references/http_api_reference.md CHANGED
@@ -1721,6 +1721,7 @@ Creates a session with a chat assistant.
1721
  - `'Authorization: Bearer <YOUR_API_KEY>'`
1722
  - Body:
1723
  - `"name"`: `string`
 
1724
 
1725
  ##### Request example
1726
 
@@ -1741,6 +1742,8 @@ curl --request POST \
1741
  The ID of the associated chat assistant.
1742
  - `"name"`: (*Body parameter*), `string`
1743
  The name of the chat session to create.
 
 
1744
 
1745
  #### Response
1746
 
@@ -1793,6 +1796,7 @@ Updates a session of a specified chat assistant.
1793
  - `'Authorization: Bearer <YOUR_API_KEY>'`
1794
  - Body:
1795
  - `"name`: `string`
 
1796
 
1797
  ##### Request example
1798
 
@@ -1815,6 +1819,8 @@ curl --request PUT \
1815
  The ID of the session to update.
1816
  - `"name"`: (*Body Parameter*), `string`
1817
  The revised name of the session.
 
 
1818
 
1819
  #### Response
1820
 
@@ -1846,7 +1852,7 @@ Lists sessions associated with a specified chat assistant.
1846
  #### Request
1847
 
1848
  - Method: GET
1849
- - URL: `/api/v1/chats/{chat_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&name={session_name}&id={session_id}`
1850
  - Headers:
1851
  - `'Authorization: Bearer <YOUR_API_KEY>'`
1852
 
@@ -1876,6 +1882,8 @@ curl --request GET \
1876
  The name of the chat session to retrieve.
1877
  - `id`: (*Filter parameter*), `string`
1878
  The ID of the chat session to retrieve.
 
 
1879
 
1880
  #### Response
1881
 
@@ -2000,7 +2008,8 @@ Asks a specified chat assistant a question to start an AI-powered conversation.
2000
  - Body:
2001
  - `"question"`: `string`
2002
  - `"stream"`: `boolean`
2003
- - `"session_id"`: `string`
 
2004
 
2005
  ##### Request example
2006
 
@@ -2038,6 +2047,8 @@ curl --request POST \
2038
  - `false`: Disable streaming.
2039
  - `"session_id"`: (*Body Parameter*)
2040
  The ID of session. If it is not provided, a new session will be generated.
 
 
2041
 
2042
  #### Response
2043
 
@@ -2162,6 +2173,8 @@ Creates a session with an agent.
2162
  - Body:
2163
  - the required parameters:`str`
2164
  - the optional parameters:`str`
 
 
2165
 
2166
  ##### Request example
2167
  If `begin` component in the agent doesn't have required parameters:
@@ -2337,6 +2350,7 @@ Asks a specified agent a question to start an AI-powered conversation.
2337
  - `"question"`: `string`
2338
  - `"stream"`: `boolean`
2339
  - `"session_id"`: `string`
 
2340
  - other parameters: `string`
2341
  ##### Request example
2342
  If the `begin` component doesn't have parameters, the following code will create a session.
@@ -2388,6 +2402,8 @@ curl --request POST \
2388
  - `false`: Disable streaming.
2389
  - `"session_id"`: (*Body Parameter*)
2390
  The ID of the session. If it is not provided, a new session will be generated.
 
 
2391
  - Other parameters: (*Body Parameter*)
2392
  The parameters in the begin component.
2393
  #### Response
@@ -2538,7 +2554,7 @@ Failure:
2538
 
2539
  ### List agent sessions
2540
 
2541
- **GET** `/api/v1/agents/{agent_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&id={session_id}`
2542
 
2543
  Lists sessions associated with a specified agent.
2544
 
@@ -2553,7 +2569,7 @@ Lists sessions associated with a specified agent.
2553
 
2554
  ```bash
2555
  curl --request GET \
2556
- --url http://{address}/api/v1/agents/{agent_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&id={session_id} \
2557
  --header 'Authorization: Bearer <YOUR_API_KEY>'
2558
  ```
2559
 
@@ -2573,7 +2589,9 @@ curl --request GET \
2573
  Indicates whether the retrieved sessions should be sorted in descending order. Defaults to `true`.
2574
  - `id`: (*Filter parameter*), `string`
2575
  The ID of the agent session to retrieve.
2576
-
 
 
2577
  #### Response
2578
 
2579
  Success:
 
1721
  - `'Authorization: Bearer <YOUR_API_KEY>'`
1722
  - Body:
1723
  - `"name"`: `string`
1724
+ - `"user_id"`: `string`(optional)
1725
 
1726
  ##### Request example
1727
 
 
1742
  The ID of the associated chat assistant.
1743
  - `"name"`: (*Body parameter*), `string`
1744
  The name of the chat session to create.
1745
+ - `"user_id"`: (*Body parameter*), `string`
1746
+ Optional user-defined ID.
1747
 
1748
  #### Response
1749
 
 
1796
  - `'Authorization: Bearer <YOUR_API_KEY>'`
1797
  - Body:
1798
  - `"name`: `string`
1799
+ - `"user_id`: `string`(optional)
1800
 
1801
  ##### Request example
1802
 
 
1819
  The ID of the session to update.
1820
  - `"name"`: (*Body Parameter*), `string`
1821
  The revised name of the session.
1822
+ - `"user_id"`: (*Body parameter*), `string`
1823
+ Optional user-defined ID.
1824
 
1825
  #### Response
1826
 
 
1852
  #### Request
1853
 
1854
  - Method: GET
1855
+ - URL: `/api/v1/chats/{chat_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&name={session_name}&id={session_id}&user_id={user_id}`
1856
  - Headers:
1857
  - `'Authorization: Bearer <YOUR_API_KEY>'`
1858
 
 
1882
  The name of the chat session to retrieve.
1883
  - `id`: (*Filter parameter*), `string`
1884
  The ID of the chat session to retrieve.
1885
+ - `user_id`: (*Filter parameter*), `string`
1886
+ The optional user-defined ID passed in when creating session.
1887
 
1888
  #### Response
1889
 
 
2008
  - Body:
2009
  - `"question"`: `string`
2010
  - `"stream"`: `boolean`
2011
+ - `"session_id"`: `string`(optional)
2012
+ - `"user_id`: `string`(optional)
2013
 
2014
  ##### Request example
2015
 
 
2047
  - `false`: Disable streaming.
2048
  - `"session_id"`: (*Body Parameter*)
2049
  The ID of session. If it is not provided, a new session will be generated.
2050
+ - `"user_id"`: (*Body parameter*), `string`
2051
+ The optional user-defined ID. Valid *only* when no `session_id` is provided.
2052
 
2053
  #### Response
2054
 
 
2173
  - Body:
2174
  - the required parameters:`str`
2175
  - the optional parameters:`str`
2176
+ - `"user_id"`: `string`
2177
+ The optional user-defined ID.
2178
 
2179
  ##### Request example
2180
  If `begin` component in the agent doesn't have required parameters:
 
2350
  - `"question"`: `string`
2351
  - `"stream"`: `boolean`
2352
  - `"session_id"`: `string`
2353
+ - `"user_id"`: `string`(optional)
2354
  - other parameters: `string`
2355
  ##### Request example
2356
  If the `begin` component doesn't have parameters, the following code will create a session.
 
2402
  - `false`: Disable streaming.
2403
  - `"session_id"`: (*Body Parameter*)
2404
  The ID of the session. If it is not provided, a new session will be generated.
2405
+ - `"user_id"`: (*Body parameter*), `string`
2406
+ The optional user-defined ID. Valid *only* when no `session_id` is provided.
2407
  - Other parameters: (*Body Parameter*)
2408
  The parameters in the begin component.
2409
  #### Response
 
2554
 
2555
  ### List agent sessions
2556
 
2557
+ **GET** `/api/v1/agents/{agent_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&id={session_id}&user_id={user_id}`
2558
 
2559
  Lists sessions associated with a specified agent.
2560
 
 
2569
 
2570
  ```bash
2571
  curl --request GET \
2572
+ --url http://{address}/api/v1/agents/{agent_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&id={session_id}&user_id={user_id} \
2573
  --header 'Authorization: Bearer <YOUR_API_KEY>'
2574
  ```
2575
 
 
2589
  Indicates whether the retrieved sessions should be sorted in descending order. Defaults to `true`.
2590
  - `id`: (*Filter parameter*), `string`
2591
  The ID of the agent session to retrieve.
2592
+ - `user_id`: (*Filter parameter*), `string`
2593
+ The optional user-defined ID passed in when creating session.
2594
+
2595
  #### Response
2596
 
2597
  Success: