Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

model_config.py 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import json
  2. from typing import cast
  3. from flask import request
  4. from flask_login import current_user
  5. from flask_restx import Resource, fields
  6. from werkzeug.exceptions import Forbidden
  7. from controllers.console import api, console_ns
  8. from controllers.console.app.wraps import get_app_model
  9. from controllers.console.wraps import account_initialization_required, setup_required
  10. from core.agent.entities import AgentToolEntity
  11. from core.tools.tool_manager import ToolManager
  12. from core.tools.utils.configuration import ToolParameterConfigurationManager
  13. from events.app_event import app_model_config_was_updated
  14. from extensions.ext_database import db
  15. from libs.login import login_required
  16. from models.account import Account
  17. from models.model import AppMode, AppModelConfig
  18. from services.app_model_config_service import AppModelConfigService
  19. @console_ns.route("/apps/<uuid:app_id>/model-config")
  20. class ModelConfigResource(Resource):
  21. @api.doc("update_app_model_config")
  22. @api.doc(description="Update application model configuration")
  23. @api.doc(params={"app_id": "Application ID"})
  24. @api.expect(
  25. api.model(
  26. "ModelConfigRequest",
  27. {
  28. "provider": fields.String(description="Model provider"),
  29. "model": fields.String(description="Model name"),
  30. "configs": fields.Raw(description="Model configuration parameters"),
  31. "opening_statement": fields.String(description="Opening statement"),
  32. "suggested_questions": fields.List(fields.String(), description="Suggested questions"),
  33. "more_like_this": fields.Raw(description="More like this configuration"),
  34. "speech_to_text": fields.Raw(description="Speech to text configuration"),
  35. "text_to_speech": fields.Raw(description="Text to speech configuration"),
  36. "retrieval_model": fields.Raw(description="Retrieval model configuration"),
  37. "tools": fields.List(fields.Raw(), description="Available tools"),
  38. "dataset_configs": fields.Raw(description="Dataset configurations"),
  39. "agent_mode": fields.Raw(description="Agent mode configuration"),
  40. },
  41. )
  42. )
  43. @api.response(200, "Model configuration updated successfully")
  44. @api.response(400, "Invalid configuration")
  45. @api.response(404, "App not found")
  46. @setup_required
  47. @login_required
  48. @account_initialization_required
  49. @get_app_model(mode=[AppMode.AGENT_CHAT, AppMode.CHAT, AppMode.COMPLETION])
  50. def post(self, app_model):
  51. """Modify app model config"""
  52. if not isinstance(current_user, Account):
  53. raise Forbidden()
  54. if not current_user.has_edit_permission:
  55. raise Forbidden()
  56. assert current_user.current_tenant_id is not None, "The tenant information should be loaded."
  57. # validate config
  58. model_configuration = AppModelConfigService.validate_configuration(
  59. tenant_id=current_user.current_tenant_id,
  60. config=cast(dict, request.json),
  61. app_mode=AppMode.value_of(app_model.mode),
  62. )
  63. new_app_model_config = AppModelConfig(
  64. app_id=app_model.id,
  65. created_by=current_user.id,
  66. updated_by=current_user.id,
  67. )
  68. new_app_model_config = new_app_model_config.from_model_config_dict(model_configuration)
  69. if app_model.mode == AppMode.AGENT_CHAT or app_model.is_agent:
  70. # get original app model config
  71. original_app_model_config = (
  72. db.session.query(AppModelConfig).where(AppModelConfig.id == app_model.app_model_config_id).first()
  73. )
  74. if original_app_model_config is None:
  75. raise ValueError("Original app model config not found")
  76. agent_mode = original_app_model_config.agent_mode_dict
  77. # decrypt agent tool parameters if it's secret-input
  78. parameter_map = {}
  79. masked_parameter_map = {}
  80. tool_map = {}
  81. for tool in agent_mode.get("tools") or []:
  82. if not isinstance(tool, dict) or len(tool.keys()) <= 3:
  83. continue
  84. agent_tool_entity = AgentToolEntity(**tool)
  85. # get tool
  86. try:
  87. tool_runtime = ToolManager.get_agent_tool_runtime(
  88. tenant_id=current_user.current_tenant_id,
  89. app_id=app_model.id,
  90. agent_tool=agent_tool_entity,
  91. )
  92. manager = ToolParameterConfigurationManager(
  93. tenant_id=current_user.current_tenant_id,
  94. tool_runtime=tool_runtime,
  95. provider_name=agent_tool_entity.provider_id,
  96. provider_type=agent_tool_entity.provider_type,
  97. identity_id=f"AGENT.{app_model.id}",
  98. )
  99. except Exception:
  100. continue
  101. # get decrypted parameters
  102. if agent_tool_entity.tool_parameters:
  103. parameters = manager.decrypt_tool_parameters(agent_tool_entity.tool_parameters or {})
  104. masked_parameter = manager.mask_tool_parameters(parameters or {})
  105. else:
  106. parameters = {}
  107. masked_parameter = {}
  108. key = f"{agent_tool_entity.provider_id}.{agent_tool_entity.provider_type}.{agent_tool_entity.tool_name}"
  109. masked_parameter_map[key] = masked_parameter
  110. parameter_map[key] = parameters
  111. tool_map[key] = tool_runtime
  112. # encrypt agent tool parameters if it's secret-input
  113. agent_mode = new_app_model_config.agent_mode_dict
  114. for tool in agent_mode.get("tools") or []:
  115. agent_tool_entity = AgentToolEntity(**tool)
  116. # get tool
  117. key = f"{agent_tool_entity.provider_id}.{agent_tool_entity.provider_type}.{agent_tool_entity.tool_name}"
  118. if key in tool_map:
  119. tool_runtime = tool_map[key]
  120. else:
  121. try:
  122. tool_runtime = ToolManager.get_agent_tool_runtime(
  123. tenant_id=current_user.current_tenant_id,
  124. app_id=app_model.id,
  125. agent_tool=agent_tool_entity,
  126. )
  127. except Exception:
  128. continue
  129. manager = ToolParameterConfigurationManager(
  130. tenant_id=current_user.current_tenant_id,
  131. tool_runtime=tool_runtime,
  132. provider_name=agent_tool_entity.provider_id,
  133. provider_type=agent_tool_entity.provider_type,
  134. identity_id=f"AGENT.{app_model.id}",
  135. )
  136. manager.delete_tool_parameters_cache()
  137. # override parameters if it equals to masked parameters
  138. if agent_tool_entity.tool_parameters:
  139. if key not in masked_parameter_map:
  140. continue
  141. for masked_key, masked_value in masked_parameter_map[key].items():
  142. if (
  143. masked_key in agent_tool_entity.tool_parameters
  144. and agent_tool_entity.tool_parameters[masked_key] == masked_value
  145. ):
  146. agent_tool_entity.tool_parameters[masked_key] = parameter_map[key].get(masked_key)
  147. # encrypt parameters
  148. if agent_tool_entity.tool_parameters:
  149. tool["tool_parameters"] = manager.encrypt_tool_parameters(agent_tool_entity.tool_parameters or {})
  150. # update app model config
  151. new_app_model_config.agent_mode = json.dumps(agent_mode)
  152. db.session.add(new_app_model_config)
  153. db.session.flush()
  154. app_model.app_model_config_id = new_app_model_config.id
  155. db.session.commit()
  156. app_model_config_was_updated.send(app_model, app_model_config=new_app_model_config)
  157. return {"result": "success"}