dify/api/core/agent/strategy/plugin.py

62 lines
2.1 KiB
Python
Raw Normal View History

2024-12-24 18:38:34 +08:00
from collections.abc import Generator, Sequence
from typing import Any, Optional
2024-12-09 23:02:11 +08:00
from core.agent.entities import AgentInvokeMessage
from core.agent.plugin_entities import AgentStrategyEntity, AgentStrategyParameter
2024-12-09 23:02:11 +08:00
from core.agent.strategy.base import BaseAgentStrategy
from core.plugin.manager.agent import PluginAgentManager
2024-12-13 19:50:54 +08:00
from core.plugin.utils.converter import convert_parameters_to_plugin_format
2024-12-09 23:02:11 +08:00
class PluginAgentStrategy(BaseAgentStrategy):
"""
Agent Strategy
"""
tenant_id: str
plugin_unique_identifier: str
declaration: AgentStrategyEntity
def __init__(self, tenant_id: str, plugin_unique_identifier: str, declaration: AgentStrategyEntity):
self.tenant_id = tenant_id
self.plugin_unique_identifier = plugin_unique_identifier
self.declaration = declaration
def get_parameters(self) -> Sequence[AgentStrategyParameter]:
2024-12-09 23:02:11 +08:00
return self.declaration.parameters
2024-12-13 19:50:54 +08:00
def initialize_parameters(self, params: dict[str, Any]) -> dict[str, Any]:
"""
Initialize the parameters for the agent strategy.
"""
for parameter in self.declaration.parameters:
params[parameter.name] = parameter.init_frontend_parameter(params.get(parameter.name))
return params
2024-12-09 23:02:11 +08:00
def _invoke(
self,
params: dict[str, Any],
user_id: str,
conversation_id: Optional[str] = None,
app_id: Optional[str] = None,
message_id: Optional[str] = None,
) -> Generator[AgentInvokeMessage, None, None]:
"""
Invoke the agent strategy.
"""
manager = PluginAgentManager()
2024-12-13 19:50:54 +08:00
initialized_params = self.initialize_parameters(params)
params = convert_parameters_to_plugin_format(initialized_params)
2024-12-09 23:02:11 +08:00
yield from manager.invoke(
tenant_id=self.tenant_id,
user_id=user_id,
agent_provider=self.declaration.identity.provider,
agent_strategy=self.declaration.identity.name,
agent_params=params,
conversation_id=conversation_id,
app_id=app_id,
message_id=message_id,
)