ms-agent 0.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ms_agent/__init__.py +1 -0
- ms_agent/agent/__init__.py +6 -0
- ms_agent/agent/base.py +98 -0
- ms_agent/agent/code/__init__.py +2 -0
- ms_agent/agent/code/base.py +27 -0
- ms_agent/agent/code_agent.py +64 -0
- ms_agent/agent/llm_agent.py +347 -0
- ms_agent/agent/memory/__init__.py +3 -0
- ms_agent/agent/memory/base.py +21 -0
- ms_agent/agent/memory/mem0.py +2 -0
- ms_agent/agent/memory/utils.py +2 -0
- ms_agent/agent/plan/__init__.py +2 -0
- ms_agent/agent/plan/base.py +36 -0
- ms_agent/agent/plan/utils.py +3 -0
- ms_agent/agent/runtime.py +29 -0
- ms_agent/callbacks/__init__.py +3 -0
- ms_agent/callbacks/base.py +98 -0
- ms_agent/callbacks/utils.py +2 -0
- ms_agent/cli/__init__.py +1 -0
- ms_agent/cli/input_callback.py +33 -0
- ms_agent/cli/main.py +28 -0
- ms_agent/cli/run.py +70 -0
- ms_agent/config/__init__.py +3 -0
- ms_agent/config/config.py +171 -0
- ms_agent/config/env.py +17 -0
- ms_agent/llm/__init__.py +3 -0
- ms_agent/llm/claude.py +2 -0
- ms_agent/llm/dashscope_llm.py +37 -0
- ms_agent/llm/deepseek_llm.py +98 -0
- ms_agent/llm/llm.py +70 -0
- ms_agent/llm/model_mapping.py +8 -0
- ms_agent/llm/modelscope_llm.py +12 -0
- ms_agent/llm/openai_llm.py +369 -0
- ms_agent/llm/utils.py +49 -0
- ms_agent/rag/__init__.py +1 -0
- ms_agent/rag/base.py +61 -0
- ms_agent/rag/utils.py +2 -0
- ms_agent/tools/__init__.py +5 -0
- ms_agent/tools/base.py +58 -0
- ms_agent/tools/filesystem_tool.py +202 -0
- ms_agent/tools/mcp_client.py +166 -0
- ms_agent/tools/split_task.py +85 -0
- ms_agent/tools/tool_manager.py +79 -0
- ms_agent/utils/__init__.py +4 -0
- ms_agent/utils/llm_utils.py +84 -0
- ms_agent/utils/logger.py +119 -0
- ms_agent/utils/utils.py +71 -0
- ms_agent/version.py +1 -0
- ms_agent/workflow/__init__.py +1 -0
- ms_agent/workflow/base.py +36 -0
- ms_agent/workflow/chain_workflow.py +101 -0
- ms_agent-0.0.0.dist-info/METADATA +299 -0
- ms_agent-0.0.0.dist-info/RECORD +63 -0
- ms_agent-0.0.0.dist-info/WHEEL +5 -0
- ms_agent-0.0.0.dist-info/entry_points.txt +2 -0
- ms_agent-0.0.0.dist-info/licenses/LICENSE +203 -0
- ms_agent-0.0.0.dist-info/top_level.txt +2 -0
- temp/__init__.py +0 -0
- temp/mcp_tests/__init__.py +0 -0
- temp/mcp_tests/mcp_playground_origin/__init__.py +0 -0
- temp/mcp_tests/mcp_playground_origin/test_app.py +531 -0
- temp/mcp_tests/mcp_playground_origin/test_mcp_client.py +238 -0
- temp/mcp_tests/run_mcp_client.py +109 -0
ms_agent/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
ms_agent/agent/base.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
|
2
|
+
import importlib
|
|
3
|
+
import inspect
|
|
4
|
+
import sys
|
|
5
|
+
from abc import abstractmethod
|
|
6
|
+
from typing import Dict, List, Optional, Union
|
|
7
|
+
|
|
8
|
+
from ms_agent.config import Config
|
|
9
|
+
from ms_agent.config.config import ConfigLifecycleHandler
|
|
10
|
+
from ms_agent.llm import Message
|
|
11
|
+
from omegaconf import DictConfig
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Agent:
|
|
15
|
+
"""The base Agent class.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
config_dir_or_id (`Optional[str]`): The directory or id of the config file.
|
|
19
|
+
config (`Optional[DictConfig]`): The configuration object.
|
|
20
|
+
env (`Optional[Dict[str, str]]`): The extra environment variables.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
DEFAULT_TAG = 'Agent-default'
|
|
24
|
+
|
|
25
|
+
def __init__(self,
|
|
26
|
+
config_dir_or_id: Optional[str] = None,
|
|
27
|
+
config: Optional[DictConfig] = None,
|
|
28
|
+
env: Optional[Dict[str, str]] = None,
|
|
29
|
+
tag: Optional[str] = None,
|
|
30
|
+
trust_remote_code: bool = False):
|
|
31
|
+
if config_dir_or_id is None:
|
|
32
|
+
self.config: DictConfig = config
|
|
33
|
+
else:
|
|
34
|
+
self.config: DictConfig = Config.from_task(config_dir_or_id, env)
|
|
35
|
+
if tag is None:
|
|
36
|
+
self.tag = getattr(config, 'tag', None) or self.DEFAULT_TAG
|
|
37
|
+
else:
|
|
38
|
+
self.tag = tag
|
|
39
|
+
self.config.tag = self.tag
|
|
40
|
+
self.trust_remote_code = trust_remote_code
|
|
41
|
+
self.config.trust_remote_code = trust_remote_code
|
|
42
|
+
self.handler: Optional[ConfigLifecycleHandler] = None
|
|
43
|
+
self._register_config_handler()
|
|
44
|
+
|
|
45
|
+
def _register_config_handler(self):
|
|
46
|
+
handler_file = getattr(self.config, 'handler', None)
|
|
47
|
+
if handler_file is not None:
|
|
48
|
+
local_dir = self.config.local_dir
|
|
49
|
+
assert self.trust_remote_code, (
|
|
50
|
+
f'[External Code]A Config Lifecycle handler '
|
|
51
|
+
f'registered in the config: {handler_file}. '
|
|
52
|
+
f'\nThis is external code, if you trust this workflow, '
|
|
53
|
+
f'please specify `--trust_remote_code true`')
|
|
54
|
+
assert local_dir is not None, 'Using external py files, but local_dir cannot be found.'
|
|
55
|
+
if local_dir not in sys.path:
|
|
56
|
+
sys.path.insert(0, local_dir)
|
|
57
|
+
|
|
58
|
+
handler_module = importlib.import_module(handler_file)
|
|
59
|
+
module_classes = {
|
|
60
|
+
name: cls
|
|
61
|
+
for name, cls in inspect.getmembers(handler_module,
|
|
62
|
+
inspect.isclass)
|
|
63
|
+
}
|
|
64
|
+
for name, cls in module_classes.items():
|
|
65
|
+
# Find cls which base class is `Callback`
|
|
66
|
+
if cls.__bases__[
|
|
67
|
+
0] is ConfigLifecycleHandler and cls.__module__ == handler_file:
|
|
68
|
+
self.handler = cls()
|
|
69
|
+
assert self.handler is not None, 'Config Lifecycle handler registered, but cannot be initialized.'
|
|
70
|
+
|
|
71
|
+
def _task_begin(self):
|
|
72
|
+
if self.handler is not None:
|
|
73
|
+
self.config = self.handler.task_begin(self.config, self.tag)
|
|
74
|
+
|
|
75
|
+
def prepare_config_for_next_step(self):
|
|
76
|
+
"""Call ConfigLifecycleHandler.task_end to prepare config for the next step.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
The new config for next step.
|
|
80
|
+
"""
|
|
81
|
+
if self.handler is not None:
|
|
82
|
+
config = self.handler.task_end(self.config, self.tag)
|
|
83
|
+
else:
|
|
84
|
+
config = self.config
|
|
85
|
+
return config
|
|
86
|
+
|
|
87
|
+
@abstractmethod
|
|
88
|
+
async def run(self, inputs: Union[str, List[Message]],
|
|
89
|
+
**kwargs) -> List[Message]:
|
|
90
|
+
"""Run the agent.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
inputs(`Union[str, List[Message]]`): The inputs can be a prompt string,
|
|
94
|
+
or a list of messages from the previous agent
|
|
95
|
+
Returns:
|
|
96
|
+
The final messages
|
|
97
|
+
"""
|
|
98
|
+
pass
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
|
2
|
+
from abc import abstractmethod
|
|
3
|
+
from typing import List, Union
|
|
4
|
+
|
|
5
|
+
from ms_agent.llm import Message
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Code:
|
|
9
|
+
"""A code class can be executed in a `CodeAgent` in a workflow"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, config=None):
|
|
12
|
+
self.config = config
|
|
13
|
+
|
|
14
|
+
@abstractmethod
|
|
15
|
+
async def run(self, inputs: Union[str, List[Message]],
|
|
16
|
+
**kwargs) -> List[Message]:
|
|
17
|
+
"""Run the code
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
inputs(`Union[str, List[Message]]`): The inputs can be a prompt string,
|
|
21
|
+
or a list of messages from the previous agent
|
|
22
|
+
**kwargs:
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
The messages to output to the next agent
|
|
26
|
+
"""
|
|
27
|
+
pass
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
|
2
|
+
import importlib
|
|
3
|
+
import inspect
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from typing import Dict, Optional
|
|
7
|
+
|
|
8
|
+
from omegaconf import DictConfig
|
|
9
|
+
|
|
10
|
+
from . import Agent
|
|
11
|
+
from .code import Code
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CodeAgent(Agent):
|
|
15
|
+
|
|
16
|
+
def __init__(self,
|
|
17
|
+
config_dir_or_id: Optional[str] = None,
|
|
18
|
+
config: Optional[DictConfig] = None,
|
|
19
|
+
env: Optional[Dict[str, str]] = None,
|
|
20
|
+
*,
|
|
21
|
+
code_file: str,
|
|
22
|
+
**kwargs):
|
|
23
|
+
super().__init__(
|
|
24
|
+
config_dir_or_id,
|
|
25
|
+
config,
|
|
26
|
+
env,
|
|
27
|
+
tag=kwargs.get('tag'),
|
|
28
|
+
trust_remote_code=kwargs.get('trust_remote_code', False))
|
|
29
|
+
self.code_file = code_file
|
|
30
|
+
|
|
31
|
+
async def run(self, inputs, **kwargs):
|
|
32
|
+
"""Run the agent.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
inputs(`Union[str, List[Message]]`): The inputs can be a prompt string,
|
|
36
|
+
or a list of messages from the previous agent
|
|
37
|
+
Returns:
|
|
38
|
+
The final messages
|
|
39
|
+
"""
|
|
40
|
+
assert self.trust_remote_code, (
|
|
41
|
+
f'[External Code]A code file is required to run in the CodeAgent: {self.code_file}'
|
|
42
|
+
f'\nThis is external code, if you trust this code file, '
|
|
43
|
+
f'please specify `--trust_remote_code true`')
|
|
44
|
+
subdir = os.path.dirname(self.code_file)
|
|
45
|
+
code_file = os.path.basename(self.code_file)
|
|
46
|
+
local_dir = self.config.local_dir
|
|
47
|
+
assert local_dir is not None, 'Using external py files, but local_dir cannot be found.'
|
|
48
|
+
if subdir:
|
|
49
|
+
subdir = os.path.join(local_dir, subdir)
|
|
50
|
+
if local_dir not in sys.path:
|
|
51
|
+
sys.path.insert(0, local_dir)
|
|
52
|
+
if subdir and subdir not in sys.path:
|
|
53
|
+
sys.path.insert(0, subdir)
|
|
54
|
+
code_module = importlib.import_module(code_file)
|
|
55
|
+
module_classes = {
|
|
56
|
+
name: cls
|
|
57
|
+
for name, cls in inspect.getmembers(code_module, inspect.isclass)
|
|
58
|
+
}
|
|
59
|
+
for name, cls in module_classes.items():
|
|
60
|
+
if cls.__bases__[0] is Code and cls.__module__ == code_file:
|
|
61
|
+
instance = cls(self.config)
|
|
62
|
+
messages = await instance.run(inputs, **kwargs)
|
|
63
|
+
return messages
|
|
64
|
+
return inputs
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
|
2
|
+
import importlib
|
|
3
|
+
import inspect
|
|
4
|
+
import os.path
|
|
5
|
+
import sys
|
|
6
|
+
from copy import deepcopy
|
|
7
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from ms_agent.callbacks import Callback, callbacks_mapping
|
|
11
|
+
from ms_agent.llm.llm import LLM
|
|
12
|
+
from ms_agent.llm.utils import Message, Tool
|
|
13
|
+
from ms_agent.rag.base import Rag
|
|
14
|
+
from ms_agent.rag.utils import rag_mapping
|
|
15
|
+
from ms_agent.tools import ToolManager
|
|
16
|
+
from ms_agent.utils import async_retry
|
|
17
|
+
from ms_agent.utils.logger import logger
|
|
18
|
+
from omegaconf import DictConfig
|
|
19
|
+
|
|
20
|
+
from ..utils.utils import read_history, save_history
|
|
21
|
+
from .base import Agent
|
|
22
|
+
from .memory import Memory, memory_mapping
|
|
23
|
+
from .plan.base import Planer
|
|
24
|
+
from .plan.utils import planer_mapping
|
|
25
|
+
from .runtime import Runtime
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class LLMAgent(Agent):
|
|
29
|
+
"""Agent running for llm-based tasks.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
config_dir_or_id (`Optional[str]`): The directory or id of the config file.
|
|
33
|
+
config (`Optional[DictConfig]`): The configuration object.
|
|
34
|
+
env (`Optional[Dict[str, str]]`): The extra environment variables.
|
|
35
|
+
mcp_config(`Optional[Dict[str, Any]]`): The extra mcp config file location.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
DEFAULT_SYSTEM = 'You are a helpful assistant.'
|
|
39
|
+
|
|
40
|
+
def __init__(self,
|
|
41
|
+
config_dir_or_id: Optional[str] = None,
|
|
42
|
+
config: Optional[DictConfig] = None,
|
|
43
|
+
env: Optional[Dict[str, str]] = None,
|
|
44
|
+
**kwargs):
|
|
45
|
+
super().__init__(
|
|
46
|
+
config_dir_or_id,
|
|
47
|
+
config,
|
|
48
|
+
env,
|
|
49
|
+
tag=kwargs.get('tag'),
|
|
50
|
+
trust_remote_code=kwargs.get('trust_remote_code', False))
|
|
51
|
+
self.callbacks: List[Callback] = []
|
|
52
|
+
self.tool_manager: Optional[ToolManager] = None
|
|
53
|
+
self.memory_tools: List[Memory] = []
|
|
54
|
+
self.planer: Optional[Planer] = None
|
|
55
|
+
self.rag: Optional[Rag] = None
|
|
56
|
+
self.llm: Optional[LLM] = None
|
|
57
|
+
self.runtime: Optional[Runtime] = None
|
|
58
|
+
self.max_chat_round: int = 0
|
|
59
|
+
self.task = kwargs.get('task', 'default')
|
|
60
|
+
self.load_cache = kwargs.get('load_cache', True)
|
|
61
|
+
self.mcp_server_file = kwargs.get('mcp_server_file', None)
|
|
62
|
+
self.mcp_config: Dict[str, Any] = self._parse_mcp_servers()
|
|
63
|
+
self._task_begin()
|
|
64
|
+
|
|
65
|
+
def register_callback(self, callback: Callback):
|
|
66
|
+
"""Register a callback."""
|
|
67
|
+
self.callbacks.append(callback)
|
|
68
|
+
|
|
69
|
+
def _parse_mcp_servers(self) -> Dict[str, Any]:
|
|
70
|
+
if self.mcp_server_file is not None and os.path.isfile(
|
|
71
|
+
self.mcp_server_file):
|
|
72
|
+
with open(self.mcp_server_file, 'r') as f:
|
|
73
|
+
return json.load(f)
|
|
74
|
+
return {}
|
|
75
|
+
|
|
76
|
+
def _register_callback_from_config(self):
|
|
77
|
+
local_dir = self.config.local_dir if hasattr(self.config,
|
|
78
|
+
'local_dir') else None
|
|
79
|
+
if hasattr(self.config, 'callbacks'):
|
|
80
|
+
callbacks = self.config.callbacks or []
|
|
81
|
+
for _callback in callbacks:
|
|
82
|
+
subdir = os.path.dirname(_callback)
|
|
83
|
+
assert local_dir is not None, 'Using external py files, but local_dir cannot be found.'
|
|
84
|
+
if subdir:
|
|
85
|
+
subdir = os.path.join(local_dir, str(subdir))
|
|
86
|
+
_callback = os.path.basename(_callback)
|
|
87
|
+
if _callback not in callbacks_mapping:
|
|
88
|
+
if not self.trust_remote_code:
|
|
89
|
+
raise AssertionError(
|
|
90
|
+
'[External Code Found] Your config file contains external code, '
|
|
91
|
+
'instantiate the code may be UNSAFE, if you trust the code, '
|
|
92
|
+
'please pass `trust_remote_code=True` or `--trust_remote_code true`'
|
|
93
|
+
)
|
|
94
|
+
if local_dir not in sys.path:
|
|
95
|
+
sys.path.insert(0, local_dir)
|
|
96
|
+
if subdir and subdir not in sys.path:
|
|
97
|
+
sys.path.insert(0, subdir)
|
|
98
|
+
callback_file = importlib.import_module(_callback)
|
|
99
|
+
module_classes = {
|
|
100
|
+
name: cls
|
|
101
|
+
for name, cls in inspect.getmembers(
|
|
102
|
+
callback_file, inspect.isclass)
|
|
103
|
+
}
|
|
104
|
+
for name, cls in module_classes.items():
|
|
105
|
+
# Find cls which base class is `Callback`
|
|
106
|
+
if issubclass(
|
|
107
|
+
cls, Callback) and cls.__module__ == _callback:
|
|
108
|
+
self.callbacks.append(cls(self.config))
|
|
109
|
+
else:
|
|
110
|
+
self.callbacks.append(callbacks_mapping[_callback](
|
|
111
|
+
self.config))
|
|
112
|
+
|
|
113
|
+
async def _loop_callback(self, point, messages: List[Message]):
|
|
114
|
+
for callback in self.callbacks:
|
|
115
|
+
await getattr(callback, point)(self.runtime, messages)
|
|
116
|
+
|
|
117
|
+
async def _parallel_tool_call(self,
|
|
118
|
+
messages: List[Message]) -> List[Message]:
|
|
119
|
+
tool_call_result = await self.tool_manager.parallel_call_tool(
|
|
120
|
+
messages[-1].tool_calls)
|
|
121
|
+
assert len(tool_call_result) == len(messages[-1].tool_calls)
|
|
122
|
+
for tool_call_result, tool_call_query in zip(tool_call_result,
|
|
123
|
+
messages[-1].tool_calls):
|
|
124
|
+
_new_message = Message(
|
|
125
|
+
role='tool',
|
|
126
|
+
content=tool_call_result,
|
|
127
|
+
tool_call_id=tool_call_query['id'],
|
|
128
|
+
name=tool_call_query['tool_name'])
|
|
129
|
+
messages.append(_new_message)
|
|
130
|
+
self._log_output(_new_message.content, self.tag)
|
|
131
|
+
return messages
|
|
132
|
+
|
|
133
|
+
async def _prepare_tools(self):
|
|
134
|
+
self.tool_manager = ToolManager(self.config, self.mcp_config)
|
|
135
|
+
await self.tool_manager.connect()
|
|
136
|
+
|
|
137
|
+
async def _cleanup_tools(self):
|
|
138
|
+
await self.tool_manager.cleanup()
|
|
139
|
+
|
|
140
|
+
async def _prepare_messages(
|
|
141
|
+
self, inputs: Union[List[Message], str]) -> List[Message]:
|
|
142
|
+
if isinstance(inputs, list):
|
|
143
|
+
return inputs
|
|
144
|
+
assert isinstance(
|
|
145
|
+
inputs, str
|
|
146
|
+
), f'inputs can be either a list or a string, but current is {type(inputs)}'
|
|
147
|
+
system = None
|
|
148
|
+
query = None
|
|
149
|
+
if hasattr(self.config, 'prompt'):
|
|
150
|
+
system = getattr(self.config.prompt, 'system', None)
|
|
151
|
+
query = getattr(self.config.prompt, 'query', None)
|
|
152
|
+
messages = [
|
|
153
|
+
Message(role='system', content=system or self.DEFAULT_SYSTEM),
|
|
154
|
+
Message(role='user', content=inputs or query),
|
|
155
|
+
]
|
|
156
|
+
if self.rag is not None:
|
|
157
|
+
messages = await self.rag.run(messages)
|
|
158
|
+
return messages
|
|
159
|
+
|
|
160
|
+
async def _prepare_memory(self):
|
|
161
|
+
if hasattr(self.config, 'memory'):
|
|
162
|
+
for _memory in (self.config.memory or []):
|
|
163
|
+
assert _memory.name in memory_mapping, (
|
|
164
|
+
f'{_memory.name} not in memory_mapping, '
|
|
165
|
+
f'which supports: {list(memory_mapping.keys())}')
|
|
166
|
+
self.memory_tools.append(memory_mapping[_memory.name](
|
|
167
|
+
self.config))
|
|
168
|
+
|
|
169
|
+
async def _prepare_planer(self):
|
|
170
|
+
if hasattr(self.config, 'planer'):
|
|
171
|
+
planer = self.config.planer
|
|
172
|
+
if planer is not None:
|
|
173
|
+
assert planer.name in planer_mapping, (
|
|
174
|
+
f'{planer.name} not in planer_mapping, '
|
|
175
|
+
f'which supports: {list(planer_mapping.keys())}')
|
|
176
|
+
self.planer = planer_mapping[planer.name](self.config)
|
|
177
|
+
|
|
178
|
+
async def _prepare_rag(self):
|
|
179
|
+
if hasattr(self.config, 'rag'):
|
|
180
|
+
rag = self.config.rag
|
|
181
|
+
if rag is not None:
|
|
182
|
+
assert rag.name in rag_mapping, (
|
|
183
|
+
f'{rag.name} not in rag_mapping, '
|
|
184
|
+
f'which supports: {list(rag_mapping.keys())}')
|
|
185
|
+
self.rag: Rag = rag_mapping(rag.name)(self.config)
|
|
186
|
+
|
|
187
|
+
async def _refine_memory(self, messages: List[Message]) -> List[Message]:
|
|
188
|
+
for memory_tool in self.memory_tools:
|
|
189
|
+
messages = await memory_tool.run(messages)
|
|
190
|
+
return messages
|
|
191
|
+
|
|
192
|
+
async def _update_plan(self, messages: List[Message]) -> List[Message]:
|
|
193
|
+
if self.planer is not None:
|
|
194
|
+
messages = await self.planer.update_plan(self.runtime, messages)
|
|
195
|
+
return messages
|
|
196
|
+
|
|
197
|
+
def _handle_stream_message(self, messages: List[Message],
|
|
198
|
+
tools: List[Tool]):
|
|
199
|
+
for message in self.llm.generate(messages, tools=tools):
|
|
200
|
+
yield message
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def _log_output(content: str, tag: str):
|
|
204
|
+
for line in content.split('\n'):
|
|
205
|
+
for _line in line.split('\\n'):
|
|
206
|
+
logger.info(f'[{tag}] {_line}')
|
|
207
|
+
|
|
208
|
+
@async_retry(max_attempts=2)
|
|
209
|
+
async def _step(self, messages: List[Message], tag: str) -> List[Message]:
|
|
210
|
+
messages = deepcopy(messages)
|
|
211
|
+
# Refine memory
|
|
212
|
+
messages = await self._refine_memory(messages)
|
|
213
|
+
# Do plan
|
|
214
|
+
messages = await self._update_plan(messages)
|
|
215
|
+
await self._loop_callback('on_generate_response', messages)
|
|
216
|
+
tools = await self.tool_manager.get_tools()
|
|
217
|
+
if hasattr(self.config, 'generation_config') and getattr(
|
|
218
|
+
self.config.generation_config, 'stream', False):
|
|
219
|
+
self._log_output('[assistant]:', tag=tag)
|
|
220
|
+
_content = ''
|
|
221
|
+
for _response_message in self._handle_stream_message(
|
|
222
|
+
messages, tools=tools):
|
|
223
|
+
new_content = _response_message.content[len(_content):]
|
|
224
|
+
sys.stdout.write(new_content)
|
|
225
|
+
sys.stdout.flush()
|
|
226
|
+
_content = _response_message.content
|
|
227
|
+
else:
|
|
228
|
+
_response_message = self.llm.generate(messages, tools=tools)
|
|
229
|
+
if _response_message.content:
|
|
230
|
+
self._log_output('[assistant]:', tag=tag)
|
|
231
|
+
self._log_output(_response_message.content, tag=tag)
|
|
232
|
+
if _response_message.tool_calls:
|
|
233
|
+
self._log_output('[tool_calling]:', tag=tag)
|
|
234
|
+
for tool_call in _response_message.tool_calls:
|
|
235
|
+
tool_call = deepcopy(tool_call)
|
|
236
|
+
if isinstance(tool_call['arguments'], str):
|
|
237
|
+
tool_call['arguments'] = json.loads(tool_call['arguments'])
|
|
238
|
+
self._log_output(
|
|
239
|
+
json.dumps(tool_call, ensure_ascii=False, indent=4),
|
|
240
|
+
tag=tag)
|
|
241
|
+
|
|
242
|
+
if messages[-1] is not _response_message:
|
|
243
|
+
messages.append(_response_message)
|
|
244
|
+
await self._loop_callback('after_generate_response', messages)
|
|
245
|
+
await self._loop_callback('on_tool_call', messages)
|
|
246
|
+
|
|
247
|
+
if _response_message.tool_calls:
|
|
248
|
+
messages = await self._parallel_tool_call(messages)
|
|
249
|
+
else:
|
|
250
|
+
self.runtime.should_stop = True
|
|
251
|
+
await self._loop_callback('after_tool_call', messages)
|
|
252
|
+
return messages
|
|
253
|
+
|
|
254
|
+
def _prepare_llm(self):
|
|
255
|
+
self.llm: LLM = LLM.from_config(self.config)
|
|
256
|
+
|
|
257
|
+
def _prepare_runtime(self):
|
|
258
|
+
self.runtime: Runtime = Runtime(llm=self.llm)
|
|
259
|
+
|
|
260
|
+
def _read_history(self, messages: List[Message],
|
|
261
|
+
**kwargs) -> Tuple[DictConfig, Runtime, List[Message]]:
|
|
262
|
+
if isinstance(messages, str):
|
|
263
|
+
query = messages
|
|
264
|
+
else:
|
|
265
|
+
query = messages[1].content
|
|
266
|
+
if not query or not self.load_cache or not self.task:
|
|
267
|
+
return self.config, self.runtime, messages # noqa
|
|
268
|
+
|
|
269
|
+
config, _messages = read_history(task=self.task, query=query)
|
|
270
|
+
if config is not None and _messages is not None:
|
|
271
|
+
runtime = Runtime(llm=self.llm)
|
|
272
|
+
if hasattr(config, 'runtime'):
|
|
273
|
+
runtime.from_dict(config.runtime)
|
|
274
|
+
delattr(config, 'runtime')
|
|
275
|
+
return config, runtime, _messages
|
|
276
|
+
else:
|
|
277
|
+
return self.config, self.runtime, messages # noqa
|
|
278
|
+
|
|
279
|
+
def _save_history(self, messages: List[Message], **kwargs):
|
|
280
|
+
query = messages[1].content
|
|
281
|
+
if not query or not self.task:
|
|
282
|
+
return
|
|
283
|
+
config: DictConfig = deepcopy(self.config) # noqa
|
|
284
|
+
config.runtime = self.runtime.to_dict()
|
|
285
|
+
save_history(
|
|
286
|
+
query=query, task=self.task, config=config, messages=messages)
|
|
287
|
+
|
|
288
|
+
async def run(self, messages: Union[List[Message], str],
|
|
289
|
+
**kwargs) -> List[Message]:
|
|
290
|
+
"""Run the agent, mainly contains a llm calling and tool calling loop.
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
messages(`Union[str, List[Message]]`): The inputs can be a prompt string,
|
|
294
|
+
or a list of messages from the previous agent
|
|
295
|
+
Returns:
|
|
296
|
+
The final messages
|
|
297
|
+
"""
|
|
298
|
+
try:
|
|
299
|
+
self.max_chat_round = getattr(self.config, 'max_chat_round', 20)
|
|
300
|
+
self._register_callback_from_config()
|
|
301
|
+
self._prepare_llm()
|
|
302
|
+
self._prepare_runtime()
|
|
303
|
+
await self._prepare_tools()
|
|
304
|
+
await self._prepare_memory()
|
|
305
|
+
await self._prepare_planer()
|
|
306
|
+
await self._prepare_rag()
|
|
307
|
+
self.runtime.tag = self.tag
|
|
308
|
+
|
|
309
|
+
self.config, self.runtime, messages = self._read_history(
|
|
310
|
+
messages, **kwargs)
|
|
311
|
+
|
|
312
|
+
if self.runtime.round == 0:
|
|
313
|
+
# 0 means no history
|
|
314
|
+
messages = await self._prepare_messages(messages)
|
|
315
|
+
await self._loop_callback('on_task_begin', messages)
|
|
316
|
+
if self.planer:
|
|
317
|
+
messages = await self.planer.make_plan(
|
|
318
|
+
self.runtime, messages)
|
|
319
|
+
|
|
320
|
+
for message in messages:
|
|
321
|
+
self._log_output('[' + message.role + ']:', tag=self.tag)
|
|
322
|
+
self._log_output(message.content, tag=self.tag)
|
|
323
|
+
while not self.runtime.should_stop:
|
|
324
|
+
messages = await self._step(messages, self.tag)
|
|
325
|
+
self.runtime.round += 1
|
|
326
|
+
# +1 means the next round the assistant may give a conclusion
|
|
327
|
+
if self.runtime.round >= self.max_chat_round + 1:
|
|
328
|
+
if not self.runtime.should_stop:
|
|
329
|
+
messages.append(
|
|
330
|
+
Message(
|
|
331
|
+
role='assistant',
|
|
332
|
+
content=
|
|
333
|
+
f'Task {messages[1].content} failed, max round({self.max_chat_round}) exceeded.'
|
|
334
|
+
))
|
|
335
|
+
self.runtime.should_stop = True
|
|
336
|
+
# save history
|
|
337
|
+
self._save_history(messages, **kwargs)
|
|
338
|
+
|
|
339
|
+
await self._loop_callback('on_task_end', messages)
|
|
340
|
+
await self._cleanup_tools()
|
|
341
|
+
return messages
|
|
342
|
+
except Exception as e:
|
|
343
|
+
if hasattr(self.config, 'help'):
|
|
344
|
+
logger.error(
|
|
345
|
+
f'[{self.tag}] Runtime error, please follow the instructions:\n\n {self.config.help}'
|
|
346
|
+
)
|
|
347
|
+
raise e
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
|
2
|
+
from abc import abstractmethod
|
|
3
|
+
from typing import List
|
|
4
|
+
|
|
5
|
+
from ms_agent.llm.utils import Message
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Memory:
|
|
9
|
+
"""The memory refine tool"""
|
|
10
|
+
|
|
11
|
+
@abstractmethod
|
|
12
|
+
async def run(self, messages: List[Message]) -> List[Message]:
|
|
13
|
+
"""Refine the messages
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
messages(`List[Message]`): The input messages
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
The output messages
|
|
20
|
+
"""
|
|
21
|
+
pass
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
|
2
|
+
from abc import abstractmethod
|
|
3
|
+
from typing import List
|
|
4
|
+
|
|
5
|
+
from ms_agent.agent.runtime import Runtime
|
|
6
|
+
from ms_agent.llm.utils import Message
|
|
7
|
+
from pydantic import ConfigDict
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Planer:
|
|
11
|
+
"""A planer to guide the agent"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, config: ConfigDict):
|
|
14
|
+
self.config = config
|
|
15
|
+
|
|
16
|
+
@abstractmethod
|
|
17
|
+
async def make_plan(self, runtime: Runtime,
|
|
18
|
+
messages: List[Message]) -> List[Message]:
|
|
19
|
+
"""Make an initial plan
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
runtime (`Runtime`): The runtime
|
|
23
|
+
messages (`List[Message]`): The input messages
|
|
24
|
+
"""
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
@abstractmethod
|
|
28
|
+
async def update_plan(self, runtime: Runtime,
|
|
29
|
+
messages: List[Message]) -> List[Message]:
|
|
30
|
+
"""Update the plan
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
runtime (`Runtime`): The runtime
|
|
34
|
+
messages (`List[Message]`): The input messages
|
|
35
|
+
"""
|
|
36
|
+
pass
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from ms_agent.llm import LLM
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class Runtime:
|
|
10
|
+
|
|
11
|
+
should_stop: bool = False
|
|
12
|
+
|
|
13
|
+
llm: LLM = None
|
|
14
|
+
|
|
15
|
+
tag: Optional[str] = None
|
|
16
|
+
|
|
17
|
+
round: int = 0
|
|
18
|
+
|
|
19
|
+
def to_dict(self):
|
|
20
|
+
return {
|
|
21
|
+
'should_stop': self.should_stop,
|
|
22
|
+
'tag': self.tag,
|
|
23
|
+
'round': self.round,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
def from_dict(self, data: dict):
|
|
27
|
+
self.should_stop = data['should_stop']
|
|
28
|
+
self.tag = data['tag']
|
|
29
|
+
self.round = data['round']
|