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

model_config.py 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import json
  2. from typing import cast
  3. from flask import request
  4. from flask_restx import Resource
  5. from werkzeug.exceptions import Forbidden
  6. from controllers.console import api
  7. from controllers.console.app.wraps import get_app_model
  8. from controllers.console.wraps import account_initialization_required, setup_required
  9. from core.agent.entities import AgentToolEntity
  10. from core.tools.tool_manager import ToolManager
  11. from core.tools.utils.configuration import ToolParameterConfigurationManager
  12. from events.app_event import app_model_config_was_updated
  13. from extensions.ext_database import db
  14. from libs.login import current_user, login_required
  15. from models.account import Account
  16. from models.model import AppMode, AppModelConfig
  17. from services.app_model_config_service import AppModelConfigService
  18. class ModelConfigResource(Resource):
  19. @setup_required
  20. @login_required
  21. @account_initialization_required
  22. @get_app_model(mode=[AppMode.AGENT_CHAT, AppMode.CHAT, AppMode.COMPLETION])
  23. def post(self, app_model):
  24. """Modify app model config"""
  25. if not isinstance(current_user, Account):
  26. raise Forbidden()
  27. if not current_user.has_edit_permission:
  28. raise Forbidden()
  29. assert current_user.current_tenant_id is not None, "The tenant information should be loaded."
  30. # validate config
  31. model_configuration = AppModelConfigService.validate_configuration(
  32. tenant_id=current_user.current_tenant_id,
  33. config=cast(dict, request.json),
  34. app_mode=AppMode.value_of(app_model.mode),
  35. )
  36. new_app_model_config = AppModelConfig(
  37. app_id=app_model.id,
  38. created_by=current_user.id,
  39. updated_by=current_user.id,
  40. )
  41. new_app_model_config = new_app_model_config.from_model_config_dict(model_configuration)
  42. if app_model.mode == AppMode.AGENT_CHAT.value or app_model.is_agent:
  43. # get original app model config
  44. original_app_model_config = (
  45. db.session.query(AppModelConfig).where(AppModelConfig.id == app_model.app_model_config_id).first()
  46. )
  47. if original_app_model_config is None:
  48. raise ValueError("Original app model config not found")
  49. agent_mode = original_app_model_config.agent_mode_dict
  50. # decrypt agent tool parameters if it's secret-input
  51. parameter_map = {}
  52. masked_parameter_map = {}
  53. tool_map = {}
  54. for tool in agent_mode.get("tools") or []:
  55. if not isinstance(tool, dict) or len(tool.keys()) <= 3:
  56. continue
  57. agent_tool_entity = AgentToolEntity(**tool)
  58. # get tool
  59. try:
  60. tool_runtime = ToolManager.get_agent_tool_runtime(
  61. tenant_id=current_user.current_tenant_id,
  62. app_id=app_model.id,
  63. agent_tool=agent_tool_entity,
  64. )
  65. manager = ToolParameterConfigurationManager(
  66. tenant_id=current_user.current_tenant_id,
  67. tool_runtime=tool_runtime,
  68. provider_name=agent_tool_entity.provider_id,
  69. provider_type=agent_tool_entity.provider_type,
  70. identity_id=f"AGENT.{app_model.id}",
  71. )
  72. except Exception:
  73. continue
  74. # get decrypted parameters
  75. if agent_tool_entity.tool_parameters:
  76. parameters = manager.decrypt_tool_parameters(agent_tool_entity.tool_parameters or {})
  77. masked_parameter = manager.mask_tool_parameters(parameters or {})
  78. else:
  79. parameters = {}
  80. masked_parameter = {}
  81. key = f"{agent_tool_entity.provider_id}.{agent_tool_entity.provider_type}.{agent_tool_entity.tool_name}"
  82. masked_parameter_map[key] = masked_parameter
  83. parameter_map[key] = parameters
  84. tool_map[key] = tool_runtime
  85. # encrypt agent tool parameters if it's secret-input
  86. agent_mode = new_app_model_config.agent_mode_dict
  87. for tool in agent_mode.get("tools") or []:
  88. agent_tool_entity = AgentToolEntity(**tool)
  89. # get tool
  90. key = f"{agent_tool_entity.provider_id}.{agent_tool_entity.provider_type}.{agent_tool_entity.tool_name}"
  91. if key in tool_map:
  92. tool_runtime = tool_map[key]
  93. else:
  94. try:
  95. tool_runtime = ToolManager.get_agent_tool_runtime(
  96. tenant_id=current_user.current_tenant_id,
  97. app_id=app_model.id,
  98. agent_tool=agent_tool_entity,
  99. )
  100. except Exception:
  101. continue
  102. manager = ToolParameterConfigurationManager(
  103. tenant_id=current_user.current_tenant_id,
  104. tool_runtime=tool_runtime,
  105. provider_name=agent_tool_entity.provider_id,
  106. provider_type=agent_tool_entity.provider_type,
  107. identity_id=f"AGENT.{app_model.id}",
  108. )
  109. manager.delete_tool_parameters_cache()
  110. # override parameters if it equals to masked parameters
  111. if agent_tool_entity.tool_parameters:
  112. if key not in masked_parameter_map:
  113. continue
  114. for masked_key, masked_value in masked_parameter_map[key].items():
  115. if (
  116. masked_key in agent_tool_entity.tool_parameters
  117. and agent_tool_entity.tool_parameters[masked_key] == masked_value
  118. ):
  119. agent_tool_entity.tool_parameters[masked_key] = parameter_map[key].get(masked_key)
  120. # encrypt parameters
  121. if agent_tool_entity.tool_parameters:
  122. tool["tool_parameters"] = manager.encrypt_tool_parameters(agent_tool_entity.tool_parameters or {})
  123. # update app model config
  124. new_app_model_config.agent_mode = json.dumps(agent_mode)
  125. db.session.add(new_app_model_config)
  126. db.session.flush()
  127. app_model.app_model_config_id = new_app_model_config.id
  128. db.session.commit()
  129. app_model_config_was_updated.send(app_model, app_model_config=new_app_model_config)
  130. return {"result": "success"}
  131. api.add_resource(ModelConfigResource, "/apps/<uuid:app_id>/model-config")