ai-agent-book 精选快照(<2MB 代码与文档,来自 github.com/bojieli/ai-agent-book)
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
import atexit
|
||||
import os
|
||||
|
||||
try:
|
||||
from aworld.utils.import_package import import_package
|
||||
|
||||
import_package("dotenv", install_name="python-dotenv")
|
||||
from dotenv import load_dotenv
|
||||
|
||||
sucess = load_dotenv()
|
||||
if not sucess:
|
||||
load_dotenv(os.path.join(os.getcwd(), ".env"))
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
|
||||
def cleanup():
|
||||
import re
|
||||
|
||||
try:
|
||||
value = os.environ.get("LOCAL_TOOLS_ENV_VAR", '')
|
||||
if value:
|
||||
for action_file in value.split(";"):
|
||||
v = re.split(r"\w{6}__tmp", action_file)[0]
|
||||
if v == action_file:
|
||||
continue
|
||||
tool_file = action_file.replace("_action.py", ".py")
|
||||
try:
|
||||
os.remove(action_file)
|
||||
os.remove(tool_file)
|
||||
except:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
os.environ["LOCAL_TOOLS_ENV_VAR"] = ''
|
||||
|
||||
|
||||
atexit.register(cleanup, )
|
||||
@@ -0,0 +1,7 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
|
||||
from aworld.cmd.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,276 @@
|
||||
# Multi-agent
|
||||
|
||||
```python
|
||||
from aworld.agents.llm_agent import Agent
|
||||
from aworld.config.conf import AgentConfig
|
||||
from aworld.core.agent.swarm import Swarm, GraphBuildType
|
||||
|
||||
agent_conf = AgentConfig(...)
|
||||
```
|
||||
|
||||
## Builder
|
||||
Builder represents the way topology is constructed, which is related to runtime execution.
|
||||
Topology is the definition of structure. For the same topology structure, different builders
|
||||
will produce execution processes and different results.
|
||||
|
||||
```python
|
||||
"""
|
||||
Topology:
|
||||
┌─────A─────┐
|
||||
B | C
|
||||
D
|
||||
"""
|
||||
A = Agent(name="A", conf=agent_conf)
|
||||
B = Agent(name="B", conf=agent_conf)
|
||||
C = Agent(name="C", conf=agent_conf)
|
||||
D = Agent(name="D", conf=agent_conf)
|
||||
```
|
||||
|
||||
### Workflow
|
||||
Workflow is a special topological structure that can be executed deterministically, all nodes in the swarm
|
||||
will be executed. And the starting and ending nodes are **unique** and **indispensable**.
|
||||
|
||||
Define:
|
||||
```python
|
||||
# default is workflow
|
||||
Swarm((A, B), (A, C), (A, D))
|
||||
or
|
||||
Swarm(A, [B, C, D])
|
||||
```
|
||||
The example means A is the start node, and the merge of B, C, and D is the end node.
|
||||
|
||||
### Handoff
|
||||
Handoff using pure AI to drive the flow of the entire topology diagram, one agent's decision hands off
|
||||
control to another. Agents as tools, depending on the defined pairs of agents.
|
||||
|
||||
Define:
|
||||
```python
|
||||
Swarm((A, B), (A, C), (A, D), build_type=GraphBuildType.HANDOFF)
|
||||
or
|
||||
HandoffSwarm((A, B), (A, C), (A, D))
|
||||
```
|
||||
**NOTE**: Handoff supported tuple of paired agents forms only.
|
||||
|
||||
### Team
|
||||
Team requires a leadership agent, and other agents follow its command.
|
||||
Team is a special case of handoff, which is the leader-follower mode.
|
||||
|
||||
Define:
|
||||
```python
|
||||
Swarm((A, B), (A, C), (A, D), build_type=GraphBuildType.TEAM)
|
||||
or
|
||||
TeamSwarm(A, B, C, D)
|
||||
or
|
||||
Swarm(B, C, D, root_agent=A, build_type=GraphBuildType.TEAM)
|
||||
```
|
||||
The root_agent or first agent A is the leader; other agents interact with the leader A.
|
||||
|
||||
### Debate
|
||||
TODO
|
||||
|
||||
### Hybrid
|
||||
Hybrid is not a new type of builder of topology. Due to the use of different builders for the same topology,
|
||||
the execution process varies, so hybrid builder is the fusion of **nested** topologies from different builders.
|
||||
That is, interaction between multi-agents with multi-agents in different build modes.
|
||||
For example, in a `WorkflowSwarm`, one node can be a `TeamSwarm`, `HandoffSwarm` or other. Or a node in a
|
||||
`HandoffSwarm` can also be a `WorkflowSwarm` or other.
|
||||
|
||||
Example:
|
||||
```python
|
||||
A1 = Agent(name="A1", conf=agent_conf)
|
||||
B1 = Agent(name="B1", conf=agent_conf)
|
||||
C1 = Agent(name="C1", conf=agent_conf)
|
||||
swarm1 = TeamSwarm(A1, B1, C1, build_type=GraphBuildType.TEAM)
|
||||
|
||||
Swarm(A, [B, C, swarm1], D)
|
||||
```
|
||||
The example shows that workflow swarm. After A completes execution, B, C, and swarm1(TeamSwarm) execute in parallel,
|
||||
swarm1 will run in plan-execute mode until the end of the swarm1, and finally D is executed.
|
||||
|
||||
## Topology
|
||||
The topology structure of multi-agent is represented by Swarm, Swarm's topology is built based on
|
||||
various single agents,can use the topology type and build type Swarm to represent different structural types.
|
||||
|
||||
### Star
|
||||
Each agent communicates with a single supervisor agent, also known as star topology,
|
||||
a special structure of tree topology, also referred to as a team topology in **Aworld**.
|
||||
|
||||
A plan agent with other executing agents is a typical example.
|
||||
```python
|
||||
"""
|
||||
Star topology:
|
||||
┌───── plan ───┐
|
||||
exec1 exec2
|
||||
"""
|
||||
plan = Agent(name="plan", conf=agent_conf)
|
||||
exec1 = Agent(name="exec1", conf=agent_conf)
|
||||
exec2 = Agent(name="exec2", conf=agent_conf)
|
||||
```
|
||||
|
||||
We have two ways to construct this topology structure.
|
||||
```python
|
||||
swarm = Swarm((plan, exec1), (plan, exec2))
|
||||
```
|
||||
or use handoffs mechanism:
|
||||
```python
|
||||
plan = Agent(name="plan", conf=agent_conf, agent_names=['exec1', 'exec2'])
|
||||
swarm = Swarm(plan, register_agents=[exec1, exec2])
|
||||
```
|
||||
or use team mechanism:
|
||||
```python
|
||||
# The order of the plan agent is the first.
|
||||
swarm = TeamSwarm(plan, exec1, exec2,
|
||||
build_type=GraphBuildType.TEAM)
|
||||
```
|
||||
|
||||
Note:
|
||||
- Whether to execute exec1 or exec2 is decided by LLM.
|
||||
- If you want to execute all defined nodes with certainty, you need to use the `workflow` pattern.
|
||||
Like this will execute all the defined nodes:
|
||||
```python
|
||||
swarm = Swarm(plan, [exec1, exec2])
|
||||
```
|
||||
- If it is necessary to execute exec1, whether to execute exec2 depends on LLM, you can define it as:
|
||||
```python
|
||||
plan = Agent(name="plan", conf=agent_conf, agent_names=['exec1', 'exec2'])
|
||||
swarm = Swarm((plan, exec1), register_agents=[exec2])
|
||||
```
|
||||
That means that **GraphBuildType.WORKFLOW** is set, all nodes within the swarm will be executed.
|
||||
|
||||
### Tree
|
||||
This is a generalization of the star topology and allows for more complex control flows.
|
||||
|
||||
#### Hierarchical
|
||||
```python
|
||||
"""
|
||||
Hierarchical topology:
|
||||
┌─────────── root ───────────┐
|
||||
┌───── parent1 ───┐ ┌─────── parent2 ───────┐
|
||||
leaf1_1 leaf1_2 leaf1_1 leaf2_2
|
||||
"""
|
||||
|
||||
root = Agent(name="root", conf=agent_conf)
|
||||
parent1 = Agent(name="parent1", conf=agent_conf)
|
||||
parent2 = Agent(name="parent2", conf=agent_conf)
|
||||
leaf1_1 = Agent(name="leaf1_1", conf=agent_conf)
|
||||
leaf1_2 = Agent(name="leaf1_2", conf=agent_conf)
|
||||
leaf2_1 = Agent(name="leaf2_1", conf=agent_conf)
|
||||
leaf2_2 = Agent(name="leaf2_2", conf=agent_conf)
|
||||
```
|
||||
|
||||
```python
|
||||
swarm = Swarm((root, parent1), (root, parent2),
|
||||
(parent1, leaf1_1), (parent1, leaf1_2),
|
||||
(parent2, leaf2_1), (parent2, leaf2_2),
|
||||
build_type=GraphBuildType.HANDOFF)
|
||||
```
|
||||
or use agent handoff:
|
||||
```python
|
||||
root = Agent(name="root", conf=agent_conf, agent_names=['parent1', 'parent2'])
|
||||
parent1 = Agent(name="parent1", conf=agent_conf, agent_names=['leaf1_1', 'leaf1_2'])
|
||||
parent2 = Agent(name="parent2", conf=agent_conf, agent_names=['leaf2_1', 'leaf2_2'])
|
||||
|
||||
swarm = HandoffSwarm((root, parent1), (root, parent2),
|
||||
register_agents=[leaf1_1, leaf1_2, leaf2_1, leaf2_2])
|
||||
```
|
||||
|
||||
#### Map-reduce
|
||||
If the topology structure becomes further complex:
|
||||
```
|
||||
┌─────────── root ───────────┐
|
||||
┌───── parent1 ───┐ ┌────── parent2 ──────┐
|
||||
leaf1_1 leaf1_2 leaf1_1 leaf2_2
|
||||
└─────result1─────┘ └───────result2───────┘
|
||||
└───────────final───────────┘
|
||||
```
|
||||
We define it as **Map-reduce** topology, equivalent to workflow in terms of execution mode.
|
||||
|
||||
Build in this way:
|
||||
|
||||
```python
|
||||
result1 = Agent(name="result1", conf=agent_conf)
|
||||
result2 = Agent(name="result2", conf=agent_conf)
|
||||
final = Agent(name="final", conf=agent_conf)
|
||||
|
||||
swarm = Swarm(
|
||||
(root, [parent1, parent2]),
|
||||
(parent1, [leaf1_1, leaf1_2]),
|
||||
(parent2, [leaf2_1, leaf2_2]),
|
||||
([leaf1_1, leaf1_2], result1),
|
||||
([leaf2_1, leaf2_2], result2),
|
||||
([result1, result2], final)
|
||||
)
|
||||
```
|
||||
Assuming there is a cycle final -> root in the topology, define it as:
|
||||
```python
|
||||
final = LoopableAgent(name="final",
|
||||
conf=agent_conf,
|
||||
max_run_times=5,
|
||||
loop_point=root.name(),
|
||||
stop_func=...)
|
||||
```
|
||||
`stop_func` is a function that determines whether to terminate prematurely.
|
||||
|
||||
|
||||
### Mesh
|
||||
Divided into a fully meshed topology and a partially meshed topology.
|
||||
Fully meshed topology means that each agent can communicate with every other agent,
|
||||
any agent can decide which other agent to call next.
|
||||
|
||||
```python
|
||||
"""
|
||||
Fully Meshed topology:
|
||||
┌─────────── A ──────────┐
|
||||
B ───────────|────────── C
|
||||
└─────────── D ─────────┘
|
||||
"""
|
||||
A = Agent(name="A", conf=agent_conf)
|
||||
B = Agent(name="B", conf=agent_conf)
|
||||
C = Agent(name="C", conf=agent_conf)
|
||||
D = Agent(name="D", conf=agent_conf)
|
||||
```
|
||||
|
||||
Network topology need to use the `handoffs` mechanism:
|
||||
```python
|
||||
swarm = HandoffsSwarm((A, B), (B, A),
|
||||
(A, C), (C, A),
|
||||
(A, D), (D, A),
|
||||
(B, C), (C, B),
|
||||
(B, D), (D, B),
|
||||
(C, D), (D, C))
|
||||
```
|
||||
If a few pairs are removed, it becomes a partially meshed topology.
|
||||
|
||||
### Ring
|
||||
A ring topology structure is a closed loop formed by nodes.
|
||||
|
||||
```python
|
||||
"""
|
||||
Ring topology:
|
||||
┌───────────> A >──────────┐
|
||||
B C
|
||||
└───────────< D <─────────┘
|
||||
"""
|
||||
A = Agent(name="A", conf=agent_conf)
|
||||
B = Agent(name="B", conf=agent_conf)
|
||||
C = Agent(name="C", conf=agent_conf)
|
||||
D = Agent(name="D", conf=agent_conf)
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
swarm = Swarm((A, C), (C, D), (D, B), (B, A))
|
||||
```
|
||||
**Note:**
|
||||
- This defined loop can only be executed once.
|
||||
- If you want to execute multiple times, need to define it as:
|
||||
|
||||
```python
|
||||
B = LoopableAgent(name="B", max_run_times=5, stop_func=...)
|
||||
swarm = Swarm((A, C), (C, D), (D, B))
|
||||
```
|
||||
### hybrid
|
||||
A generalization of topology, supporting an arbitrary combination of topologies, internally capable of
|
||||
loops, parallel, serial dependencies, and groups.
|
||||
|
||||
## Execution
|
||||
@@ -0,0 +1,107 @@
|
||||
# AI Agents
|
||||
|
||||
Intelligent agents that control devices or tools in env using AI models or policy.
|
||||
|
||||

|
||||
|
||||
Most of the time, we directly use existing tools to build different types of agents that use LLM,
|
||||
using frameworks makes it easy to write various agents.
|
||||
|
||||
Detailed steps for building an agent:
|
||||
1. Define your `Agent`
|
||||
2. Write prompt used to the agent, also choose not to set it.
|
||||
3. Run it.
|
||||
|
||||
We provide a complete and simple example for writing an agent and multi-agent:
|
||||
|
||||
```python
|
||||
from aworld.config.conf import AgentConfig
|
||||
from aworld.agents.llm_agent import Agent
|
||||
|
||||
prompt = """
|
||||
Please act as a search agent, constructing appropriate keywords and searach terms, using search toolkit to collect relevant information, including urls, webpage snapshots, etc.
|
||||
Here are some tips that help you perform web search:
|
||||
- Never add too many keywords in your search query! Some detailed results need to perform browser interaction to get, not using search toolkit.
|
||||
- If the question is complex, search results typically do not provide precise answers. It is not likely to find the answer directly using search toolkit only, the search query should be concise and focuses on finding official sources rather than direct answers.
|
||||
For example, as for the question "What is the maximum length in meters of #9 in the first National Geographic short on YouTube that was ever released according to the Monterey Bay Aquarium website?", your first search term must be coarse-grained like "National Geographic YouTube" to find the youtube website first, and then try other fine-grained search terms step-by-step to find more urls.
|
||||
- The results you return do not have to directly answer the original question, you only need to collect relevant information.
|
||||
|
||||
Here are the question: {task}
|
||||
|
||||
Please perform web search and return the listed search result, including urls and necessary webpage snapshots, introductions, etc.
|
||||
Your output should be like the followings (at most 3 relevant pages from coa):
|
||||
[
|
||||
{{
|
||||
"url": [URL],
|
||||
"information": [INFORMATION OR CONTENT]
|
||||
}},
|
||||
...
|
||||
]
|
||||
"""
|
||||
|
||||
# Step1
|
||||
agent_config = AgentConfig(
|
||||
llm_provider="openai",
|
||||
llm_model_name="gpt-4o",
|
||||
llm_temperature=1,
|
||||
# need to set llm_api_key for use LLM
|
||||
llm_api_key=""
|
||||
)
|
||||
|
||||
search = Agent(
|
||||
conf=agent_config,
|
||||
name="search_agent",
|
||||
system_prompt="You are a helpful search agent.",
|
||||
# used to opt the result, also choose not to set it
|
||||
agent_prompt=prompt,
|
||||
tool_names=["search_api"]
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
It can also quickly develop multi-agent based on the framework.
|
||||
|
||||
On the basis of the above agent(SearchAgent), we provide a multi-agent example:
|
||||
|
||||
```python
|
||||
from aworld.agents.llm_agent import Agent
|
||||
|
||||
summary_prompt = """
|
||||
Summarize the following text in one clear and concise paragraph, capturing the key ideas without missing critical points.
|
||||
Ensure the summary is easy to understand and avoids excessive detail.
|
||||
|
||||
Here are the content:
|
||||
{task}
|
||||
"""
|
||||
|
||||
summary = Agent(
|
||||
conf=agent_config,
|
||||
name="summary_agent",
|
||||
system_prompt="You are a helpful general summary agent.",
|
||||
# used to opt the result, also choose not to set it
|
||||
agent_prompt=summary_prompt
|
||||
)
|
||||
```
|
||||
|
||||
You can run single-agent or multi-agent through Swarm.
|
||||
NOTE: Need to set some environment variables first! Effective GOOGLE_API_KEY, GOOGLE_ENGINE_ID, OPENAI_API_KEY and OPENAI_ENDPOINT.
|
||||
|
||||
```python
|
||||
|
||||
from aworld.core.agent.swarm import Swarm
|
||||
from aworld.runner import Runners
|
||||
|
||||
if __name__ == '__main__':
|
||||
task = "search 1+1=?"
|
||||
# build topology graph, the correct order is necessary
|
||||
swarm = Swarm(search, summary, max_steps=1)
|
||||
|
||||
prefix = ""
|
||||
# can special search google, wiki, duck go, or baidu. such as:
|
||||
# prefix = "search wiki: "
|
||||
res = Runners.sync_run(
|
||||
input=prefix + """What is an agent.""",
|
||||
swarm=swarm
|
||||
)
|
||||
```
|
||||
You can view search example [code](../../examples/multi_agents/workflow/search).
|
||||
@@ -0,0 +1,2 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
@@ -0,0 +1,935 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
import copy
|
||||
import json
|
||||
import time
|
||||
import traceback
|
||||
import uuid
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, List, Callable, Optional
|
||||
|
||||
import aworld.trace as trace
|
||||
from aworld.core.agent.agent_desc import get_agent_desc
|
||||
from aworld.core.agent.base import BaseAgent, AgentResult, is_agent_by_name, is_agent
|
||||
from aworld.core.common import ActionResult, Observation, ActionModel, Config, TaskItem
|
||||
from aworld.core.context.base import Context
|
||||
from aworld.core.context.processor.prompt_processor import PromptProcessor
|
||||
from aworld.core.context.prompts import BasePromptTemplate
|
||||
from aworld.core.context.prompts.string_prompt_template import StringPromptTemplate
|
||||
from aworld.core.event import eventbus
|
||||
from aworld.core.event.base import Message, ToolMessage, Constants, AgentMessage, GroupMessage, TopicType
|
||||
from aworld.core.model_output_parser import ModelOutputParser
|
||||
from aworld.core.tool.tool_desc import get_tool_desc
|
||||
from aworld.events.util import send_message
|
||||
from aworld.logs.util import logger, color_log, Color
|
||||
from aworld.mcp_client.utils import mcp_tool_desc_transform
|
||||
from aworld.memory.main import MemoryFactory
|
||||
from aworld.memory.models import MessageMetadata, MemoryAIMessage, MemoryToolMessage, MemoryHumanMessage, \
|
||||
MemorySystemMessage, MemoryMessage
|
||||
from aworld.models.llm import get_llm_model, acall_llm_model, acall_llm_model_stream
|
||||
from aworld.models.model_response import ModelResponse, ToolCall, LLMResponseError
|
||||
from aworld.models.utils import tool_desc_transform, agent_desc_transform
|
||||
from aworld.output import Outputs
|
||||
from aworld.output.base import MessageOutput, Output
|
||||
from aworld.runners.hook.hooks import HookPoint
|
||||
from aworld.sandbox.base import Sandbox
|
||||
from aworld.trace.constants import SPAN_NAME_PREFIX_AGENT
|
||||
from aworld.trace.instrumentation import semconv
|
||||
from aworld.utils.common import sync_exec, nest_dict_counter
|
||||
from aworld.utils.serialized_util import to_serializable
|
||||
|
||||
|
||||
class LlmOutputParser(ModelOutputParser[ModelResponse, AgentResult]):
|
||||
async def parse(self, resp: ModelResponse, **kwargs) -> AgentResult:
|
||||
"""Standard parse based Openai API."""
|
||||
|
||||
if not resp:
|
||||
logger.warning("no valid content to parse!")
|
||||
return AgentResult(actions=[], current_state=None)
|
||||
|
||||
agent_id = kwargs.get("agent_id")
|
||||
if not agent_id:
|
||||
logger.warning("need agent_id param.")
|
||||
raise RuntimeError("no `agent_id` param.")
|
||||
|
||||
results = []
|
||||
is_call_tool = False
|
||||
content = '' if resp.content is None else resp.content
|
||||
if kwargs.get("use_tools_in_prompt"):
|
||||
tool_calls = []
|
||||
for tool in self.use_tool_list(content):
|
||||
tool_calls.append(ToolCall.from_dict({
|
||||
"id": tool.get("id"),
|
||||
"function": {
|
||||
"name": tool.get("tool"),
|
||||
"arguments": tool.get("arguments")
|
||||
}
|
||||
}))
|
||||
if tool_calls:
|
||||
resp.tool_calls = tool_calls
|
||||
|
||||
if resp.tool_calls:
|
||||
is_call_tool = True
|
||||
for tool_call in resp.tool_calls:
|
||||
full_name: str = tool_call.function.name
|
||||
if not full_name:
|
||||
logger.warning("tool call response no tool name.")
|
||||
continue
|
||||
try:
|
||||
params = json.loads(tool_call.function.arguments)
|
||||
except:
|
||||
logger.warning(f"{tool_call.function.arguments} parse to json fail.")
|
||||
params = {}
|
||||
# format in framework
|
||||
names = full_name.split("__")
|
||||
tool_name = names[0]
|
||||
if is_agent_by_name(full_name):
|
||||
param_info = params.get('content', "") + ' ' + params.get('info', '')
|
||||
results.append(ActionModel(tool_name=full_name,
|
||||
tool_call_id=tool_call.id,
|
||||
agent_name=agent_id,
|
||||
params=params,
|
||||
policy_info=content + param_info))
|
||||
else:
|
||||
action_name = '__'.join(names[1:]) if len(names) > 1 else ''
|
||||
results.append(ActionModel(tool_name=tool_name,
|
||||
tool_call_id=tool_call.id,
|
||||
action_name=action_name,
|
||||
agent_name=agent_id,
|
||||
params=params,
|
||||
policy_info=content))
|
||||
else:
|
||||
content = content.replace("```json", "").replace("```", "")
|
||||
results.append(ActionModel(agent_name=agent_id, policy_info=content))
|
||||
|
||||
return AgentResult(actions=results, current_state=None, is_call_tool=is_call_tool)
|
||||
|
||||
def use_tool_list(self, content: str) -> List[Dict[str, Any]]:
|
||||
tool_list = []
|
||||
try:
|
||||
content = content.replace('\n', '').replace('\r', '')
|
||||
response_json = json.loads(content)
|
||||
use_tool_list = response_json.get("use_tool_list", [])
|
||||
for use_tool in use_tool_list:
|
||||
tool_name = use_tool.get("tool", None)
|
||||
if tool_name:
|
||||
tool_list.append(use_tool)
|
||||
except Exception:
|
||||
logger.debug(f"tool_parse error, content: {content}, \n{traceback.format_exc()}")
|
||||
return tool_list
|
||||
|
||||
|
||||
class Agent(BaseAgent[Observation, List[ActionModel]]):
|
||||
"""Basic agent for unified protocol within the framework."""
|
||||
|
||||
def __init__(self,
|
||||
name: str,
|
||||
conf: Config | None = None,
|
||||
desc: str = None,
|
||||
agent_id: str = None,
|
||||
*,
|
||||
task: Any = None,
|
||||
tool_names: List[str] = None,
|
||||
agent_names: List[str] = None,
|
||||
mcp_servers: List[str] = None,
|
||||
mcp_config: Dict[str, Any] = None,
|
||||
feedback_tool_result: bool = True,
|
||||
wait_tool_result: bool = False,
|
||||
sandbox: Sandbox = None,
|
||||
system_prompt: str = None,
|
||||
system_prompt_template: BasePromptTemplate = None,
|
||||
agent_prompt: str = None,
|
||||
need_reset: bool = True,
|
||||
step_reset: bool = True,
|
||||
use_tools_in_prompt: bool = False,
|
||||
black_tool_actions: Dict[str, List[str]] = None,
|
||||
model_output_parser: ModelOutputParser[..., AgentResult] = LlmOutputParser(),
|
||||
tool_aggregate_func: Callable[..., Any] = None,
|
||||
event_handler_name: str = None,
|
||||
event_driven: bool = True,
|
||||
**kwargs):
|
||||
"""A api class implementation of agent, using the `Observation` and `List[ActionModel]` protocols.
|
||||
|
||||
Args:
|
||||
system_prompt: Instruction of the agent.
|
||||
agent_prompt: Optimized prompt of the agent.
|
||||
need_reset: Whether need to reset the status in start.
|
||||
step_reset: Reset the status at each step
|
||||
use_tools_in_prompt: Whether the tool description in prompt.
|
||||
black_tool_actions: Black list of actions of the tool.
|
||||
model_output_parser: Llm response parse function for the agent standard output, transform llm response.
|
||||
tool_aggregate_func: Aggregation strategy for multiple tool results.
|
||||
event_handler_name: Custom handlers for certain types of events.
|
||||
"""
|
||||
super(Agent, self).__init__(name, conf, desc, agent_id,
|
||||
task=task,
|
||||
tool_names=tool_names,
|
||||
agent_names=agent_names,
|
||||
mcp_servers=mcp_servers,
|
||||
mcp_config=mcp_config,
|
||||
black_tool_actions=black_tool_actions,
|
||||
feedback_tool_result=feedback_tool_result,
|
||||
wait_tool_result=wait_tool_result,
|
||||
sandbox=sandbox,
|
||||
**kwargs)
|
||||
conf = self.conf
|
||||
self.model_name = conf.llm_config.llm_model_name
|
||||
self._llm = None
|
||||
self.memory = MemoryFactory.instance()
|
||||
self.memory_config = conf.memory_config
|
||||
self.system_prompt: str = system_prompt if system_prompt else conf.system_prompt
|
||||
self.system_prompt_template: str = system_prompt_template if (
|
||||
system_prompt_template) else conf.system_prompt_template
|
||||
|
||||
# for backward compatibility
|
||||
if not self.system_prompt_template:
|
||||
self.system_prompt_template = StringPromptTemplate.from_template(self.system_prompt)
|
||||
if isinstance(self.system_prompt_template, str):
|
||||
self.system_prompt_template = StringPromptTemplate.from_template(self.system_prompt_template)
|
||||
if not self.system_prompt:
|
||||
self.system_prompt = self.system_prompt_template.template
|
||||
self.agent_prompt: str = agent_prompt if agent_prompt else conf.agent_prompt
|
||||
self.event_driven = event_driven
|
||||
|
||||
self.need_reset = need_reset if need_reset else conf.need_reset
|
||||
# whether to keep contextual information, False means keep, True means reset in every step by the agent call
|
||||
self.step_reset = step_reset
|
||||
# tool_name: [tool_action1, tool_action2, ...]
|
||||
# self.black_tool_actions: Dict[str, List[str]] = black_tool_actions if black_tool_actions \
|
||||
# else conf.get('black_tool_actions', {})
|
||||
self.model_output_parser = model_output_parser
|
||||
self.use_tools_in_prompt = use_tools_in_prompt if use_tools_in_prompt else conf.use_tools_in_prompt
|
||||
self.tools_aggregate_func = tool_aggregate_func if tool_aggregate_func else self._tools_aggregate_func
|
||||
self.event_handler_name = event_handler_name
|
||||
|
||||
@property
|
||||
def llm(self):
|
||||
# lazy
|
||||
if self._llm is None:
|
||||
llm_config = self.conf.llm_config or None
|
||||
conf = llm_config if llm_config and (
|
||||
llm_config.llm_provider or llm_config.llm_base_url or llm_config.llm_api_key or llm_config.llm_model_name) else self.conf
|
||||
self._llm = get_llm_model(conf)
|
||||
return self._llm
|
||||
|
||||
def desc_transform(self, context: Context) -> None:
|
||||
"""Transform of descriptions of supported tools, agents, and MCP servers in the framework to support function calls of LLM."""
|
||||
sync_exec(self.async_desc_transform, context)
|
||||
|
||||
async def async_desc_transform(self, context: Context) -> None:
|
||||
"""Transform of descriptions of supported tools, agents, and MCP servers in the framework to support function calls of LLM."""
|
||||
|
||||
# Stateless tool
|
||||
self.tools = tool_desc_transform(get_tool_desc(),
|
||||
tools=self.tool_names if self.tool_names else [],
|
||||
black_tool_actions=self.black_tool_actions)
|
||||
# Agents as tool
|
||||
self.tools.extend(agent_desc_transform(get_agent_desc(),
|
||||
agents=self.handoffs if self.handoffs else []))
|
||||
# MCP servers are tools
|
||||
if self.sandbox:
|
||||
mcp_tools = await self.sandbox.mcpservers.list_tools(context)
|
||||
self.tools.extend(mcp_tools)
|
||||
else:
|
||||
self.tools.extend(await mcp_tool_desc_transform(self.mcp_servers, self.mcp_config))
|
||||
|
||||
def messages_transform(self,
|
||||
content: str,
|
||||
image_urls: List[str] = None,
|
||||
observation: Observation = None,
|
||||
message: Message = None,
|
||||
**kwargs) -> List[Dict[str, Any]]:
|
||||
return sync_exec(self.async_messages_transform, image_urls=image_urls, observation=observation,
|
||||
message=message, **kwargs)
|
||||
|
||||
async def async_messages_transform(self,
|
||||
image_urls: List[str] = None,
|
||||
observation: Observation = None,
|
||||
message: Message = None,
|
||||
**kwargs) -> List[Dict[str, Any]]:
|
||||
"""Transform the original content to LLM messages of native format.
|
||||
|
||||
Args:
|
||||
observation: Observation by env.
|
||||
image_urls: List of images encoded using base64.
|
||||
message: Event received by the Agent.
|
||||
Returns:
|
||||
Message list for LLM.
|
||||
"""
|
||||
agent_prompt = self.agent_prompt
|
||||
messages = []
|
||||
# append sys_prompt to memory
|
||||
await self._add_system_message_to_memory(context=message.context, content=observation.content)
|
||||
|
||||
session_id = message.context.get_task().session_id
|
||||
task_id = message.context.get_task().id
|
||||
histories = self.memory.get_all(filters={
|
||||
"agent_id": self.id(),
|
||||
"session_id": session_id,
|
||||
"task_id": task_id,
|
||||
"memory_type": "message"
|
||||
})
|
||||
last_history = histories[-1] if histories and len(histories) > 0 else None
|
||||
|
||||
# append observation to memory
|
||||
if observation.is_tool_result:
|
||||
for action_item in observation.action_result:
|
||||
tool_call_id = action_item.tool_call_id
|
||||
await self._add_tool_result_to_memory(tool_call_id, tool_result=action_item, context=message.context)
|
||||
elif last_history and last_history.metadata and "tool_calls" in last_history.metadata and \
|
||||
last_history.metadata[
|
||||
'tool_calls']:
|
||||
for tool_call in last_history.metadata['tool_calls']:
|
||||
tool_call_id = tool_call['id']
|
||||
tool_name = tool_call['function']['name']
|
||||
if tool_name and tool_name == message.sender:
|
||||
await self._add_tool_result_to_memory(tool_call_id, tool_result=observation.content,
|
||||
context=message.context)
|
||||
break
|
||||
else:
|
||||
content = observation.content
|
||||
logger.debug(f"agent_prompt: {agent_prompt}")
|
||||
if agent_prompt:
|
||||
content = agent_prompt.format(task=content, current_date=datetime.now().strftime("%Y-%m-%d"))
|
||||
if image_urls:
|
||||
urls = [{'type': 'text', 'text': content}]
|
||||
for image_url in image_urls:
|
||||
urls.append(
|
||||
{'type': 'image_url', 'image_url': {"url": image_url}})
|
||||
content = urls
|
||||
await self._add_human_input_to_memory(content, message.context, memory_type="message")
|
||||
|
||||
# from memory get last n messages
|
||||
histories = self.memory.get_last_n(self.memory_config.history_rounds, filters={
|
||||
"agent_id": self.id(),
|
||||
"session_id": session_id,
|
||||
"task_id": task_id
|
||||
}, agent_memory_config=self.memory_config)
|
||||
if histories:
|
||||
# default use the first tool call
|
||||
for history in histories:
|
||||
if isinstance(history, MemoryMessage):
|
||||
messages.append(history.to_openai_message())
|
||||
else:
|
||||
if not self.use_tools_in_prompt and "tool_calls" in history.metadata and history.metadata[
|
||||
'tool_calls']:
|
||||
messages.append({'role': history.metadata['role'], 'content': history.content,
|
||||
'tool_calls': [history.metadata["tool_calls"][0]]})
|
||||
else:
|
||||
messages.append({'role': history.metadata['role'], 'content': history.content,
|
||||
"tool_call_id": history.metadata.get("tool_call_id")})
|
||||
return messages
|
||||
|
||||
async def init_observation(self, observation: Observation) -> Observation:
|
||||
# supported string only
|
||||
# if self.task and isinstance(self.task, str) and self.task != observation.content:
|
||||
# observation.content = f"base task is: {self.task}\n{observation.content}"
|
||||
# # `task` only needs to be processed once and reflected in the context
|
||||
# self.task = None
|
||||
|
||||
# default use origin observation
|
||||
return observation
|
||||
|
||||
def _log_messages(self, messages: List[Dict[str, Any]], **kwargs) -> None:
|
||||
"""Log the sequence of messages for debugging purposes"""
|
||||
logger.info(f"[agent] Invoking LLM with {len(messages)} messages:")
|
||||
logger.debug(f"[agent] use tools: {self.tools}")
|
||||
for i, msg in enumerate(messages):
|
||||
prefix = msg.get('role')
|
||||
logger.info(
|
||||
f"[agent] Message {i + 1}: {prefix} ===================================")
|
||||
if isinstance(msg['content'], list):
|
||||
try:
|
||||
for item in msg['content']:
|
||||
if item.get('type') == 'text':
|
||||
logger.info(
|
||||
f"[agent] Text content: {item.get('text')}")
|
||||
elif item.get('type') == 'image_url':
|
||||
image_url = item.get('image_url', {}).get('url', '')
|
||||
if image_url.startswith('data:image'):
|
||||
logger.info(f"[agent] Image: [Base64 image data]")
|
||||
else:
|
||||
logger.info(
|
||||
f"[agent] Image URL: {image_url[:30]}...")
|
||||
except Exception as e:
|
||||
logger.error(f"[agent] Error parsing msg['content']: {msg}. Error: {e}")
|
||||
content = str(msg['content'])
|
||||
chunk_size = 500
|
||||
for j in range(0, len(content), chunk_size):
|
||||
chunk = content[j:j + chunk_size]
|
||||
if j == 0:
|
||||
logger.info(f"[agent] Content: {chunk}")
|
||||
else:
|
||||
logger.info(f"[agent] Content (continued): {chunk}")
|
||||
else:
|
||||
content = str(msg['content'])
|
||||
chunk_size = 500
|
||||
for j in range(0, len(content), chunk_size):
|
||||
chunk = content[j:j + chunk_size]
|
||||
if j == 0:
|
||||
logger.info(f"[agent] Content: {chunk}")
|
||||
else:
|
||||
logger.info(f"[agent] Content (continued): {chunk}")
|
||||
|
||||
if 'tool_calls' in msg and msg['tool_calls']:
|
||||
for tool_call in msg.get('tool_calls'):
|
||||
if isinstance(tool_call, dict):
|
||||
logger.info(
|
||||
f"[agent] Tool call: {tool_call.get('function', {}).get('name', {})} - ID: {tool_call.get('id')}")
|
||||
args = str(tool_call.get('function', {}).get(
|
||||
'arguments', {}))[:1000]
|
||||
logger.info(f"[agent] Tool args: {args}...")
|
||||
elif isinstance(tool_call, ToolCall):
|
||||
logger.info(
|
||||
f"[agent] Tool call: {tool_call.function.name} - ID: {tool_call.id}")
|
||||
args = str(tool_call.function.arguments)[:1000]
|
||||
logger.info(f"[agent] Tool args: {args}...")
|
||||
|
||||
def _agent_result(self, actions: List[ActionModel], caller: str, input_message: Message):
|
||||
if not actions:
|
||||
raise Exception(f'{self.id()} no action decision has been made.')
|
||||
if self.event_handler_name:
|
||||
return Message(payload=actions,
|
||||
caller=caller,
|
||||
sender=self.id(),
|
||||
receiver=actions[0].tool_name,
|
||||
category=self.event_handler_name,
|
||||
session_id=input_message.context.session_id if input_message.context else "",
|
||||
headers=self._update_headers(input_message))
|
||||
|
||||
tools = OrderedDict()
|
||||
agents = []
|
||||
for action in actions:
|
||||
if is_agent(action):
|
||||
agents.append(action)
|
||||
else:
|
||||
if action.tool_name not in tools:
|
||||
tools[action.tool_name] = []
|
||||
tools[action.tool_name].append(action)
|
||||
|
||||
_group_name = None
|
||||
# agents and tools exist simultaneously, more than one agent/tool name
|
||||
if (agents and tools) or len(agents) > 1 or len(tools) > 1:
|
||||
_group_name = f"{self.id()}_{uuid.uuid1().hex}"
|
||||
|
||||
# complex processing
|
||||
if _group_name:
|
||||
return GroupMessage(payload=actions,
|
||||
caller=caller,
|
||||
sender=self.id(),
|
||||
receiver=actions[0].tool_name,
|
||||
session_id=input_message.context.session_id if input_message.context else "",
|
||||
group_id=_group_name,
|
||||
topic=TopicType.GROUP_ACTIONS,
|
||||
headers=self._update_headers(input_message))
|
||||
elif agents:
|
||||
return AgentMessage(payload=actions,
|
||||
caller=caller,
|
||||
sender=self.id(),
|
||||
receiver=actions[0].tool_name,
|
||||
session_id=input_message.context.session_id if input_message.context else "",
|
||||
headers=self._update_headers(input_message))
|
||||
|
||||
else:
|
||||
return ToolMessage(payload=actions,
|
||||
caller=caller,
|
||||
sender=self.id(),
|
||||
receiver=actions[0].tool_name,
|
||||
session_id=input_message.context.session_id if input_message.context else "",
|
||||
headers=self._update_headers(input_message))
|
||||
|
||||
def post_run(self, policy_result: List[ActionModel], policy_input: Observation, message: Message = None) -> Message:
|
||||
return self._agent_result(
|
||||
policy_result,
|
||||
policy_input.from_agent_name if policy_input.from_agent_name else policy_input.observer,
|
||||
message
|
||||
)
|
||||
|
||||
async def async_post_run(self, policy_result: List[ActionModel], policy_input: Observation,
|
||||
message: Message = None) -> Message:
|
||||
return self._agent_result(
|
||||
policy_result,
|
||||
policy_input.from_agent_name if policy_input.from_agent_name else policy_input.observer,
|
||||
message
|
||||
)
|
||||
|
||||
def policy(self, observation: Observation, info: Dict[str, Any] = {}, message: Message = None, **kwargs) -> List[
|
||||
ActionModel]:
|
||||
"""The strategy of an agent can be to decide which tools to use in the environment, or to delegate tasks to other agents.
|
||||
|
||||
Args:
|
||||
observation: The state observed from tools in the environment.
|
||||
info: Extended information is used to assist the agent to decide a policy.
|
||||
|
||||
Returns:
|
||||
ActionModel sequence from agent policy
|
||||
"""
|
||||
return sync_exec(self.async_policy, observation, info, message, **kwargs)
|
||||
|
||||
async def async_policy(self, observation: Observation, info: Dict[str, Any] = {}, message: Message = None,
|
||||
**kwargs) -> List[ActionModel]:
|
||||
"""The strategy of an agent can be to decide which tools to use in the environment, or to delegate tasks to other agents.
|
||||
|
||||
Args:
|
||||
observation: The state observed from tools in the environment.
|
||||
info: Extended information is used to assist the agent to decide a policy.
|
||||
|
||||
Returns:
|
||||
ActionModel sequence from agent policy
|
||||
"""
|
||||
logger.info(f"Agent{type(self)}#{self.id()}: async_policy start")
|
||||
|
||||
# Get current step information for trace recording
|
||||
source_span = trace.get_current_span()
|
||||
self._finished = False
|
||||
if hasattr(observation, 'context') and observation.context:
|
||||
self.task_histories = observation.context
|
||||
|
||||
try:
|
||||
events = []
|
||||
async for event in self.run_hooks(message.context, HookPoint.PRE_LLM_CALL):
|
||||
events.append(event)
|
||||
except Exception:
|
||||
logger.debug(traceback.format_exc())
|
||||
|
||||
messages = await self.build_llm_input(observation, info, message=message, **kwargs)
|
||||
|
||||
serializable_messages = to_serializable(messages)
|
||||
llm_response = None
|
||||
if source_span:
|
||||
source_span.set_attribute("messages", json.dumps(serializable_messages, ensure_ascii=False))
|
||||
try:
|
||||
llm_response = await self.invoke_model(messages, message=message, **kwargs)
|
||||
except Exception as e:
|
||||
logger.warn(traceback.format_exc())
|
||||
raise e
|
||||
finally:
|
||||
if llm_response:
|
||||
if llm_response.error:
|
||||
logger.info(f"llm result error: {llm_response.error}")
|
||||
if eventbus is not None:
|
||||
output_message = Message(
|
||||
category=Constants.OUTPUT,
|
||||
payload=Output(
|
||||
data=f"llm result error: {llm_response.error}"
|
||||
),
|
||||
sender=self.id(),
|
||||
session_id=message.context.session_id if message.context else "",
|
||||
headers={"context": message.context}
|
||||
)
|
||||
await send_message(output_message)
|
||||
else:
|
||||
await self._add_llm_response_to_memory(llm_response, message.context, history_messages=messages)
|
||||
else:
|
||||
logger.error(f"{self.id()} failed to get LLM response")
|
||||
raise RuntimeError(f"{self.id()} failed to get LLM response")
|
||||
|
||||
try:
|
||||
events = []
|
||||
async for event in self.run_hooks(message.context, HookPoint.POST_LLM_CALL):
|
||||
events.append(event)
|
||||
except Exception as e:
|
||||
logger.debug(traceback.format_exc())
|
||||
|
||||
agent_result = await self.model_output_parser.parse(llm_response,
|
||||
agent_id=self.id(),
|
||||
use_tools_in_prompt=self.use_tools_in_prompt)
|
||||
logger.info(f"agent_result: {agent_result}")
|
||||
policy_result: Optional[List[ActionModel]] = None
|
||||
if self.is_agent_finished(llm_response, agent_result):
|
||||
policy_result = agent_result.actions
|
||||
else:
|
||||
if not self.wait_tool_result:
|
||||
policy_result = agent_result.actions
|
||||
else:
|
||||
policy_result = await self.execution_tools(agent_result.actions, message)
|
||||
await self.send_llm_response_output(llm_response, agent_result, message.context, kwargs.get("outputs"))
|
||||
return policy_result
|
||||
|
||||
async def execution_tools(self, actions: List[ActionModel], message: Message = None, **kwargs) -> List[ActionModel]:
|
||||
"""Tool execution operations.
|
||||
|
||||
Returns:
|
||||
ActionModel sequence. Tool execution result.
|
||||
"""
|
||||
from aworld.utils.run_util import exec_tool
|
||||
|
||||
tool_results = []
|
||||
for act in actions:
|
||||
if is_agent(act):
|
||||
continue
|
||||
act_result = await exec_tool(tool_name=act.tool_name,
|
||||
action_name=act.action_name,
|
||||
params=act.params,
|
||||
agent_name=self.id(),
|
||||
context=message.context.deep_copy(),
|
||||
sub_task=True,
|
||||
outputs=message.context.outputs,
|
||||
task_group_id=message.context.get_task().group_id or uuid.uuid4().hex)
|
||||
if not act_result.success:
|
||||
color_log(f"Agent {self.id()} _execute_tool failed with exception: {act_result.msg}",
|
||||
color=Color.red)
|
||||
continue
|
||||
tool_results.append(
|
||||
ActionResult(tool_call_id=act.tool_call_id, tool_name=act.tool_name, content=act_result.answer))
|
||||
await self._add_tool_result_to_memory(act.tool_call_id, act_result.answer,
|
||||
context=message.context)
|
||||
result = sync_exec(self.tools_aggregate_func, tool_results)
|
||||
return result
|
||||
|
||||
async def _tools_aggregate_func(self, tool_results: List[ActionResult]) -> List[ActionModel]:
|
||||
"""Aggregate tool results
|
||||
Args:
|
||||
tool_results: Tool results
|
||||
Returns:
|
||||
ActionModel sequence
|
||||
"""
|
||||
content = ""
|
||||
for res in tool_results:
|
||||
content += f"{res.content}\n"
|
||||
return [ActionModel(agent_name=self.id(), policy_info=content)]
|
||||
|
||||
async def build_llm_input(self,
|
||||
observation: Observation,
|
||||
info: Dict[str, Any] = {},
|
||||
message: Message = None,
|
||||
**kwargs):
|
||||
"""Build LLM input.
|
||||
|
||||
Args:
|
||||
observation: The state observed from the environment
|
||||
info: Extended information to assist the agent in decision-making
|
||||
"""
|
||||
await self.async_desc_transform(message.context)
|
||||
# observation secondary processing
|
||||
observation = await self.init_observation(observation)
|
||||
images = observation.images if self.conf.use_vision else None
|
||||
if self.conf.use_vision and not images and observation.image:
|
||||
images = [observation.image]
|
||||
messages = await self.async_messages_transform(image_urls=images, observation=observation, message=message)
|
||||
# truncate and other process
|
||||
try:
|
||||
messages = self._process_messages(messages=messages, context=message.context)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to process messages in messages_transform: {e}")
|
||||
logger.debug(f"Process messages error details: {traceback.format_exc()}")
|
||||
|
||||
self._log_messages(messages, context=message.context)
|
||||
|
||||
return messages
|
||||
|
||||
def _process_messages(self, messages: List[Dict[str, Any]],
|
||||
context: Context = None) -> Optional[List[Dict[str, Any]]]:
|
||||
origin_messages = messages
|
||||
st = time.time()
|
||||
with trace.span(f"{SPAN_NAME_PREFIX_AGENT}llm_context_process", attributes={
|
||||
"start_time": st,
|
||||
semconv.AGENT_ID: self.id()
|
||||
}) as compress_span:
|
||||
if self.conf.context_rule is None:
|
||||
logger.debug('debug|skip process_messages context_rule is None')
|
||||
return messages
|
||||
origin_len = compressed_len = len(str(messages))
|
||||
origin_messages_count = truncated_messages_count = len(messages)
|
||||
try:
|
||||
prompt_processor = PromptProcessor(self.conf.context_rule, self.conf.llm_config)
|
||||
result = prompt_processor.process_messages(messages, context)
|
||||
messages = result.processed_messages
|
||||
|
||||
compressed_len = len(str(messages))
|
||||
truncated_messages_count = len(messages)
|
||||
logger.debug(
|
||||
f'debug|llm_context_process|{origin_len}|{compressed_len}|{origin_messages_count}|{truncated_messages_count}|\n|{origin_messages}\n|{messages}')
|
||||
return messages
|
||||
finally:
|
||||
compress_span.set_attributes({
|
||||
"end_time": time.time(),
|
||||
"duration": time.time() - st,
|
||||
# messages length
|
||||
"origin_messages_count": origin_messages_count,
|
||||
"truncated_messages_count": truncated_messages_count,
|
||||
"truncated_ratio": round(truncated_messages_count / origin_messages_count,
|
||||
2) if origin_messages_count > 0 else 0,
|
||||
# token length
|
||||
"origin_len": origin_len,
|
||||
"compressed_len": compressed_len,
|
||||
"compress_ratio": round(compressed_len / origin_len, 2)
|
||||
})
|
||||
|
||||
async def invoke_model(self,
|
||||
messages: List[Dict[str, str]] = [],
|
||||
message: Message = None,
|
||||
**kwargs) -> ModelResponse:
|
||||
"""Perform LLM call.
|
||||
|
||||
Args:
|
||||
messages: LLM model input messages.
|
||||
message: Event message.
|
||||
**kwargs: Other parameters
|
||||
|
||||
Returns:
|
||||
LLM response
|
||||
"""
|
||||
llm_response = None
|
||||
source_span = trace.get_current_span()
|
||||
serializable_messages = to_serializable(messages)
|
||||
message.context.context_info["llm_input"] = serializable_messages
|
||||
|
||||
if source_span:
|
||||
source_span.set_attribute("messages", json.dumps(
|
||||
serializable_messages, ensure_ascii=False))
|
||||
|
||||
try:
|
||||
stream_mode = kwargs.get("stream", False)
|
||||
float_temperature = float(self.conf.llm_config.llm_temperature)
|
||||
if stream_mode:
|
||||
llm_response = ModelResponse(
|
||||
id="", model="", content="", tool_calls=[])
|
||||
resp_stream = acall_llm_model_stream(
|
||||
self.llm,
|
||||
messages=messages,
|
||||
model=self.model_name,
|
||||
temperature=float_temperature,
|
||||
tools=self.tools if not self.use_tools_in_prompt and self.tools else None,
|
||||
stream=True
|
||||
)
|
||||
|
||||
async def async_call_llm(resp_stream, json_parse=False):
|
||||
llm_resp = ModelResponse(
|
||||
id="", model="", content="", tool_calls=[])
|
||||
|
||||
# Async streaming with acall_llm_model
|
||||
async def async_generator():
|
||||
async for chunk in resp_stream:
|
||||
if chunk.content:
|
||||
llm_resp.content += chunk.content
|
||||
yield chunk.content
|
||||
if chunk.tool_calls:
|
||||
llm_resp.tool_calls.extend(chunk.tool_calls)
|
||||
if chunk.error:
|
||||
llm_resp.error = chunk.error
|
||||
llm_resp.id = chunk.id
|
||||
llm_resp.model = chunk.model
|
||||
llm_resp.usage = nest_dict_counter(
|
||||
llm_resp.usage, chunk.usage)
|
||||
|
||||
return MessageOutput(source=async_generator(), json_parse=json_parse), llm_resp
|
||||
|
||||
output, response = await async_call_llm(resp_stream)
|
||||
llm_response = response
|
||||
|
||||
else:
|
||||
llm_response = await acall_llm_model(
|
||||
self.llm,
|
||||
messages=messages,
|
||||
model=self.model_name,
|
||||
temperature=float_temperature,
|
||||
tools=self.tools if not self.use_tools_in_prompt and self.tools else None,
|
||||
stream=kwargs.get("stream", False)
|
||||
)
|
||||
|
||||
logger.info(f"Execute response: {json.dumps(llm_response.to_dict(), ensure_ascii=False)}")
|
||||
except Exception as e:
|
||||
logger.warn(traceback.format_exc())
|
||||
await send_message(Message(
|
||||
category=Constants.OUTPUT,
|
||||
payload=Output(
|
||||
data=f"Failed to call llm model: {e}"
|
||||
),
|
||||
sender=self.id(),
|
||||
session_id=message.context.session_id if message.context else "",
|
||||
headers={"context": message.context}
|
||||
))
|
||||
|
||||
if "Please reduce the length of the messages" in str(e):
|
||||
# Meaning context too long, will return directly. You can develop a Processor to truncate or compress it.
|
||||
await send_message(Message(
|
||||
category=Constants.TASK,
|
||||
topic=TopicType.CANCEL,
|
||||
payload=TaskItem(data=messages, msg=str(e)),
|
||||
sender=self.id(),
|
||||
priority=-1,
|
||||
session_id=message.context.session_id if message.context else "",
|
||||
headers={"context": message.context}
|
||||
))
|
||||
return ModelResponse(id=uuid.uuid4().hex, model=self.model_name, content=to_serializable(messages))
|
||||
raise e
|
||||
finally:
|
||||
message.context.context_info["llm_output"] = llm_response
|
||||
return llm_response
|
||||
|
||||
def _init_context(self, context: Context):
|
||||
super()._init_context(context)
|
||||
logger.debug(f'init_context llm_agent {self.name()} {self.conf} {self.conf.context_rule}')
|
||||
|
||||
async def run_hooks(self, context: Context, hook_point: str):
|
||||
"""Execute hooks asynchronously"""
|
||||
from aworld.runners.hook.hook_factory import HookFactory
|
||||
from aworld.core.event.base import Message
|
||||
|
||||
# Get all hooks for the specified hook point
|
||||
all_hooks = HookFactory.hooks(hook_point)
|
||||
hooks = all_hooks.get(hook_point, [])
|
||||
|
||||
for hook in hooks:
|
||||
try:
|
||||
# Create a temporary Message object to pass to the hook
|
||||
message = Message(
|
||||
category="agent_hook",
|
||||
payload=None,
|
||||
sender=self.id(),
|
||||
session_id=context.session_id if hasattr(
|
||||
context, 'session_id') else None,
|
||||
headers={"context": message.context}
|
||||
)
|
||||
|
||||
# Execute hook
|
||||
msg = await hook.exec(message, context)
|
||||
if msg:
|
||||
logger.debug(f"Hook {hook.point()} executed successfully")
|
||||
yield msg
|
||||
except Exception as e:
|
||||
logger.warning(f"Hook {hook.point()} execution failed: {traceback.format_exc()}")
|
||||
|
||||
async def _add_system_message_to_memory(self, context: Context, content: str):
|
||||
if not self.system_prompt:
|
||||
return
|
||||
session_id = context.get_task().session_id
|
||||
task_id = context.get_task().id
|
||||
user_id = context.get_task().user_id
|
||||
|
||||
histories = self.memory.get_last_n(0, filters={
|
||||
"agent_id": self.id(),
|
||||
"session_id": session_id,
|
||||
"task_id": task_id
|
||||
}, agent_memory_config=self.memory_config)
|
||||
if histories:
|
||||
logger.debug(f"🧠 [MEMORY:short-term] histories is not empty, do not need add system input to agent memory")
|
||||
return
|
||||
|
||||
content = await self.custom_system_prompt(context=context, content=content, tool_list=self.tools)
|
||||
await self.memory.add(MemorySystemMessage(
|
||||
content=content,
|
||||
metadata=MessageMetadata(
|
||||
session_id=session_id,
|
||||
user_id=user_id,
|
||||
task_id=task_id,
|
||||
agent_id=self.id(),
|
||||
agent_name=self.name(),
|
||||
)
|
||||
), agent_memory_config=self.memory_config)
|
||||
|
||||
async def custom_system_prompt(self, context: Context, content: str, tool_list: List[str] = None):
|
||||
logger.info(f"llm_agent custom_system_prompt .. agent#{type(self)}#{self.id()}")
|
||||
return self.system_prompt_template.format(context=context, task=content, tool_list=tool_list)
|
||||
|
||||
async def _add_human_input_to_memory(self, content: Any, context: Context, memory_type="init"):
|
||||
"""Add user input to memory"""
|
||||
session_id = context.get_task().session_id
|
||||
user_id = context.get_task().user_id
|
||||
task_id = context.get_task().id
|
||||
|
||||
await self.memory.add(MemoryHumanMessage(
|
||||
content=content,
|
||||
metadata=MessageMetadata(
|
||||
session_id=session_id,
|
||||
user_id=user_id,
|
||||
task_id=task_id,
|
||||
agent_id=self.id(),
|
||||
agent_name=self.name(),
|
||||
),
|
||||
memory_type=memory_type
|
||||
), agent_memory_config=self.memory_config)
|
||||
|
||||
async def _add_llm_response_to_memory(self, llm_response, context: Context, history_messages: list, **kwargs):
|
||||
"""Add LLM response to memory"""
|
||||
ai_message = MemoryAIMessage(
|
||||
content=llm_response.content,
|
||||
tool_calls=llm_response.tool_calls,
|
||||
metadata=MessageMetadata(
|
||||
session_id=context.get_task().session_id,
|
||||
user_id=context.get_task().user_id,
|
||||
task_id=context.get_task().id,
|
||||
agent_id=self.id(),
|
||||
agent_name=self.name()
|
||||
)
|
||||
)
|
||||
await self.memory.add(ai_message, agent_memory_config=self.memory_config)
|
||||
|
||||
async def _add_tool_result_to_memory(self, tool_call_id: str, tool_result: ActionResult, context: Context):
|
||||
"""Add tool result to memory"""
|
||||
if hasattr(tool_result, 'content') and isinstance(tool_result.content, str) and tool_result.content.startswith(
|
||||
"data:image"):
|
||||
image_content = tool_result.content
|
||||
tool_result.content = "this picture is below "
|
||||
await self._do_add_tool_result_to_memory(tool_call_id, tool_result, context)
|
||||
image_content = [
|
||||
{
|
||||
"type": "text",
|
||||
"text": f"this is file of tool_call_id:{tool_result.tool_call_id}"
|
||||
},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": image_content
|
||||
}
|
||||
}
|
||||
]
|
||||
await self._add_human_input_to_memory(image_content, context, "message")
|
||||
else:
|
||||
await self._do_add_tool_result_to_memory(tool_call_id, tool_result, context)
|
||||
|
||||
async def _do_add_tool_result_to_memory(self, tool_call_id: str, tool_result: ActionResult, context: Context):
|
||||
"""Add tool result to memory"""
|
||||
tool_use_summary = None
|
||||
if isinstance(tool_result, ActionResult):
|
||||
tool_use_summary = tool_result.metadata.get("tool_use_summary")
|
||||
await self.memory.add(MemoryToolMessage(
|
||||
content=tool_result.content if hasattr(tool_result, 'content') else tool_result,
|
||||
tool_call_id=tool_call_id,
|
||||
status="success",
|
||||
metadata=MessageMetadata(
|
||||
session_id=context.get_task().session_id,
|
||||
user_id=context.get_task().user_id,
|
||||
task_id=context.get_task().id,
|
||||
agent_id=self.id(),
|
||||
agent_name=self.name(),
|
||||
summary_content=tool_use_summary
|
||||
)
|
||||
), agent_memory_config=self.memory_config)
|
||||
|
||||
async def send_llm_response_output(self, llm_response: ModelResponse, agent_result: AgentResult, context: Context,
|
||||
outputs: Outputs = None):
|
||||
"""Send LLM response to output"""
|
||||
if not llm_response or llm_response.error:
|
||||
return
|
||||
if eventbus is None:
|
||||
logger.warn("=============== eventbus is none ============")
|
||||
llm_resp_output = MessageOutput(
|
||||
source=llm_response,
|
||||
metadata={"agent_id": self.id(), "agent_name": self.name(), "is_finished": self.finished}
|
||||
)
|
||||
if eventbus is not None and llm_response:
|
||||
await send_message(Message(
|
||||
category=Constants.OUTPUT,
|
||||
payload=llm_resp_output,
|
||||
sender=self.id(),
|
||||
session_id=context.session_id if context else "",
|
||||
headers={"context": context}
|
||||
))
|
||||
elif not self.event_driven and outputs:
|
||||
await outputs.add_output(llm_resp_output)
|
||||
|
||||
def is_agent_finished(self, llm_response: ModelResponse, agent_result: AgentResult) -> bool:
|
||||
if not agent_result.is_call_tool:
|
||||
self._finished = True
|
||||
return self.finished
|
||||
|
||||
def _update_headers(self, input_message: Message) -> Dict[str, Any]:
|
||||
headers = input_message.headers.copy()
|
||||
headers['context'] = input_message.context
|
||||
headers['level'] = headers.get('level', 0) + 1
|
||||
if input_message.group_id:
|
||||
headers['parent_group_id'] = input_message.group_id
|
||||
return headers
|
||||
@@ -0,0 +1,46 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
from typing import Any, Callable
|
||||
|
||||
from aworld.agents.llm_agent import Agent
|
||||
|
||||
|
||||
class LoopableAgent(Agent):
|
||||
"""Support for loop agents in the swarm.
|
||||
|
||||
The parameters of the extension function are the agent itself, which can obtain internal information of the agent.
|
||||
`stop_func` function example:
|
||||
>>> def stop(agent: LoopableAgent):
|
||||
>>> ...
|
||||
|
||||
`loop_point_finder` function example:
|
||||
>>> def find(agent: LoopableAgent):
|
||||
>>> ...
|
||||
"""
|
||||
max_run_times: int = 1
|
||||
cur_run_times: int = 0
|
||||
# The loop agent special the loop point (agent name)
|
||||
loop_point: str = None
|
||||
# Used to determine the loop point for multiple loops
|
||||
loop_point_finder: Callable[..., Any] = None
|
||||
# def stop(agent: LoopableAgent): ...
|
||||
stop_func: Callable[..., Any] = None
|
||||
|
||||
@property
|
||||
def goto(self):
|
||||
"""The next loop point is what the loop agent wants to reach."""
|
||||
if self.loop_point_finder:
|
||||
return self.loop_point_finder(self)
|
||||
if self.loop_point:
|
||||
return self.loop_point
|
||||
return self.id()
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
"""Loop agent termination state detection, achieved loop count or termination condition."""
|
||||
if self.cur_run_times >= self.max_run_times or (self.stop_func and self.stop_func(self)):
|
||||
self._finished = True
|
||||
return True
|
||||
|
||||
self._finished = False
|
||||
return False
|
||||
@@ -0,0 +1,67 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
import asyncio
|
||||
from typing import List, Dict, Any, Callable
|
||||
|
||||
from aworld.agents.llm_agent import Agent
|
||||
from aworld.core.common import Observation, ActionModel
|
||||
from aworld.core.event.base import Message
|
||||
from aworld.utils.run_util import exec_agent
|
||||
|
||||
|
||||
class ParallelizableAgent(Agent):
|
||||
"""Support for parallel agents in the swarm.
|
||||
|
||||
The parameters of the extension function are the agent itself, which can obtain internal information of the agent.
|
||||
`aggregate_func` function example:
|
||||
>>> def agg(agent: ParallelizableAgent, res: Dict[str, Any]) -> ActionModel:
|
||||
>>> ...
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
agents: List[Agent] = None,
|
||||
aggregate_func: Callable[['ParallelizableAgent', Dict[str, Any]], ActionModel] = None,
|
||||
**kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.agents = agents if agents else []
|
||||
# The function of aggregating the results of the parallel execution of agents.
|
||||
self.aggregate_func = aggregate_func
|
||||
|
||||
async def async_policy(self, observation: Observation, info: Dict[str, Any] = {}, **kwargs) -> List[ActionModel]:
|
||||
tasks = []
|
||||
if self.agents:
|
||||
for agent in self.agents:
|
||||
tasks.append(asyncio.create_task(exec_agent(observation.content, agent, self.context, sub_task=True)))
|
||||
|
||||
results = await asyncio.gather(*tasks)
|
||||
res = []
|
||||
for idx, result in enumerate(results):
|
||||
if result.success:
|
||||
con = result.answer
|
||||
else:
|
||||
con = result.msg
|
||||
res.append(ActionModel(agent_name=self.agents[idx].id(), policy_info=con))
|
||||
|
||||
if self.aggregate_func:
|
||||
res = [self.aggregate_func(self, {action.agent_name: action.policy_info for action in res})]
|
||||
return res
|
||||
|
||||
async def _agent_result(self, actions: List[ActionModel], caller: str, input_message: Message):
|
||||
if self.aggregate_func:
|
||||
return super()._agent_result(actions, caller, input_message)
|
||||
|
||||
if not actions:
|
||||
raise Exception(f'{self.id()} no action decision has been made.')
|
||||
|
||||
action = ActionModel(agent_name=self.id(),
|
||||
policy_info={action.agent_name: action.policy_info for action in actions})
|
||||
return Message(payload=[action],
|
||||
caller=caller,
|
||||
sender=self.id(),
|
||||
receiver=actions[0].tool_name,
|
||||
category=self.event_handler_name,
|
||||
session_id=input_message.context.session_id if input_message.context else "",
|
||||
headers=self._update_headers(input_message))
|
||||
|
||||
def finished(self) -> bool:
|
||||
return all([agent.finished for agent in self.agents])
|
||||
@@ -0,0 +1,64 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
from typing import List, Dict, Any, Callable
|
||||
|
||||
from aworld.core.event.base import Message
|
||||
|
||||
from aworld.utils.run_util import exec_agent
|
||||
|
||||
from aworld.agents.llm_agent import Agent
|
||||
from aworld.core.common import Observation, ActionModel, Config
|
||||
from aworld.logs.util import logger
|
||||
|
||||
|
||||
class SerialableAgent(Agent):
|
||||
"""Support for serial execution of agents based on dependency relationships in the swarm.
|
||||
|
||||
The parameters of the extension function are the agent itself, which can obtain internal information of the agent.
|
||||
`aggregate_func` function example:
|
||||
>>> def agg(agent: SerialableAgent, res: Dict[str, Any]) -> ActionModel:
|
||||
>>> ...
|
||||
>>> return ActionModel(agent_name=agent.id(), policy_info='...')
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
agents: List[Agent] = None,
|
||||
aggregate_func: Callable[['SerialableAgent', Dict[str, Any]], ActionModel] = None,
|
||||
**kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.agents = agents if agents else []
|
||||
self.aggregate_func = aggregate_func
|
||||
|
||||
async def async_policy(self, observation: Observation, info: Dict[str, Any] = {}, **kwargs) -> List[ActionModel]:
|
||||
self.results = None
|
||||
results = {}
|
||||
action = ActionModel(agent_name=self.id(), policy_info=observation.content)
|
||||
if self.agents:
|
||||
for agent in self.agents:
|
||||
result = await exec_agent(observation.content, agent, self.context, sub_task=True)
|
||||
if result:
|
||||
if result.success:
|
||||
con = result.answer
|
||||
else:
|
||||
con = result.msg
|
||||
action = ActionModel(agent_name=agent.id(), policy_info=con)
|
||||
observation = self._action_to_observation(action, agent.id())
|
||||
results[agent.id()] = con
|
||||
else:
|
||||
raise Exception(f"{agent.id()} execute fail.")
|
||||
|
||||
if self.aggregate_func:
|
||||
return [self.aggregate_func(self, results)]
|
||||
|
||||
return [action]
|
||||
|
||||
def _action_to_observation(self, policy: ActionModel, agent_name: str):
|
||||
if not policy:
|
||||
logger.warning("no agent policy, will use default error info.")
|
||||
return Observation(content=f"{agent_name} no policy")
|
||||
|
||||
logger.debug(f"{policy.policy_info}")
|
||||
return Observation(content=policy.policy_info, observer=agent_name)
|
||||
|
||||
def finished(self) -> bool:
|
||||
return all([agent.finished for agent in self.agents])
|
||||
@@ -0,0 +1,47 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from aworld.core.exceptions import AWorldRuntimeException
|
||||
|
||||
from aworld.core.agent.swarm import Swarm
|
||||
from aworld.core.task import Task, TaskResponse
|
||||
from aworld.utils.run_util import exec_tasks
|
||||
|
||||
from aworld.agents.llm_agent import Agent
|
||||
from aworld.core.common import Observation, ActionModel
|
||||
|
||||
|
||||
class TaskAgent(Agent):
|
||||
"""Support for swarm execution of in the hybrid nested swarm."""
|
||||
|
||||
def __init__(self,
|
||||
swarm: Swarm,
|
||||
**kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.swarm = swarm
|
||||
if not self.swarm:
|
||||
raise AWorldRuntimeException("no swarm in task agent.")
|
||||
|
||||
def reset(self, options: Dict[str, Any] = None):
|
||||
super().reset(options)
|
||||
if not options:
|
||||
self.swarm.reset()
|
||||
else:
|
||||
self.swarm.reset(options.get("task"), options.get("context"), options.get("tools"))
|
||||
|
||||
async def async_policy(self, observation: Observation, info: Dict[str, Any] = {}, **kwargs) -> List[ActionModel]:
|
||||
self._finished = False
|
||||
task = Task(input=observation.content, swarm=self.swarm)
|
||||
results = await exec_tasks([task])
|
||||
res = []
|
||||
for key, result in results.items():
|
||||
# result is TaskResponse
|
||||
if result.success:
|
||||
info = result.answer
|
||||
else:
|
||||
info = result.msg
|
||||
res.append(ActionModel(agent_name=self.id(), policy_info=info))
|
||||
|
||||
self._finished = True
|
||||
return res
|
||||
@@ -0,0 +1,98 @@
|
||||
# Checkpoint Module
|
||||
|
||||
## Overview
|
||||
The Checkpoint module provides a robust and extensible framework for managing state snapshots (checkpoints) in Python applications. It is designed for scenarios where you need to persist, restore, and version the state of a process, session, or task.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Application
|
||||
participant CheckpointRepository
|
||||
participant BackendStorage
|
||||
|
||||
Note over Application,BackendStorage: Create and store a checkpoint
|
||||
%% Create and store a checkpoint
|
||||
Application->>CheckpointRepository: create checkpoint
|
||||
CheckpointRepository->>BackendStorage: put(checkpoint)
|
||||
BackendStorage-->>CheckpointRepository: success
|
||||
CheckpointRepository-->>Application: ack
|
||||
|
||||
Note over Application,BackendStorage: Retrieve the latest checkpoint by session
|
||||
|
||||
%% Retrieve the latest checkpoint by session
|
||||
Application->>CheckpointRepository: get checkpoint by session_id
|
||||
CheckpointRepository->>BackendStorage: get_by_session(session_id)
|
||||
BackendStorage-->>CheckpointRepository: Checkpoint
|
||||
CheckpointRepository-->>Application: Checkpoint
|
||||
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Structured Data Model**: Uses Pydantic's `BaseModel` for strong typing and validation of checkpoint data and metadata.
|
||||
- **Versioning Support**: Built-in version management utilities for checkpoint evolution and comparison.
|
||||
- **Extensible Repository Pattern**: Abstract base class (`BaseCheckpointRepository`) defines a standard interface for checkpoint storage, supporting both synchronous and asynchronous operations.
|
||||
- **In-Memory Implementation**: Includes a simple, ready-to-use in-memory repository for development and testing.
|
||||
- **Utility Functions**: Helper methods for creating, copying, and managing checkpoints.
|
||||
|
||||
## Data Structures
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class Application {
|
||||
+CheckpointRepository repo
|
||||
+create_checkpoint()
|
||||
+get_checkpoint_by_session()
|
||||
}
|
||||
class CheckpointRepository {
|
||||
+put(checkpoint)
|
||||
+get_by_session(session_id)
|
||||
+delete_by_session(session_id)
|
||||
-BackendStorage backend
|
||||
}
|
||||
class BackendStorage {
|
||||
+put(checkpoint)
|
||||
+get_by_session(session_id)
|
||||
+delete_by_session(session_id)
|
||||
}
|
||||
Application --> CheckpointRepository : uses
|
||||
CheckpointRepository --> BackendStorage : delegates
|
||||
class Checkpoint {
|
||||
+id: str
|
||||
+ts: str
|
||||
+metadata: CheckpointMetadata
|
||||
+values: dict
|
||||
+version: int
|
||||
+parent_id: str
|
||||
+namespace: str
|
||||
}
|
||||
class CheckpointMetadata {
|
||||
+session_id: str
|
||||
+task_id: str
|
||||
}
|
||||
Checkpoint o-- CheckpointMetadata
|
||||
CheckpointRepository o-- Checkpoint
|
||||
BackendStorage o-- Checkpoint
|
||||
```
|
||||
|
||||
|
||||
## Usage Example
|
||||
|
||||
```python
|
||||
from aworld.checkpoint import (
|
||||
Checkpoint, CheckpointMetadata, empty_checkpoint, create_checkpoint, InMemoryCheckpointRepository
|
||||
)
|
||||
|
||||
# Create a new checkpoint
|
||||
metadata = CheckpointMetadata(session_id="session-123", task_id="task-456")
|
||||
values = {"step": 1, "score": 100}
|
||||
checkpoint = create_checkpoint(values=values, metadata=metadata)
|
||||
|
||||
# Store and retrieve using the in-memory repository
|
||||
repo = InMemoryCheckpointRepository()
|
||||
repo.put(checkpoint)
|
||||
restored = repo.get(checkpoint.id)
|
||||
```
|
||||
|
||||
## Extensibility
|
||||
- Implement custom repositories by inheriting from `BaseCheckpointRepository` (e.g., for database, file, or cloud storage).
|
||||
- Extend versioning logic via the `VersionUtils` class.
|
||||
@@ -0,0 +1,245 @@
|
||||
from typing import Any, Dict, Optional, List
|
||||
import copy
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from abc import ABC, abstractmethod
|
||||
import asyncio
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
|
||||
|
||||
class CheckpointMetadata(BaseModel):
|
||||
"""
|
||||
Metadata for a checkpoint, including session and task identifiers.
|
||||
|
||||
Attributes:
|
||||
session_id (str): The session identifier (required).
|
||||
task_id (Optional[str]): The task identifier (optional).
|
||||
artifact_id (Optional[str]): The artifact identifier (optional).
|
||||
"""
|
||||
session_id: str = Field(..., description="The session identifier.")
|
||||
task_id: Optional[str] = Field(None, description="The task identifier.")
|
||||
artifact_id: Optional[str] = Field(None, description="The artifact identifier.")
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
class Checkpoint(BaseModel):
|
||||
"""
|
||||
Core structure for a state checkpoint.
|
||||
|
||||
Attributes:
|
||||
id (str): Unique identifier for the checkpoint.
|
||||
ts (str): Timestamp of the checkpoint.
|
||||
metadata (CheckpointMetadata): Metadata associated with the checkpoint.
|
||||
values (dict[str, Any]): State values stored in the checkpoint.
|
||||
version (str): Version of the checkpoint format.
|
||||
parent_id (Optional[str]): Parent checkpoint identifier, if any.
|
||||
namespace (str): Namespace for the checkpoint, default is 'aworld'.
|
||||
"""
|
||||
id: str = Field(..., description="Unique identifier for the checkpoint.")
|
||||
ts: str = Field(..., description="Timestamp of the checkpoint.")
|
||||
metadata: CheckpointMetadata = Field(..., description="Metadata associated with the checkpoint.")
|
||||
values: Dict[str, Any] = Field(..., description="State values stored in the checkpoint.")
|
||||
version: int = Field(..., description="Version of the checkpoint format.")
|
||||
parent_id: Optional[str] = Field(default=None, description="Parent checkpoint identifier, if any.")
|
||||
namespace: str = Field(default="aworld", description="Namespace for the checkpoint, default is 'aworld'.")
|
||||
|
||||
def empty_checkpoint() -> Checkpoint:
|
||||
"""
|
||||
Create an empty checkpoint with default values.
|
||||
|
||||
Returns:
|
||||
Checkpoint: An empty checkpoint structure.
|
||||
"""
|
||||
return Checkpoint(
|
||||
id=str(uuid.uuid4()),
|
||||
ts=datetime.now(timezone.utc).isoformat(),
|
||||
metadata=CheckpointMetadata(session_id="", task_id=None),
|
||||
values={},
|
||||
version=1,
|
||||
parent_id=None,
|
||||
namespace="aworld",
|
||||
)
|
||||
|
||||
def copy_checkpoint(checkpoint: Checkpoint) -> Checkpoint:
|
||||
"""
|
||||
Create a deep copy of a checkpoint.
|
||||
|
||||
Args:
|
||||
checkpoint (Checkpoint): The checkpoint to copy.
|
||||
Returns:
|
||||
Checkpoint: A deep copy of the provided checkpoint.
|
||||
"""
|
||||
return copy.deepcopy(checkpoint)
|
||||
|
||||
def create_checkpoint(
|
||||
values: Dict[str, Any],
|
||||
metadata: CheckpointMetadata,
|
||||
parent_id: Optional[str] = None,
|
||||
version: int = 1,
|
||||
namespace: str = 'aworld',
|
||||
) -> Checkpoint:
|
||||
"""
|
||||
Create a new checkpoint from provided state values and metadata.
|
||||
|
||||
Args:
|
||||
values (dict[str, Any]): State values to store in the checkpoint.
|
||||
metadata (CheckpointMetadata): Metadata for the checkpoint.
|
||||
parent_id (Optional[str]): Parent checkpoint identifier, if any.
|
||||
version (str): Version of the checkpoint format.
|
||||
namespace (str): Namespace for the checkpoint.
|
||||
Returns:
|
||||
Checkpoint: The newly created checkpoint.
|
||||
"""
|
||||
return Checkpoint(
|
||||
id=str(uuid.uuid4()),
|
||||
ts=datetime.now(timezone.utc).isoformat(),
|
||||
metadata=metadata,
|
||||
values=values,
|
||||
version=version,
|
||||
parent_id=parent_id,
|
||||
namespace=namespace,
|
||||
)
|
||||
|
||||
class BaseCheckpointRepository(ABC):
|
||||
"""
|
||||
Abstract base class for a checkpoint repository.
|
||||
Provides synchronous and asynchronous methods for checkpoint management.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get(self, checkpoint_id: str) -> Optional[Checkpoint]:
|
||||
"""
|
||||
Retrieve a checkpoint by its unique identifier.
|
||||
|
||||
Args:
|
||||
checkpoint_id (str): The unique identifier of the checkpoint.
|
||||
Returns:
|
||||
Optional[Checkpoint]: The checkpoint if found, otherwise None.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def list(self, params: Dict[str, Any]) -> List[Checkpoint]:
|
||||
"""
|
||||
List checkpoints matching the given parameters.
|
||||
|
||||
Args:
|
||||
params (dict): Parameters to filter checkpoints.
|
||||
Returns:
|
||||
List[Checkpoint]: List of matching checkpoints.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def put(self, checkpoint: Checkpoint) -> None:
|
||||
"""
|
||||
Store a checkpoint.
|
||||
|
||||
Args:
|
||||
checkpoint (Checkpoint): The checkpoint to store.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_by_session(self, session_id: str) -> Optional[Checkpoint]:
|
||||
"""
|
||||
Get the latest checkpoint for a session.
|
||||
|
||||
Args:
|
||||
session_id (str): The session identifier.
|
||||
Returns:
|
||||
Optional[Checkpoint]: The latest checkpoint if found, otherwise None.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def delete_by_session(self, session_id: str) -> None:
|
||||
"""
|
||||
Delete all checkpoints related to a session.
|
||||
|
||||
Args:
|
||||
session_id (str): The session identifier.
|
||||
"""
|
||||
pass
|
||||
|
||||
# Async methods
|
||||
async def aget(self, checkpoint_id: str) -> Optional[Checkpoint]:
|
||||
"""
|
||||
Asynchronously retrieve a checkpoint by its unique identifier.
|
||||
|
||||
Args:
|
||||
checkpoint_id (str): The unique identifier of the checkpoint.
|
||||
Returns:
|
||||
Optional[Checkpoint]: The checkpoint if found, otherwise None.
|
||||
"""
|
||||
return await asyncio.to_thread(self.get, checkpoint_id)
|
||||
|
||||
async def alist(self, params: Dict[str, Any]) -> List[Checkpoint]:
|
||||
"""
|
||||
Asynchronously list checkpoints matching the given parameters.
|
||||
|
||||
Args:
|
||||
params (dict): Parameters to filter checkpoints.
|
||||
Returns:
|
||||
List[Checkpoint]: List of matching checkpoints.
|
||||
"""
|
||||
return await asyncio.to_thread(self.list, params)
|
||||
|
||||
async def aput(self, checkpoint: Checkpoint) -> None:
|
||||
"""
|
||||
Asynchronously store a checkpoint.
|
||||
|
||||
Args:
|
||||
checkpoint (Checkpoint): The checkpoint to store.
|
||||
"""
|
||||
await asyncio.to_thread(self.put, checkpoint)
|
||||
|
||||
async def aget_by_session(self, session_id: str) -> Optional[Checkpoint]:
|
||||
"""
|
||||
Asynchronously get the latest checkpoint for a session.
|
||||
|
||||
Args:
|
||||
session_id (str): The session identifier.
|
||||
Returns:
|
||||
Optional[Checkpoint]: The latest checkpoint if found, otherwise None.
|
||||
"""
|
||||
return await asyncio.to_thread(self.get_by_session, session_id)
|
||||
|
||||
async def adelete_by_session(self, session_id: str) -> None:
|
||||
"""
|
||||
Asynchronously delete all checkpoints related to a session.
|
||||
|
||||
Args:
|
||||
session_id (str): The session identifier.
|
||||
"""
|
||||
await asyncio.to_thread(self.delete_by_session, session_id)
|
||||
|
||||
class VersionUtils:
|
||||
|
||||
@staticmethod
|
||||
def get_next_version(version: int) -> int:
|
||||
"""
|
||||
Get the next version of the checkpoint.
|
||||
"""
|
||||
return version + 1
|
||||
|
||||
@staticmethod
|
||||
def get_previous_version(version: int) -> int:
|
||||
"""
|
||||
Get the previous version of the checkpoint.
|
||||
"""
|
||||
return version - 1
|
||||
|
||||
@staticmethod
|
||||
def is_version_greater(checkpoint: Checkpoint, version: int) -> bool:
|
||||
"""
|
||||
Check if the checkpoint version is greater than the given version.
|
||||
"""
|
||||
return checkpoint.version > version
|
||||
|
||||
@staticmethod
|
||||
def is_version_less(checkpoint: Checkpoint, version: int) -> bool:
|
||||
"""
|
||||
Check if the checkpoint version is less than the given version.
|
||||
"""
|
||||
return checkpoint.version < version
|
||||
@@ -0,0 +1,116 @@
|
||||
from typing import Any, Dict, List, Optional
|
||||
from . import Checkpoint, BaseCheckpointRepository, VersionUtils
|
||||
|
||||
class InMemoryCheckpointRepository(BaseCheckpointRepository):
|
||||
"""
|
||||
In-memory implementation of BaseCheckpointRepository.
|
||||
Stores checkpoints in a simple in-memory dictionary.
|
||||
Thread safety is not guaranteed.
|
||||
"""
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
Initialize the in-memory checkpoint repository.
|
||||
"""
|
||||
self._checkpoints: Dict[str, Checkpoint] = {}
|
||||
self._session_index: Dict[str, List[str]] = {}
|
||||
|
||||
def get(self, checkpoint_id: str) -> Optional[Checkpoint]:
|
||||
"""
|
||||
Retrieve a checkpoint by its unique identifier.
|
||||
Args:
|
||||
checkpoint_id (str): The unique identifier of the checkpoint.
|
||||
Returns:
|
||||
Optional[Checkpoint]: The checkpoint if found, otherwise None.
|
||||
"""
|
||||
return self._checkpoints.get(checkpoint_id)
|
||||
|
||||
def list(self, params: Dict[str, Any]) -> List[Checkpoint]:
|
||||
"""
|
||||
List checkpoints matching the given parameters.
|
||||
Args:
|
||||
params (dict): Parameters to filter checkpoints.
|
||||
Returns:
|
||||
List[Checkpoint]: List of matching checkpoints.
|
||||
"""
|
||||
result = []
|
||||
for cp in self._checkpoints.values():
|
||||
match = True
|
||||
for k, v in params.items():
|
||||
if k == 'session_id':
|
||||
if cp.metadata.session_id != v:
|
||||
match = False
|
||||
break
|
||||
elif k == 'task_id':
|
||||
if cp.metadata.task_id != v:
|
||||
match = False
|
||||
break
|
||||
elif cp.get(k) != v:
|
||||
match = False
|
||||
break
|
||||
if match:
|
||||
result.append(cp)
|
||||
return result
|
||||
|
||||
def put(self, checkpoint: Checkpoint) -> None:
|
||||
"""
|
||||
Store a checkpoint.
|
||||
Args:
|
||||
checkpoint (Checkpoint): The checkpoint to store.
|
||||
"""
|
||||
# Find last version checkpoint by session_id
|
||||
last_checkpoint = self.get_by_session(checkpoint.metadata.session_id)
|
||||
|
||||
if last_checkpoint:
|
||||
# Compare versions to ensure optimistic locking
|
||||
if VersionUtils.is_version_less(checkpoint, last_checkpoint.version):
|
||||
raise ValueError(f"New checkpoint version {checkpoint.version} must be greater than last version {last_checkpoint.version}")
|
||||
|
||||
# Store the new checkpoint
|
||||
self._checkpoints[checkpoint.id] = checkpoint
|
||||
|
||||
# Update session index
|
||||
session_id = checkpoint.metadata.session_id
|
||||
if session_id:
|
||||
if session_id not in self._session_index:
|
||||
self._session_index[session_id] = []
|
||||
self._session_index[session_id].append(checkpoint.id)
|
||||
|
||||
def get_by_session(self, session_id: str) -> Optional[Checkpoint]:
|
||||
"""
|
||||
Get the latest checkpoint for a session.
|
||||
Args:
|
||||
session_id (str): The session identifier.
|
||||
Returns:
|
||||
Optional[Checkpoint]: The latest checkpoint if found, otherwise None.
|
||||
"""
|
||||
ids = self._session_index.get(session_id, [])
|
||||
if not ids:
|
||||
return None
|
||||
# Assume the last one is the latest
|
||||
last_id = ids[-1]
|
||||
return self._checkpoints.get(last_id)
|
||||
|
||||
def delete_by_session(self, session_id: str) -> None:
|
||||
"""
|
||||
Delete all checkpoints related to a session.
|
||||
Args:
|
||||
session_id (str): The session identifier.
|
||||
"""
|
||||
ids = self._session_index.pop(session_id, [])
|
||||
for cid in ids:
|
||||
self._checkpoints.pop(cid, None)
|
||||
|
||||
async def alist(self, params: Dict[str, Any]) -> List[Checkpoint]:
|
||||
return self.list(params)
|
||||
|
||||
async def aget(self, checkpoint_id: str) -> Optional[Checkpoint]:
|
||||
return self.get(checkpoint_id)
|
||||
|
||||
async def aput(self, checkpoint: Checkpoint) -> None:
|
||||
self.put(checkpoint)
|
||||
|
||||
async def aget_by_session(self, session_id: str) -> Optional[Checkpoint]:
|
||||
return self.get_by_session(session_id)
|
||||
|
||||
async def adelete_by_session(self, session_id: str) -> None:
|
||||
self.delete_by_session(session_id)
|
||||
@@ -0,0 +1,2 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
@@ -0,0 +1,38 @@
|
||||
import click
|
||||
|
||||
|
||||
@click.group()
|
||||
def main(*args, **kwargs):
|
||||
print(
|
||||
"""\
|
||||
AWorld CLI Help:
|
||||
aworld web: run aworld web ui server
|
||||
aworld api: run aworld api server
|
||||
aworld help: show help"""
|
||||
)
|
||||
|
||||
|
||||
@main.command("web")
|
||||
@click.option(
|
||||
"--port", type=int, default=8000, help="Port to run the AWorld api server"
|
||||
)
|
||||
@click.argument("args", nargs=-1)
|
||||
def main_web(port, args=None, **kwargs):
|
||||
from .web import web_server
|
||||
|
||||
web_server.run_server(port, args, **kwargs)
|
||||
|
||||
|
||||
@main.command("api")
|
||||
@click.option(
|
||||
"--port", type=int, default=8000, help="Port to run the AWorld api server"
|
||||
)
|
||||
@click.argument("args", nargs=-1)
|
||||
def main_api(port, args=None, **kwargs):
|
||||
from .web import api_server
|
||||
|
||||
api_server.run_server(port, args, **kwargs)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,78 @@
|
||||
import datetime
|
||||
import uuid
|
||||
from abc import abstractmethod
|
||||
from typing import Any, AsyncGenerator, List, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from aworld.output.base import Output
|
||||
|
||||
|
||||
class ChatCompletionMessage(BaseModel):
|
||||
role: str = Field(..., description="The role of the message")
|
||||
content: str = Field(..., description="The content of the message")
|
||||
trace_id: Optional[str] = Field(None, description="The trace id")
|
||||
|
||||
|
||||
class ChatCompletionRequest(BaseModel):
|
||||
user_id: Optional[str] = Field(None, description="The user id")
|
||||
session_id: str = Field(
|
||||
None,
|
||||
description="The session id, if not provided, a new session will be created",
|
||||
)
|
||||
query_id: Optional[str] = Field(None, description="The query id")
|
||||
trace_id: Optional[str] = Field(None, description="The trace id")
|
||||
model: str = Field(..., description="The model to use")
|
||||
messages: List[ChatCompletionMessage] = Field(
|
||||
..., description="The messages to send to the agent"
|
||||
)
|
||||
|
||||
|
||||
class ChatCompletionChoice(BaseModel):
|
||||
index: int = 0
|
||||
delta: ChatCompletionMessage = Field(
|
||||
..., description="The delta message from the agent"
|
||||
)
|
||||
|
||||
|
||||
class ChatCompletionResponse(BaseModel):
|
||||
object: str = "chat.completion.chunk"
|
||||
id: str = uuid.uuid4().hex
|
||||
choices: List[ChatCompletionChoice] = Field(
|
||||
..., description="The choices from the agent"
|
||||
)
|
||||
|
||||
|
||||
class AgentModel(BaseModel):
|
||||
id: str = Field(..., description="The agent id")
|
||||
name: Optional[str] = Field(None, description="The agent name")
|
||||
description: Optional[str] = Field(None, description="The agent description")
|
||||
path: str = Field(..., description="The agent path")
|
||||
instance: Any = Field(..., description="The agent module instance", exclude=True)
|
||||
|
||||
|
||||
class BaseAWorldAgent:
|
||||
@abstractmethod
|
||||
def name(self) -> str:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def description(self) -> str:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def run(
|
||||
self, prompt: str = None, request: ChatCompletionRequest = None
|
||||
) -> AsyncGenerator[Output, None]:
|
||||
pass
|
||||
|
||||
|
||||
class SessionModel(BaseModel):
|
||||
user_id: str = Field(..., description="The user id")
|
||||
session_id: str = Field(..., description="The session id")
|
||||
name: str = Field(None, description="The session name")
|
||||
description: str = Field(None, description="The session description")
|
||||
created_at: datetime.datetime = Field(None, description="The session created at")
|
||||
updated_at: datetime.datetime = Field(None, description="The session updated at")
|
||||
messages: List[ChatCompletionMessage] = Field(
|
||||
None, description="The messages in the session"
|
||||
)
|
||||
@@ -0,0 +1,87 @@
|
||||
from typing import AsyncGenerator
|
||||
from aworld.cmd.utils.agent_server import AgentServer
|
||||
from aworld.output.ui.base import AworldUI
|
||||
from aworld.output.workspace import WorkSpace
|
||||
from aworld.cmd.data_model import (
|
||||
BaseAWorldAgent,
|
||||
ChatCompletionChoice,
|
||||
ChatCompletionMessage,
|
||||
ChatCompletionRequest,
|
||||
ChatCompletionResponse,
|
||||
)
|
||||
from .agent_ui_parser import AWorldWebAgentUI
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from dotenv import load_dotenv
|
||||
import traceback
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def stream_run(request: ChatCompletionRequest, agent_server: AgentServer):
|
||||
if not request.session_id:
|
||||
request.session_id = str(uuid.uuid4())
|
||||
if not request.query_id:
|
||||
request.query_id = str(uuid.uuid4())
|
||||
if request.messages and request.messages[-1].trace_id is None:
|
||||
request.messages[-1].trace_id = request.trace_id
|
||||
|
||||
logger.info(f"Stream run agent: request={request.model_dump_json()}")
|
||||
agent = agent_server.get_agent(request.model)
|
||||
instance: BaseAWorldAgent = agent.instance
|
||||
env_file = os.path.join(agent.path, ".env")
|
||||
if os.path.exists(env_file):
|
||||
logger.info(f"Loading environment variables from {env_file}")
|
||||
load_dotenv(env_file, override=True, verbose=True)
|
||||
|
||||
final_response: str = ""
|
||||
|
||||
def build_response(delta_content: str):
|
||||
nonlocal final_response
|
||||
final_response += delta_content
|
||||
logger.info(f"Agent {agent.name} response: {delta_content}")
|
||||
return ChatCompletionResponse(
|
||||
choices=[
|
||||
ChatCompletionChoice(
|
||||
index=0,
|
||||
delta=ChatCompletionMessage(
|
||||
role="assistant",
|
||||
content=delta_content,
|
||||
trace_id=request.trace_id,
|
||||
),
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
rich_ui = AWorldWebAgentUI(
|
||||
session_id=request.session_id,
|
||||
workspace=WorkSpace.from_local_storages(
|
||||
workspace_id=request.session_id,
|
||||
),
|
||||
)
|
||||
|
||||
await agent_server.on_chat_completion_request(request)
|
||||
try:
|
||||
async for output in instance.run(request=request):
|
||||
try:
|
||||
logger.info(f"Agent {agent.name} output: {output}")
|
||||
|
||||
if isinstance(output, str):
|
||||
yield build_response(output)
|
||||
else:
|
||||
res = await AworldUI.parse_output(output, rich_ui)
|
||||
for item in res if isinstance(res, list) else [res]:
|
||||
if isinstance(item, AsyncGenerator):
|
||||
async for sub_item in item:
|
||||
yield build_response(sub_item)
|
||||
else:
|
||||
yield build_response(item)
|
||||
except:
|
||||
logger.error(
|
||||
f"Agent {agent.name} output error! output={output}, error={traceback.format_exc()}"
|
||||
)
|
||||
except:
|
||||
logger.error(f"Agent {agent.name} error: {traceback.format_exc()}")
|
||||
finally:
|
||||
await agent_server.on_chat_completion_end(request, final_response)
|
||||
@@ -0,0 +1,112 @@
|
||||
import os
|
||||
import importlib
|
||||
import subprocess
|
||||
import sys
|
||||
import traceback
|
||||
import logging
|
||||
from typing import List, Dict
|
||||
from aworld.cmd.data_model import AgentModel
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_agent_cache: Dict[str, AgentModel] = {}
|
||||
|
||||
|
||||
def list_agents(server_dir: str) -> Dict[str, AgentModel]:
|
||||
"""
|
||||
List all cached agents
|
||||
|
||||
Returns:
|
||||
Dict[str, AgentModel]: The map of agent models
|
||||
"""
|
||||
if len(_agent_cache) == 0:
|
||||
for m in _list_agents(server_dir):
|
||||
_agent_cache[m.id] = m
|
||||
return _agent_cache
|
||||
|
||||
|
||||
def _list_agents(server_dir: str) -> List[AgentModel]:
|
||||
agents_dir = os.path.join(server_dir, "agent_deploy")
|
||||
|
||||
if not os.path.exists(agents_dir):
|
||||
logger.warning(f"Agents directory {agents_dir} does not exist")
|
||||
return []
|
||||
|
||||
if agents_dir not in sys.path:
|
||||
sys.path.append(agents_dir)
|
||||
|
||||
agents = []
|
||||
for agent_id in os.listdir(agents_dir):
|
||||
if agent_id.startswith("_"):
|
||||
continue
|
||||
try:
|
||||
agent_path = os.path.join(agents_dir, agent_id)
|
||||
if os.path.isdir(agent_path):
|
||||
requirements_file = os.path.join(agent_path, "requirements.txt")
|
||||
if os.path.exists(requirements_file):
|
||||
p = subprocess.Popen(
|
||||
["pip", "install", "-U", "-r", requirements_file],
|
||||
cwd=agent_path,
|
||||
)
|
||||
p.wait()
|
||||
if p.returncode != 0:
|
||||
logger.error(
|
||||
f"Error installing requirements for agent {agent_id}, path {agent_path}"
|
||||
)
|
||||
continue
|
||||
|
||||
agent_file = os.path.join(agent_path, "agent.py")
|
||||
if os.path.exists(agent_file):
|
||||
try:
|
||||
instance = _get_agent_instance(agent_id)
|
||||
if hasattr(instance, "name"):
|
||||
name = instance.name()
|
||||
else:
|
||||
name = agent_id
|
||||
if hasattr(instance, "description"):
|
||||
description = instance.description()
|
||||
else:
|
||||
description = ""
|
||||
agent_model = AgentModel(
|
||||
id=agent_id,
|
||||
name=name,
|
||||
description=description,
|
||||
path=agent_path,
|
||||
instance=instance,
|
||||
)
|
||||
|
||||
agents.append(agent_model)
|
||||
logger.info(
|
||||
f"Loaded agent {agent_id} successfully, path {agent_path}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error loading agent {agent_id}: {traceback.format_exc()}"
|
||||
)
|
||||
continue
|
||||
else:
|
||||
logger.warning(f"Agent {agent_id} does not have agent.py file")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error loading agent {agent_id}, path {agent_path} : {traceback.format_exc()}"
|
||||
)
|
||||
continue
|
||||
|
||||
return agents
|
||||
|
||||
|
||||
def _get_agent_instance(agent_name):
|
||||
try:
|
||||
agent_module = importlib.import_module(
|
||||
name=f"{agent_name}.agent",
|
||||
)
|
||||
except Exception as e:
|
||||
msg = f"Error loading agent {agent_name}, cwd:{os.getcwd()}, sys.path:{sys.path}: {traceback.format_exc()}"
|
||||
logger.error(msg)
|
||||
raise Exception(msg)
|
||||
|
||||
if hasattr(agent_module, "AWorldAgent"):
|
||||
agent = agent_module.AWorldAgent()
|
||||
return agent
|
||||
else:
|
||||
raise Exception(f"Agent {agent_name} does not have AWorldAgent class")
|
||||
@@ -0,0 +1,116 @@
|
||||
from abc import abstractmethod
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from aworld import trace
|
||||
from aworld.cmd.data_model import (
|
||||
AgentModel,
|
||||
ChatCompletionMessage,
|
||||
ChatCompletionRequest,
|
||||
)
|
||||
from aworld.session.base_session_service import BaseSessionService
|
||||
from aworld.session.simple_session_service import SimpleSessionService
|
||||
from . import agent_loader
|
||||
from aworld.trace.config import ObservabilityConfig
|
||||
from aworld.trace.opentelemetry.memory_storage import InMemoryWithPersistStorage
|
||||
|
||||
|
||||
# bugfix for tracer exception
|
||||
trace.configure(ObservabilityConfig(trace_storage=(InMemoryWithPersistStorage())))
|
||||
|
||||
|
||||
class ChatCallBack:
|
||||
@abstractmethod
|
||||
async def on_chat_completion_request(
|
||||
self, server: "AgentServer", request: ChatCompletionRequest
|
||||
):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def on_chat_completion_end(
|
||||
self, server: "AgentServer", request: ChatCompletionRequest, final_response: str
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
class SessionChatCallBack(ChatCallBack):
|
||||
|
||||
async def on_chat_completion_request(
|
||||
self, server: "AgentServer", request: ChatCompletionRequest
|
||||
):
|
||||
await server.get_session_service().append_messages(
|
||||
request.user_id,
|
||||
request.session_id,
|
||||
request.messages[-1:],
|
||||
)
|
||||
|
||||
async def on_chat_completion_end(
|
||||
self, server: "AgentServer", request: ChatCompletionRequest, final_response: str
|
||||
):
|
||||
await server.get_session_service().append_messages(
|
||||
request.user_id,
|
||||
request.session_id,
|
||||
[
|
||||
ChatCompletionMessage(
|
||||
role="assistant",
|
||||
content=final_response,
|
||||
trace_id=request.trace_id,
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class AgentServer:
|
||||
server_id: str
|
||||
server_name: str
|
||||
server_dir: str
|
||||
session_service: BaseSessionService = None
|
||||
agent_instances: Dict[str, AgentModel] = {}
|
||||
chat_call_backs: List[ChatCallBack] = [SessionChatCallBack()]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server_id: str,
|
||||
server_name: str,
|
||||
server_dir: str = os.getcwd(),
|
||||
session_service: BaseSessionService = SimpleSessionService(),
|
||||
):
|
||||
"""
|
||||
Initialize AgentServer
|
||||
"""
|
||||
self.server_id = server_id
|
||||
self.server_name = server_name
|
||||
self.server_dir = server_dir
|
||||
self.session_service = session_service
|
||||
# Load server global env
|
||||
load_dotenv(Path(self.server_dir) / ".env", override=True, verbose=True)
|
||||
# Load agent instances
|
||||
self.agent_instances = agent_loader.list_agents(self.server_dir)
|
||||
|
||||
def list_agents(self) -> Dict[str, AgentModel]:
|
||||
return self.agent_instances
|
||||
|
||||
def get_agent(self, agent_id: str) -> AgentModel:
|
||||
return self.agent_instances.get(agent_id)
|
||||
|
||||
def get_session_service(self) -> BaseSessionService:
|
||||
return self.session_service
|
||||
|
||||
async def on_chat_completion_request(self, request: ChatCompletionRequest):
|
||||
tasks = []
|
||||
for chat_call_back in self.chat_call_backs:
|
||||
tasks.append(chat_call_back.on_chat_completion_request(self, request))
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
async def on_chat_completion_end(
|
||||
self, request: ChatCompletionRequest, final_response: str
|
||||
):
|
||||
tasks = []
|
||||
for chat_call_back in self.chat_call_backs:
|
||||
tasks.append(
|
||||
chat_call_back.on_chat_completion_end(self, request, final_response)
|
||||
)
|
||||
await asyncio.gather(*tasks)
|
||||
@@ -0,0 +1,253 @@
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
import uuid
|
||||
|
||||
from pydantic import Field, BaseModel, ConfigDict
|
||||
|
||||
from aworld.output import (
|
||||
MessageOutput,
|
||||
AworldUI,
|
||||
Output,
|
||||
WorkSpace,
|
||||
)
|
||||
from aworld.output.artifact import Artifact, ArtifactType
|
||||
from aworld.output.base import StepOutput, ToolResultOutput
|
||||
from aworld.output.utils import consume_content
|
||||
from abc import ABC, abstractmethod
|
||||
from typing_extensions import override
|
||||
|
||||
|
||||
class ToolCard(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
tool_type: str = Field(None, description="tool type")
|
||||
tool_name: str = Field(None, description="tool name")
|
||||
function_name: str = Field(None, description="function name")
|
||||
tool_call_id: str = Field(None, description="tool call id")
|
||||
arguments: str = Field(None, description="arguments")
|
||||
results: str = Field(None, description="results")
|
||||
card_type: str = Field(None, description="card type")
|
||||
card_data: dict = Field(None, description="card data")
|
||||
artifacts: list = Field(default_factory=list, description="artifacts")
|
||||
|
||||
@staticmethod
|
||||
def from_tool_result(output: ToolResultOutput) -> "ToolCard":
|
||||
return ToolCard(
|
||||
tool_type=output.tool_type,
|
||||
tool_name=output.tool_name,
|
||||
function_name=output.origin_tool_call.function.name,
|
||||
tool_call_id=output.origin_tool_call.id,
|
||||
arguments=output.origin_tool_call.function.arguments,
|
||||
results=output.data,
|
||||
artifacts=[],
|
||||
)
|
||||
|
||||
|
||||
class BaseToolResultParser(ABC):
|
||||
|
||||
def __init__(self, tool_name: str = None):
|
||||
self.tool_name = tool_name or self.__class__.__name__
|
||||
|
||||
@abstractmethod
|
||||
async def parse(self, output: ToolResultOutput, workspace: WorkSpace):
|
||||
pass
|
||||
|
||||
|
||||
class DefaultToolResultParser(BaseToolResultParser):
|
||||
|
||||
@override
|
||||
async def parse(self, output: ToolResultOutput, workspace: WorkSpace):
|
||||
tool_card = ToolCard.from_tool_result(output)
|
||||
|
||||
tool_card.card_type = "tool_call_card_default"
|
||||
|
||||
# screenshots
|
||||
if (
|
||||
output.metadata.get("screenshots")
|
||||
and isinstance(output.metadata.get("screenshots"), list)
|
||||
and len(output.metadata.get("screenshots")) > 0
|
||||
):
|
||||
for _, screenshot in enumerate(output.metadata.get("screenshots")):
|
||||
image_artifact = Artifact(
|
||||
artifact_id=str(uuid.uuid4()),
|
||||
artifact_type=ArtifactType.IMAGE,
|
||||
content=screenshot.get("ossPath"),
|
||||
)
|
||||
await workspace.add_artifact(image_artifact)
|
||||
tool_card.artifacts.append(
|
||||
{
|
||||
"artifact_type": image_artifact.artifact_type.value,
|
||||
"artifact_id": image_artifact.artifact_id,
|
||||
}
|
||||
)
|
||||
|
||||
return f"""\
|
||||
\n\n**🔧 Tool: {tool_card.tool_name}#{tool_card.function_name}**\n\n
|
||||
```tool_card
|
||||
{json.dumps(tool_card.model_dump(), ensure_ascii=False, indent=2)}
|
||||
```\n
|
||||
"""
|
||||
|
||||
|
||||
class SearchToolResultParser(BaseToolResultParser):
|
||||
|
||||
@override
|
||||
async def parse(self, output: ToolResultOutput, workspace: WorkSpace):
|
||||
tool_card = ToolCard.from_tool_result(output)
|
||||
|
||||
query = ""
|
||||
try:
|
||||
args = json.loads(tool_card.arguments)
|
||||
query = args.get("query")
|
||||
# aworld search server
|
||||
if not query:
|
||||
query = args.get("query_list")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
result_items = []
|
||||
try:
|
||||
result_items = json.loads(tool_card.results)
|
||||
# aworld search server return url, not link
|
||||
if result_items and isinstance(result_items, list):
|
||||
for item in result_items:
|
||||
if not item.get("link", None) and item.get("url", None):
|
||||
item["link"] = item.get("url")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if len(result_items) > 0:
|
||||
tool_card.results = ""
|
||||
|
||||
tool_card.card_type = "tool_call_card_link_list"
|
||||
tool_card.card_data = {
|
||||
"title": "🔎 Google Search",
|
||||
"query": query,
|
||||
"search_items": result_items,
|
||||
}
|
||||
|
||||
artifact_id = str(uuid.uuid4())
|
||||
await workspace.create_artifact(
|
||||
artifact_type=ArtifactType.WEB_PAGES,
|
||||
artifact_id=artifact_id,
|
||||
content=result_items,
|
||||
metadata={
|
||||
"query": query,
|
||||
},
|
||||
)
|
||||
tool_card.artifacts.append(
|
||||
{
|
||||
"artifact_type": ArtifactType.WEB_PAGES.value,
|
||||
"artifact_id": artifact_id,
|
||||
}
|
||||
)
|
||||
|
||||
return f"""\
|
||||
\n\n**🔎 Search Results**\n\n
|
||||
```tool_card
|
||||
{json.dumps(tool_card.model_dump(), ensure_ascii=False, indent=2)}
|
||||
```\n
|
||||
"""
|
||||
|
||||
|
||||
class ToolResultParserFactory:
|
||||
def get_parser(self, tool_type: str, tool_name: str):
|
||||
if "search" in tool_name and ("search" in tool_name or tool_name == None):
|
||||
return SearchToolResultParser()
|
||||
else:
|
||||
return DefaultToolResultParser()
|
||||
|
||||
|
||||
@dataclass
|
||||
class AWorldWebAgentUI(AworldUI):
|
||||
session_id: str = Field(default="", description="session id")
|
||||
workspace: WorkSpace = Field(default=None, description="workspace")
|
||||
tool_result_parser_factory: ToolResultParserFactory = Field(
|
||||
default=ToolResultParserFactory, description="tool result parser factory"
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_id: str = None,
|
||||
workspace: WorkSpace = None,
|
||||
tool_result_parser_factory: ToolResultParserFactory = None,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialize MarkdownAworldUI
|
||||
Args:"""
|
||||
super().__init__(**kwargs)
|
||||
self.session_id = session_id
|
||||
self.workspace = workspace
|
||||
self.tool_result_parser_factory = (
|
||||
tool_result_parser_factory or ToolResultParserFactory()
|
||||
)
|
||||
|
||||
@override
|
||||
async def message_output(self, __output__: MessageOutput):
|
||||
"""
|
||||
Returns an async generator that yields each message item.
|
||||
"""
|
||||
# Sentinel object for queue completion
|
||||
_SENTINEL = object()
|
||||
|
||||
async def async_generator():
|
||||
async def __log_item(item):
|
||||
await queue.put(item)
|
||||
|
||||
from asyncio import Queue
|
||||
|
||||
queue = Queue()
|
||||
|
||||
async def consume_all():
|
||||
# Consume all relevant generators
|
||||
if __output__.reason_generator or __output__.response_generator:
|
||||
if __output__.reason_generator:
|
||||
await consume_content(__output__.reason_generator, __log_item)
|
||||
if __output__.response_generator:
|
||||
await consume_content(__output__.response_generator, __log_item)
|
||||
else:
|
||||
await consume_content(__output__.reasoning, __log_item)
|
||||
await consume_content(__output__.response, __log_item)
|
||||
# Only after all are done, put the sentinel
|
||||
await queue.put(_SENTINEL)
|
||||
|
||||
# Start the consumer in the background
|
||||
import asyncio
|
||||
|
||||
consumer_task = asyncio.create_task(consume_all())
|
||||
|
||||
while True:
|
||||
item = await queue.get()
|
||||
if item is _SENTINEL:
|
||||
break
|
||||
yield item
|
||||
await consumer_task # Ensure background task is finished
|
||||
|
||||
return async_generator()
|
||||
|
||||
@override
|
||||
async def tool_result(self, output: ToolResultOutput):
|
||||
"""
|
||||
tool_result
|
||||
"""
|
||||
parser = self.tool_result_parser_factory.get_parser(
|
||||
output.tool_type, output.tool_name
|
||||
)
|
||||
return await parser.parse(output, workspace=self.workspace)
|
||||
|
||||
@override
|
||||
async def step(self, output: StepOutput):
|
||||
emptyLine = "\n\n"
|
||||
if output.status == "START":
|
||||
return f"\n\n # {output.show_name} \n\n"
|
||||
elif output.status == "FINISHED":
|
||||
return f"{emptyLine}"
|
||||
elif output.status == "FAILED":
|
||||
return f"\n\n{output.name} 💥FAILED: reason is {output.data} {emptyLine}"
|
||||
else:
|
||||
return f"\n\n{output.name} ❓❓❓UNKNOWN#{output.status} {emptyLine}"
|
||||
|
||||
@override
|
||||
async def custom_output(self, output: Output):
|
||||
return output.data
|
||||
@@ -0,0 +1,175 @@
|
||||
import os
|
||||
import logging
|
||||
import traceback
|
||||
import asyncio
|
||||
import re
|
||||
import json
|
||||
import pickle
|
||||
from asyncio.tasks import Task
|
||||
from aworld.config.conf import AgentConfig
|
||||
from aworld.agents.llm_agent import Agent
|
||||
from typing import Dict, Union
|
||||
|
||||
from aworld.core.context.base import Context
|
||||
from aworld.utils.run_util import exec_agent
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SimpleSummaryCache:
|
||||
def __init__(self) -> None:
|
||||
self._cache_file = os.path.join(os.curdir, "data", "trace_summary_cache.pkl")
|
||||
self._cache: Dict[str, str] = {}
|
||||
self._load_cache()
|
||||
|
||||
def _load_cache(self):
|
||||
if os.path.exists(self._cache_file):
|
||||
try:
|
||||
with open(self._cache_file, "rb") as f:
|
||||
self._cache = pickle.load(f)
|
||||
except (pickle.PickleError, EOFError):
|
||||
logger.warning("Cache file is corrupted, creating new cache")
|
||||
if self._cache_file.exists():
|
||||
self._cache_file.unlink()
|
||||
|
||||
def _save_cache(self):
|
||||
serializable_cache = {
|
||||
k: v for k, v in self._cache.items() if not isinstance(v, Task)
|
||||
}
|
||||
try:
|
||||
with open(self._cache_file, "wb") as f:
|
||||
pickle.dump(serializable_cache, f)
|
||||
except pickle.PickleError:
|
||||
logger.error("Failed to save cache")
|
||||
|
||||
def add_to_cache(self, trace_id: str, value: Union[str, Task]):
|
||||
self._cache[trace_id] = value
|
||||
if not isinstance(value, Task):
|
||||
self._save_cache()
|
||||
|
||||
def get_value(self, trace_id: str) -> Union[str, Task]:
|
||||
return self._cache.get(trace_id)
|
||||
|
||||
def trace_exists(self, trace_id: str) -> bool:
|
||||
return trace_id in self._cache
|
||||
|
||||
|
||||
# _trace_summary_cache: Dict[str, Union[str, Task]] = {}
|
||||
_trace_summary_cache = SimpleSummaryCache()
|
||||
|
||||
trace_sys_prompt = "You are a helpful tracking summary agent."
|
||||
|
||||
trace_prompt = """
|
||||
you can use tracking tools to obtain tracking data and then summarize the main tasks completed by each agent and their token usage.
|
||||
You can identify which spans are agents, which spans are tool calls, and which spans are large model calls based on the following criteria:
|
||||
1 Agent span: the prefix for 'name' is 'event.agent.'
|
||||
2 LLM span: The prefix for 'name' is 'llm.'
|
||||
3 Tool span: The prefix for 'name' is 'event.tool.'
|
||||
|
||||
requirement:
|
||||
1. Please summarize and output separately for agents with different event.id.
|
||||
2. Agent Span with the same name but different event.id are also considered as different agents.
|
||||
3. There may be a parent-child relationship between agents. Please select the LLM span and Tool span from the nearest child span to the current agent for summarizing.
|
||||
4. Ensure that all agent spans have their own independent summaries, and the number of summaries is exactly the same as the number of agent spans. For example: {{"name":"event.agent.a","attributes":{{"event.id":"111"}},"children":[{{"name":"llm.gpt-4o"}},{{"name":"event.tool.1","children":[{{"name":"event.agent.a","attributes":{{"event.id":"222"}},"children":[{{"name":"llm.gpt-4o"}}]}}]}}]}}, both of the above two agent names are event.agent.a, but event.id is different and needs to be summarized separately for 111 and 222. So you need to identify all agent spans without any omissions, which is very important.
|
||||
5. Please output in the following standard JSON format without any additional explanatory text:
|
||||
[{{"agent":"947cc4c1b7ed406ab7fbf38b9d2b1f5a",,"summary":"xxx"}},{{}}]
|
||||
6. Pay attention to controlling the length of the summary, so that the overall output does not exceed your output length limit.
|
||||
Here are the trace_id: {task}
|
||||
"""
|
||||
|
||||
agent_config = None
|
||||
|
||||
|
||||
async def _do_summarize_trace(trace_id: str):
|
||||
logger.info(f"_do_summarize_trace trace_id: {trace_id}")
|
||||
global agent_config
|
||||
trace_agent = Agent(
|
||||
conf=agent_config,
|
||||
name="trace_agent",
|
||||
system_prompt=trace_sys_prompt,
|
||||
agent_prompt=trace_prompt,
|
||||
tool_names=["trace"],
|
||||
feedback_tool_result=True,
|
||||
)
|
||||
|
||||
if trace_agent.conf.llm_config.llm_api_key is None:
|
||||
logger.warning(
|
||||
"LLM_API_KEY_TRACE is not set, trace summarize will not be executed."
|
||||
)
|
||||
return ""
|
||||
try:
|
||||
res = await exec_agent(trace_id, trace_agent, Context())
|
||||
summary = _fetch_json_from_result(res.answer)
|
||||
_trace_summary_cache.add_to_cache(trace_id, summary)
|
||||
return summary
|
||||
except Exception as e:
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def summarize_trace(trace_id: str):
|
||||
global agent_config
|
||||
if agent_config is None:
|
||||
llm_provider = os.getenv("LLM_PROVIDER_TRACE", "openai")
|
||||
llm_model_name = os.getenv("LLM_MODEL_NAME_TRACE", None)
|
||||
llm_base_url = os.getenv("LLM_BASE_URL_TRACE", None)
|
||||
llm_api_key = os.getenv("LLM_API_KEY_TRACE", None)
|
||||
|
||||
if (
|
||||
not llm_provider
|
||||
or not llm_model_name
|
||||
or not llm_base_url
|
||||
or not llm_api_key
|
||||
):
|
||||
logger.warning(
|
||||
"LLM_MODEL_NAME_TRACE, LLM_BASE_URL_TRACE, LLM_API_KEY_TRACE is not set, trace summarize will not be executed."
|
||||
)
|
||||
return
|
||||
|
||||
agent_config = AgentConfig(
|
||||
llm_provider=os.getenv("LLM_PROVIDER_TRACE", "openai"),
|
||||
llm_model_name=os.getenv("LLM_MODEL_NAME_TRACE", None),
|
||||
llm_base_url=os.getenv("LLM_BASE_URL_TRACE", None),
|
||||
llm_api_key=os.getenv("LLM_API_KEY_TRACE", None),
|
||||
)
|
||||
llm_config = agent_config.llm_config
|
||||
if not _trace_summary_cache.trace_exists(trace_id):
|
||||
if (
|
||||
llm_config.llm_api_key is None
|
||||
or not llm_config.llm_base_url
|
||||
or not llm_config.llm_model_name
|
||||
):
|
||||
logger.warning(
|
||||
"LLM_MODEL_NAME_TRACE, LLM_BASE_URL_TRACE, LLM_API_KEY_TRACE is not set, trace summarize will not be executed."
|
||||
)
|
||||
return
|
||||
|
||||
task = asyncio.create_task(_do_summarize_trace(trace_id))
|
||||
_trace_summary_cache.add_to_cache(trace_id, task)
|
||||
|
||||
|
||||
async def get_summarize_trace(trace_id: str):
|
||||
if not _trace_summary_cache.trace_exists(trace_id):
|
||||
return None
|
||||
cached_value = _trace_summary_cache.get_value(trace_id)
|
||||
if isinstance(cached_value, Task):
|
||||
# try:
|
||||
# result = await cached_value
|
||||
# if isinstance(result, Task):
|
||||
# result = await result
|
||||
# _trace_summary_cache[trace_id] = _fetch_json_from_result(result)
|
||||
# except Exception as e:
|
||||
# logger.error(traceback.format_exc())
|
||||
return None
|
||||
return cached_value
|
||||
|
||||
|
||||
def _fetch_json_from_result(input_str):
|
||||
json_match = re.search(r"\[.*\]", input_str, re.DOTALL)
|
||||
if json_match:
|
||||
json_str = json_match.group(0)
|
||||
try:
|
||||
json.loads(json_str)
|
||||
return json_str
|
||||
except json.JSONDecodeError as e:
|
||||
logger.warning(f"_fetch_json_from_result json_str: {json_str} error: {e}")
|
||||
return ""
|
||||
@@ -0,0 +1,26 @@
|
||||
import subprocess
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def build_webui(force_rebuild: bool = False) -> str:
|
||||
webui_path = Path(__file__).parent.parent / "web" / "webui"
|
||||
static_path = webui_path / "dist"
|
||||
|
||||
if (not static_path.exists()) or force_rebuild:
|
||||
logger.warning(f"Build WebUI at {webui_path}")
|
||||
|
||||
try:
|
||||
subprocess.check_call(
|
||||
["sh", "-c", "npm install && npm run build"],
|
||||
cwd=webui_path,
|
||||
)
|
||||
logger.info("WebUI build successfully")
|
||||
except:
|
||||
logger.error(f"Failed to build WebUI at {webui_path}")
|
||||
sys.exit(1)
|
||||
|
||||
return static_path
|
||||
@@ -0,0 +1,32 @@
|
||||
import logging
|
||||
from fastapi import FastAPI
|
||||
import uvicorn
|
||||
|
||||
from aworld.cmd.utils.agent_server import AgentServer
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
agent_server = AgentServer(
|
||||
server_id="default_server",
|
||||
server_name="default_server",
|
||||
)
|
||||
|
||||
app.state.agent_server = agent_server
|
||||
|
||||
from .routers import chats, workspaces, sessions
|
||||
|
||||
app.include_router(chats.router, prefix=chats.prefix)
|
||||
app.include_router(workspaces.router, prefix=workspaces.prefix)
|
||||
app.include_router(sessions.router, prefix=sessions.prefix)
|
||||
|
||||
|
||||
def run_server(port, args=None, **kwargs):
|
||||
logger.info(f"Running API server on port {port}")
|
||||
uvicorn.run(
|
||||
app,
|
||||
host="0.0.0.0",
|
||||
port=port,
|
||||
)
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "web",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import logging
|
||||
import json
|
||||
from typing import Dict
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from aworld.cmd.data_model import AgentModel, ChatCompletionRequest
|
||||
from aworld.cmd.utils import agent_executor
|
||||
from aworld.cmd.utils.trace_summarize import summarize_trace
|
||||
from aworld.cmd.web.utils.users import get_user_id_from_jwt
|
||||
import aworld.trace as trace
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
prefix = "/api/agent"
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
@router.get("/models")
|
||||
async def list_agents(request: Request) -> Dict[str, AgentModel]:
|
||||
return request.app.state.agent_server.list_agents()
|
||||
|
||||
|
||||
@router.post("/chat/completions")
|
||||
async def chat_completion(
|
||||
form_data: ChatCompletionRequest,
|
||||
request: Request,
|
||||
user_id: str = Depends(get_user_id_from_jwt),
|
||||
) -> StreamingResponse:
|
||||
# Set user_id from JWT to form_data
|
||||
form_data.user_id = user_id
|
||||
|
||||
async def generate_stream():
|
||||
async with trace.span(
|
||||
"/chat/chat_completion", attributes={"model": form_data.model}
|
||||
) as span:
|
||||
form_data.trace_id = span.get_trace_id()
|
||||
async for chunk in agent_executor.stream_run(
|
||||
form_data, request.app.state.agent_server
|
||||
):
|
||||
yield f"data: {json.dumps(chunk.model_dump(), ensure_ascii=False)}\n\n"
|
||||
summarize_trace(form_data.trace_id)
|
||||
|
||||
return StreamingResponse(
|
||||
generate_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
import logging
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from aworld.cmd.data_model import SessionModel
|
||||
from aworld.cmd.web.utils.users import get_user_id_from_jwt
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
prefix = "/api/session"
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
async def list_sessions(
|
||||
request: Request,
|
||||
user_id: str = Depends(get_user_id_from_jwt),
|
||||
) -> List[SessionModel]:
|
||||
return await request.app.state.agent_server.get_session_service().list_sessions(
|
||||
user_id
|
||||
)
|
||||
|
||||
|
||||
class CommonResponse(BaseModel):
|
||||
code: int = Field(..., description="The code")
|
||||
message: str = Field(..., description="The message")
|
||||
|
||||
@staticmethod
|
||||
def success(message: str = "success"):
|
||||
return CommonResponse(code=0, message=message)
|
||||
|
||||
@staticmethod
|
||||
def error(message: str):
|
||||
return CommonResponse(code=1, message=message)
|
||||
|
||||
|
||||
class DeleteSessionRequest(BaseModel):
|
||||
session_id: str = Field(..., description="The session id")
|
||||
|
||||
|
||||
@router.post("/delete")
|
||||
async def delete_session(
|
||||
request: DeleteSessionRequest, user_id: str = Depends(get_user_id_from_jwt)
|
||||
) -> CommonResponse:
|
||||
try:
|
||||
await request.app.state.agent_server.get_session_service().delete_session(
|
||||
user_id, request.session_id
|
||||
)
|
||||
return CommonResponse.success()
|
||||
except Exception as e:
|
||||
return CommonResponse.error(str(e))
|
||||
@@ -0,0 +1,50 @@
|
||||
import json
|
||||
import logging
|
||||
from fastapi import APIRouter
|
||||
from aworld.trace.server import get_trace_server
|
||||
from aworld.trace.server.util import build_trace_tree, get_agent_flow
|
||||
from aworld.cmd.utils.trace_summarize import get_summarize_trace
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
prefix = "/api/trace"
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
async def list_traces():
|
||||
storage = get_trace_server().get_storage()
|
||||
trace_data = []
|
||||
for trace_id in storage.get_all_traces():
|
||||
spans = storage.get_all_spans(trace_id)
|
||||
spans_sorted = sorted(spans, key=lambda x: x.start_time)
|
||||
trace_tree = build_trace_tree(spans_sorted)
|
||||
trace_data.append({
|
||||
'trace_id': trace_id,
|
||||
'root_span': trace_tree,
|
||||
})
|
||||
return {
|
||||
"data": trace_data
|
||||
}
|
||||
|
||||
|
||||
@router.get("/agent")
|
||||
async def get_agent_trace(trace_id: str):
|
||||
data = get_agent_flow(trace_id)
|
||||
await _add_trace_summary(trace_id, data.get('nodes'))
|
||||
return data
|
||||
|
||||
|
||||
async def _add_trace_summary(trace_id, spans):
|
||||
summary = await get_summarize_trace(trace_id)
|
||||
json_summary_dict = {}
|
||||
if summary:
|
||||
json_summary = json.loads(summary)
|
||||
json_summary_dict = {item['agent']: json.dumps(
|
||||
item) for item in json_summary}
|
||||
|
||||
for span in spans:
|
||||
if summary and "event_id" in span:
|
||||
span['summary'] = json_summary_dict.get(span['event_id'])
|
||||
span['attributes'] = None
|
||||
@@ -0,0 +1,74 @@
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Query, Body
|
||||
|
||||
from aworld.output import WorkSpace, ArtifactType
|
||||
from aworld.output.utils import load_workspace
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
prefix = "/api/workspaces"
|
||||
|
||||
@router.get("/{workspace_id}/tree")
|
||||
async def get_workspace_tree(workspace_id: str):
|
||||
logging.info(f"get_workspace_tree: {workspace_id}")
|
||||
workspace = await get_workspace(workspace_id)
|
||||
return workspace.generate_tree_data()
|
||||
|
||||
|
||||
class ArtifactRequest(BaseModel):
|
||||
artifact_ids: Optional[List[str]] = None
|
||||
artifact_types: Optional[List[str]] = None
|
||||
|
||||
|
||||
@router.post("/{workspace_id}/artifacts")
|
||||
async def get_workspace_artifacts(workspace_id: str, request: ArtifactRequest):
|
||||
"""
|
||||
Get artifacts by workspace id and filter by a list of artifact types.
|
||||
Args:
|
||||
workspace_id: Workspace ID
|
||||
request: Request body containing optional artifact_types list
|
||||
Returns:
|
||||
Dict with filtered artifacts
|
||||
"""
|
||||
artifact_types = request.artifact_types
|
||||
if artifact_types:
|
||||
# Validate all types
|
||||
invalid_types = [t for t in artifact_types if t not in ArtifactType.__members__]
|
||||
if invalid_types:
|
||||
logging.error(f"Invalid artifact_types: {invalid_types}")
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Invalid artifact types: {invalid_types}")
|
||||
logging.info(f"Fetching artifacts of types: {artifact_types}")
|
||||
else:
|
||||
logging.info(f"Fetching all artifacts (no type filter)")
|
||||
|
||||
workspace = await get_workspace(workspace_id)
|
||||
all_artifacts = workspace.list_artifacts()
|
||||
filtered_artifacts = all_artifacts
|
||||
if request.artifact_ids:
|
||||
filtered_artifacts = [a for a in filtered_artifacts if a.artifact_id in request.artifact_ids]
|
||||
if artifact_types:
|
||||
filtered_artifacts = [a for a in filtered_artifacts if a.artifact_type.name in artifact_types]
|
||||
|
||||
return {
|
||||
"data": filtered_artifacts
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{workspace_id}/file/{artifact_id}/content")
|
||||
async def get_workspace_file_content(workspace_id: str, artifact_id: str):
|
||||
logging.info(f"get_workspace_file_content: {workspace_id}, {artifact_id}")
|
||||
workspace = await get_workspace(workspace_id)
|
||||
return {
|
||||
"data": workspace.get_file_content_by_artifact_id(artifact_id)
|
||||
}
|
||||
|
||||
|
||||
async def get_workspace(workspace_id: str) -> WorkSpace:
|
||||
workspace_type = os.environ.get("WORKSPACE_TYPE", "local")
|
||||
workspace_path = os.environ.get("WORKSPACE_PATH", "./data/workspaces")
|
||||
return await load_workspace(workspace_id, workspace_type, workspace_path)
|
||||
@@ -0,0 +1,4 @@
|
||||
from fastapi import Request
|
||||
|
||||
def get_user_id_from_jwt(request: Request) -> str:
|
||||
return f"default_user_001"
|
||||
@@ -0,0 +1,62 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
import uvicorn
|
||||
import os
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from aworld.cmd.utils.agent_server import AgentServer
|
||||
from aworld.cmd.utils.webui_builder import build_webui
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return RedirectResponse("/index.html")
|
||||
|
||||
agent_server = AgentServer(
|
||||
server_id="default_server",
|
||||
server_name="default_server",
|
||||
)
|
||||
|
||||
app.state.agent_server = agent_server
|
||||
|
||||
from .routers import chats, workspaces, sessions, traces # noqa
|
||||
|
||||
app.include_router(chats.router, prefix=chats.prefix)
|
||||
app.include_router(workspaces.router, prefix=workspaces.prefix)
|
||||
app.include_router(sessions.router, prefix=sessions.prefix)
|
||||
app.include_router(traces.router, prefix=traces.prefix)
|
||||
|
||||
|
||||
static_path = build_webui(force_rebuild=os.getenv("AWORLD_WEB_UI_FORCE_REBUILD", False))
|
||||
logger.info(f"Mounting static files from {static_path}")
|
||||
app.mount("/", StaticFiles(directory=static_path, html=True), name="static")
|
||||
|
||||
|
||||
class TimeoutMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app, timeout: int = 300):
|
||||
super().__init__(app)
|
||||
self.timeout = timeout
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
try:
|
||||
return await asyncio.wait_for(call_next(request), timeout=self.timeout)
|
||||
except asyncio.TimeoutError:
|
||||
return Response("Request timeout", status_code=408)
|
||||
|
||||
|
||||
app.add_middleware(TimeoutMiddleware, timeout=300)
|
||||
|
||||
|
||||
def run_server(port, args=None, **kwargs):
|
||||
logger.info(f"Running Web server on port {port}")
|
||||
uvicorn.run(
|
||||
app,
|
||||
host="0.0.0.0",
|
||||
port=port,
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
Front End Code Here
|
||||
+1
File diff suppressed because one or more lines are too long
+261
File diff suppressed because one or more lines are too long
BIN
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
+68
File diff suppressed because one or more lines are too long
+281
File diff suppressed because one or more lines are too long
+85
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
body{margin:0}
|
||||
+1
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/aworld_logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Aworld</title>
|
||||
<script type="module" crossorigin src="/assets/index-C7nkBYbk.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-TZrNw7dA.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,526 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Trace Viewer V2</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
|
||||
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
||||
<script src="https://unpkg.com/element-plus"></script>
|
||||
<script src="https://unpkg.com/@element-plus/icons-vue"></script>
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<style>
|
||||
.trace-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
.trace-content {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.trace-list {
|
||||
width: 30%;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.trace-detail {
|
||||
width: 70%;
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.timeline {
|
||||
height: 120px;
|
||||
min-width: 100%;
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.span-node {
|
||||
cursor: pointer;
|
||||
padding: 5px 0;
|
||||
}
|
||||
|
||||
.span-node:hover {
|
||||
background-color: #f0f7ff;
|
||||
}
|
||||
|
||||
.span-duration {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.timeline-bg {
|
||||
fill: #f8f8f8;
|
||||
}
|
||||
|
||||
.axis--x path {
|
||||
stroke: #333;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.axis--x line {
|
||||
stroke: #ddd;
|
||||
}
|
||||
|
||||
.axis--x text {
|
||||
font-size: 12px;
|
||||
fill: #333;
|
||||
}
|
||||
|
||||
.timeline-visualization {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
background: #f8f8f8;
|
||||
border-left: 1px solid #e6e6e6;
|
||||
overflow-y: auto;
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.span-visualization-container {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
margin-top: 40px;
|
||||
}
|
||||
|
||||
.span-visualization {
|
||||
height: 20px;
|
||||
background: #409EFF;
|
||||
position: absolute;
|
||||
margin-top: 2px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.span-label {
|
||||
font-size: 8px;
|
||||
color: white;
|
||||
padding: 0 5px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.trace-timeline {
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.trace-timeline svg {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.trace-timeline .axis path {
|
||||
stroke: #333;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.trace-timeline .axis line {
|
||||
stroke: #ddd;
|
||||
}
|
||||
|
||||
.trace-timeline .axis text {
|
||||
font-size: 12px;
|
||||
fill: #333;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app" class="trace-container">
|
||||
<!-- Top timeline -->
|
||||
<div class="timeline">
|
||||
<div id="timeline-chart"></div>
|
||||
</div>
|
||||
<div class="trace-content">
|
||||
<div class="trace-list">
|
||||
<div style="padding: 10px; border-bottom: 1px solid #e6e6e6;">
|
||||
<el-input v-model="searchTraceId" placeholder="输入Trace ID搜索" style="width: 100%;"
|
||||
@keyup.enter="searchByTraceId">
|
||||
<template #append>
|
||||
<el-button @click="searchByTraceId">
|
||||
<el-icon>
|
||||
<search />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
</div>
|
||||
<el-tree :data="traceTree" node-key="span_id" :props="treeProps" :expand-on-click-node="false"
|
||||
@node-click="handleNodeClick" :default-expanded-keys="expandedNodes">
|
||||
<template #default="{ node, data }">
|
||||
<span class="span-node">
|
||||
{{ data.name }}
|
||||
<span class="span-duration">({{ data.duration_ms.toFixed(2) }}ms)</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree>
|
||||
</div>
|
||||
|
||||
<div class="timeline-visualization" v-if="selectedSpan" v-html="renderTimelineVisualization()">
|
||||
</div>
|
||||
</div>
|
||||
<!-- Span detail -->
|
||||
<el-dialog v-model="dialogVisible" title="Span Details" width="70%">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="Trace ID">{{ selectedSpan.trace_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Span ID">{{ selectedSpan.span_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Parent Span ID">{{ selectedSpan.parent_id || 'None'
|
||||
}}</el-descriptions-item>
|
||||
<el-descriptions-item label="Name">{{ selectedSpan.name }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Status">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<span :style="{color: selectedSpan.status.code === 'StatusCode.ERROR' ? '#F56C6C' : ''}">
|
||||
{{ selectedSpan.status.code }}
|
||||
</span>
|
||||
<el-button v-if="selectedSpan.status.code === 'StatusCode.ERROR'" type="text" size="small"
|
||||
@click="showStacktrace = true" icon="View" style="color: #F56C6C">
|
||||
View Stack
|
||||
</el-button>
|
||||
</div>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="Start Time">{{ selectedSpan.start_time}}</el-descriptions-item>
|
||||
<el-descriptions-item label="End Time">{{ selectedSpan.end_time }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Duration">{{ selectedSpan.duration_ms.toFixed(2) }}
|
||||
ms</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<el-card style="margin-top: 20px;">
|
||||
<template #header>
|
||||
<h4>Attributes</h4>
|
||||
</template>
|
||||
<pre style="
|
||||
max-height: 400px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
background: #f8f8f8;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
">{{ formatAttributes(selectedSpan.attributes) }}</pre>
|
||||
</el-card>
|
||||
</el-dialog>
|
||||
<el-dialog v-model="showStacktrace" title="Stacktrace Details" width="70%">
|
||||
<pre>{{ formatStacktrace(selectedSpan.attributes?.['exception.stacktrace'] || "No stacktrace available") }}</pre>
|
||||
</el-dialog>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const { createApp, ref, onMounted, nextTick } = Vue;
|
||||
const { Search } = ElementPlusIconsVue;
|
||||
createApp({
|
||||
setup() {
|
||||
const traces = ref([]);
|
||||
const traceTree = ref([]);
|
||||
const selectedSpan = ref(null);
|
||||
const expandedNodes = ref([]);
|
||||
const searchTraceId = ref('');
|
||||
const showStacktrace = ref(false);
|
||||
|
||||
const treeProps = {
|
||||
label: 'name',
|
||||
children: 'children'
|
||||
};
|
||||
const dialogVisible = ref(false);
|
||||
|
||||
function searchByTraceId() {
|
||||
if (!searchTraceId.value) {
|
||||
buildTraceTree();
|
||||
return;
|
||||
}
|
||||
const filtered = traces.value.filter(trace =>
|
||||
trace.trace_id.includes(searchTraceId.value)
|
||||
);
|
||||
|
||||
const tree = [];
|
||||
filtered.forEach(trace => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const root = buildSpanTree(trace.root_span[0]);
|
||||
tree.push(root);
|
||||
}
|
||||
});
|
||||
traceTree.value = tree;
|
||||
}
|
||||
|
||||
function initTimeline() {
|
||||
const timelineContainer = document.getElementById('timeline-chart');
|
||||
const width = timelineContainer.clientWidth;
|
||||
const height = 100;
|
||||
const margin = { top: 20, right: 20, bottom: 30, left: 20 };
|
||||
|
||||
const svg = d3.select(timelineContainer)
|
||||
.append('svg')
|
||||
.attr('width', width)
|
||||
.attr('height', height);
|
||||
|
||||
const now = new Date();
|
||||
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
|
||||
const x = d3.scaleTime()
|
||||
.domain([oneDayAgo, now])
|
||||
.range([margin.left, width - margin.right]);
|
||||
|
||||
svg.append('g')
|
||||
.attr('transform', `translate(0,${height - margin.bottom})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(d3.timeHour.every(2))
|
||||
.tickFormat(d3.timeFormat("%H:%M")));
|
||||
|
||||
svg.append('g')
|
||||
.attr('class', 'grid')
|
||||
.attr('transform', `translate(0,${height - margin.bottom})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(d3.timeMinute.every(10))
|
||||
.tickSize(-5)
|
||||
.tickFormat(''));
|
||||
|
||||
if (traces.value && traces.value.length > 0) {
|
||||
const colorScale = d3.scaleOrdinal()
|
||||
.domain(traces.value.map((_, i) => i))
|
||||
.range(d3.schemeCategory10);
|
||||
traces.value.forEach((trace, index) => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const span = trace.root_span[0];
|
||||
const startTime = new Date(span.start_time);
|
||||
const endTime = new Date(span.end_time);
|
||||
const duration = endTime - startTime;
|
||||
|
||||
if (startTime >= oneDayAgo && startTime <= now) {
|
||||
svg.append('rect')
|
||||
.attr('x', x(startTime))
|
||||
.attr('y', margin.top + 30)
|
||||
.attr('width', Math.max(3, x(endTime) - x(startTime)))
|
||||
.attr('height', 20)
|
||||
.attr('fill', colorScale(index))
|
||||
.attr('rx', 2)
|
||||
.attr('opacity', 0.7)
|
||||
.on('mouseover', function () {
|
||||
d3.select(this).attr('opacity', 1);
|
||||
})
|
||||
.on('mouseout', function () {
|
||||
d3.select(this).attr('opacity', 0.7);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function renderTimelineVisualization() {
|
||||
if (!selectedSpan.value) return '';
|
||||
|
||||
const currentTrace = traceTree.value.find(t => t.trace_id === selectedSpan.value.trace_id);
|
||||
if (!currentTrace) return '';
|
||||
|
||||
const rootSpan = currentTrace.root_span?.[0] || currentTrace;
|
||||
let minTime = new Date(rootSpan.start_time).getTime();
|
||||
let maxTime = new Date(rootSpan.end_time).getTime();
|
||||
|
||||
const timelineContainer = document.createElement('div');
|
||||
timelineContainer.className = 'trace-timeline';
|
||||
timelineContainer.style.height = '60px';
|
||||
timelineContainer.style.marginBottom = '20px';
|
||||
timelineContainer.style.width = '100%';
|
||||
|
||||
const svg = d3.select(timelineContainer)
|
||||
.append('svg')
|
||||
.attr('width', '100%')
|
||||
.attr('height', '100%')
|
||||
.attr('viewBox', '0 0 1000 60');
|
||||
|
||||
const margin = { top: 10, right: 0, bottom: 30, left: 0 };
|
||||
const width = 1000 - margin.left - margin.right;
|
||||
const height = 60 - margin.top - margin.bottom;
|
||||
|
||||
const g = svg.append('g')
|
||||
.attr('transform', `translate(${margin.left},${margin.top})`);
|
||||
|
||||
|
||||
const x = d3.scaleTime()
|
||||
.domain([new Date(minTime), new Date(maxTime)])
|
||||
.range([0, width]);
|
||||
|
||||
g.append('g')
|
||||
.attr('class', 'axis axis--x')
|
||||
.attr('transform', `translate(0,${height})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(5)
|
||||
.tickFormat(d3.timeFormat("%H:%M:%S.%L")));
|
||||
|
||||
g.selectAll(".grid-line")
|
||||
.data(x.ticks(5))
|
||||
.enter().append("line")
|
||||
.attr("class", "grid-line")
|
||||
.attr("x1", d => x(d))
|
||||
.attr("x2", d => x(d))
|
||||
.attr("y1", 0)
|
||||
.attr("y2", height)
|
||||
.attr("stroke", "#eee")
|
||||
.attr("stroke-width", 1);
|
||||
|
||||
const timelineHtml = timelineContainer.outerHTML;
|
||||
|
||||
function renderSpans(span, depth = 0, rowIndex = 0) {
|
||||
const spanStart = new Date(span.start_time).getTime();
|
||||
const spanEnd = new Date(span.end_time).getTime();
|
||||
const position = Math.min(13, Math.max(5, ((spanStart - minTime) / (maxTime - minTime)) * 10 * 0.9 + 5));
|
||||
const width = Math.min(92, Math.max(2, ((spanEnd - spanStart) / (maxTime - minTime)) * 100 * 0.9 + 2));
|
||||
//const position = ((spanStart - minTime) / (maxTime - minTime)) * 10 * 0.9 + 5;
|
||||
//const width = ((spanEnd - spanStart) / (maxTime - minTime)) * 100 * 0.9 + 2;
|
||||
|
||||
const minWidth = 0.5;
|
||||
const adjustedWidth = Math.max(width, minWidth);
|
||||
|
||||
const row = rowIndex * 24;
|
||||
|
||||
let childrenHtml = '';
|
||||
let nextRowIndex = rowIndex + 1;
|
||||
|
||||
if (span.children && span.children.length > 0) {
|
||||
childrenHtml = span.children.map(child => {
|
||||
const childHtml = renderSpans(child, depth + 1, nextRowIndex);
|
||||
nextRowIndex += countSpans(child);
|
||||
return childHtml;
|
||||
}).join('');
|
||||
}
|
||||
return `
|
||||
<div class="span-visualization"
|
||||
style="top: ${row}px;
|
||||
left: ${position}%;
|
||||
width: ${adjustedWidth}%;
|
||||
background: ${span.status.code === 'StatusCode.ERROR' ? '#F56C6C' : '#409EFF'};
|
||||
opacity: ${span.span_id === selectedSpan.value.span_id ? 1 : 0.6}"
|
||||
onclick="window.handleSpanClick.call(this, ${JSON.stringify(span).replace(/"/g, '"')})">
|
||||
<span class="span-label">${span.duration_ms} ${span.name}</span>
|
||||
</div>
|
||||
${childrenHtml}
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<h3>Timeline Visualization</h3>
|
||||
${timelineHtml}
|
||||
<div class="span-visualization-container" style="height: ${traceTree.value.length * 24 + 100}px">
|
||||
${renderSpans(rootSpan)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function countSpans(span) {
|
||||
let count = 1;
|
||||
if (span.children && span.children.length > 0) {
|
||||
span.children.forEach(child => {
|
||||
count += countSpans(child);
|
||||
});
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
async function fetchTraces() {
|
||||
try {
|
||||
const response = await fetch('/api/trace/list');
|
||||
const data = await response.json();
|
||||
traces.value = data.data;
|
||||
buildTraceTree();
|
||||
initTimeline();
|
||||
} catch (error) {
|
||||
console.error('Error loading traces:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function buildTraceTree() {
|
||||
const tree = [];
|
||||
traces.value.forEach(trace => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const root = buildSpanTree(trace.root_span[0]);
|
||||
tree.push(root);
|
||||
}
|
||||
});
|
||||
traceTree.value = tree;
|
||||
}
|
||||
|
||||
function buildSpanTree(span) {
|
||||
const node = {
|
||||
...span,
|
||||
children: []
|
||||
};
|
||||
|
||||
if (span.children && span.children.length > 0) {
|
||||
span.children.forEach(child => {
|
||||
node.children.push(buildSpanTree(child));
|
||||
});
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
function handleNodeClick(data) {
|
||||
selectedSpan.value = data;
|
||||
nextTick(() => {
|
||||
renderTimelineVisualization();
|
||||
});
|
||||
}
|
||||
|
||||
function handleSpanClick(data) {
|
||||
selectedSpan.value = data;
|
||||
dialogVisible.value = true;
|
||||
if (!expandedNodes.value.includes(data.span_id)) {
|
||||
expandedNodes.value.push(data.span_id);
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(timestamp) {
|
||||
return timestamp.split('.')[0];
|
||||
}
|
||||
|
||||
function formatAttributes(attrs) {
|
||||
return JSON.stringify(attrs, null, 2);
|
||||
}
|
||||
|
||||
function formatStacktrace(stacktrace) {
|
||||
if (!stacktrace) return 'No stacktrace available';
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(stacktrace), null, 2);
|
||||
} catch {
|
||||
return stacktrace;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchTraces();
|
||||
//setInterval(fetchTraces, 5000);
|
||||
window.handleSpanClick = handleSpanClick;
|
||||
});
|
||||
|
||||
return {
|
||||
traces,
|
||||
traceTree,
|
||||
selectedSpan,
|
||||
expandedNodes,
|
||||
treeProps,
|
||||
handleNodeClick,
|
||||
handleSpanClick,
|
||||
formatTime,
|
||||
formatAttributes,
|
||||
dialogVisible,
|
||||
renderTimelineVisualization,
|
||||
searchTraceId,
|
||||
searchByTraceId,
|
||||
showStacktrace,
|
||||
formatStacktrace
|
||||
};
|
||||
}
|
||||
}).use(ElementPlus).component('search', Search).mount('#app');
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist'] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/aworld_logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Aworld</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "Aworld-UI",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/x": "^1.4.0",
|
||||
"@xyflow/react": "^12.8.1",
|
||||
"antd": "^5.26.0",
|
||||
"antd-style": "^3.7.1",
|
||||
"dagre": "^0.8.5",
|
||||
"mermaid": "^11.7.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router-dom": "^6.30.1",
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.25.0",
|
||||
"@types/dagre": "^0.7.53",
|
||||
"@types/node": "^24.0.4",
|
||||
"@types/react": "^18.2.0",
|
||||
"@types/react-dom": "^18.2.0",
|
||||
"@vitejs/plugin-react": "^4.4.1",
|
||||
"eslint": "^9.25.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.19",
|
||||
"globals": "^16.0.0",
|
||||
"less": "^4.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.30.1",
|
||||
"vite": "^6.3.5"
|
||||
},
|
||||
"repository": "git@github.com:inclusionAI/AWorld.git"
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,526 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Trace Viewer V2</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
|
||||
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
||||
<script src="https://unpkg.com/element-plus"></script>
|
||||
<script src="https://unpkg.com/@element-plus/icons-vue"></script>
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<style>
|
||||
.trace-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
.trace-content {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.trace-list {
|
||||
width: 30%;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.trace-detail {
|
||||
width: 70%;
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.timeline {
|
||||
height: 120px;
|
||||
min-width: 100%;
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.span-node {
|
||||
cursor: pointer;
|
||||
padding: 5px 0;
|
||||
}
|
||||
|
||||
.span-node:hover {
|
||||
background-color: #f0f7ff;
|
||||
}
|
||||
|
||||
.span-duration {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.timeline-bg {
|
||||
fill: #f8f8f8;
|
||||
}
|
||||
|
||||
.axis--x path {
|
||||
stroke: #333;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.axis--x line {
|
||||
stroke: #ddd;
|
||||
}
|
||||
|
||||
.axis--x text {
|
||||
font-size: 12px;
|
||||
fill: #333;
|
||||
}
|
||||
|
||||
.timeline-visualization {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
background: #f8f8f8;
|
||||
border-left: 1px solid #e6e6e6;
|
||||
overflow-y: auto;
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.span-visualization-container {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
margin-top: 40px;
|
||||
}
|
||||
|
||||
.span-visualization {
|
||||
height: 20px;
|
||||
background: #409EFF;
|
||||
position: absolute;
|
||||
margin-top: 2px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.span-label {
|
||||
font-size: 8px;
|
||||
color: white;
|
||||
padding: 0 5px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.trace-timeline {
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.trace-timeline svg {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.trace-timeline .axis path {
|
||||
stroke: #333;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.trace-timeline .axis line {
|
||||
stroke: #ddd;
|
||||
}
|
||||
|
||||
.trace-timeline .axis text {
|
||||
font-size: 12px;
|
||||
fill: #333;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app" class="trace-container">
|
||||
<!-- Top timeline -->
|
||||
<div class="timeline">
|
||||
<div id="timeline-chart"></div>
|
||||
</div>
|
||||
<div class="trace-content">
|
||||
<div class="trace-list">
|
||||
<div style="padding: 10px; border-bottom: 1px solid #e6e6e6;">
|
||||
<el-input v-model="searchTraceId" placeholder="输入Trace ID搜索" style="width: 100%;"
|
||||
@keyup.enter="searchByTraceId">
|
||||
<template #append>
|
||||
<el-button @click="searchByTraceId">
|
||||
<el-icon>
|
||||
<search />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
</div>
|
||||
<el-tree :data="traceTree" node-key="span_id" :props="treeProps" :expand-on-click-node="false"
|
||||
@node-click="handleNodeClick" :default-expanded-keys="expandedNodes">
|
||||
<template #default="{ node, data }">
|
||||
<span class="span-node">
|
||||
{{ data.name }}
|
||||
<span class="span-duration">({{ data.duration_ms.toFixed(2) }}ms)</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree>
|
||||
</div>
|
||||
|
||||
<div class="timeline-visualization" v-if="selectedSpan" v-html="renderTimelineVisualization()">
|
||||
</div>
|
||||
</div>
|
||||
<!-- Span detail -->
|
||||
<el-dialog v-model="dialogVisible" title="Span Details" width="70%">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="Trace ID">{{ selectedSpan.trace_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Span ID">{{ selectedSpan.span_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Parent Span ID">{{ selectedSpan.parent_id || 'None'
|
||||
}}</el-descriptions-item>
|
||||
<el-descriptions-item label="Name">{{ selectedSpan.name }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Status">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<span :style="{color: selectedSpan.status.code === 'StatusCode.ERROR' ? '#F56C6C' : ''}">
|
||||
{{ selectedSpan.status.code }}
|
||||
</span>
|
||||
<el-button v-if="selectedSpan.status.code === 'StatusCode.ERROR'" type="text" size="small"
|
||||
@click="showStacktrace = true" icon="View" style="color: #F56C6C">
|
||||
View Stack
|
||||
</el-button>
|
||||
</div>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="Start Time">{{ selectedSpan.start_time}}</el-descriptions-item>
|
||||
<el-descriptions-item label="End Time">{{ selectedSpan.end_time }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Duration">{{ selectedSpan.duration_ms.toFixed(2) }}
|
||||
ms</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<el-card style="margin-top: 20px;">
|
||||
<template #header>
|
||||
<h4>Attributes</h4>
|
||||
</template>
|
||||
<pre style="
|
||||
max-height: 400px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
background: #f8f8f8;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
">{{ formatAttributes(selectedSpan.attributes) }}</pre>
|
||||
</el-card>
|
||||
</el-dialog>
|
||||
<el-dialog v-model="showStacktrace" title="Stacktrace Details" width="70%">
|
||||
<pre>{{ formatStacktrace(selectedSpan.attributes?.['exception.stacktrace'] || "No stacktrace available") }}</pre>
|
||||
</el-dialog>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const { createApp, ref, onMounted, nextTick } = Vue;
|
||||
const { Search } = ElementPlusIconsVue;
|
||||
createApp({
|
||||
setup() {
|
||||
const traces = ref([]);
|
||||
const traceTree = ref([]);
|
||||
const selectedSpan = ref(null);
|
||||
const expandedNodes = ref([]);
|
||||
const searchTraceId = ref('');
|
||||
const showStacktrace = ref(false);
|
||||
|
||||
const treeProps = {
|
||||
label: 'name',
|
||||
children: 'children'
|
||||
};
|
||||
const dialogVisible = ref(false);
|
||||
|
||||
function searchByTraceId() {
|
||||
if (!searchTraceId.value) {
|
||||
buildTraceTree();
|
||||
return;
|
||||
}
|
||||
const filtered = traces.value.filter(trace =>
|
||||
trace.trace_id.includes(searchTraceId.value)
|
||||
);
|
||||
|
||||
const tree = [];
|
||||
filtered.forEach(trace => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const root = buildSpanTree(trace.root_span[0]);
|
||||
tree.push(root);
|
||||
}
|
||||
});
|
||||
traceTree.value = tree;
|
||||
}
|
||||
|
||||
function initTimeline() {
|
||||
const timelineContainer = document.getElementById('timeline-chart');
|
||||
const width = timelineContainer.clientWidth;
|
||||
const height = 100;
|
||||
const margin = { top: 20, right: 20, bottom: 30, left: 20 };
|
||||
|
||||
const svg = d3.select(timelineContainer)
|
||||
.append('svg')
|
||||
.attr('width', width)
|
||||
.attr('height', height);
|
||||
|
||||
const now = new Date();
|
||||
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
|
||||
const x = d3.scaleTime()
|
||||
.domain([oneDayAgo, now])
|
||||
.range([margin.left, width - margin.right]);
|
||||
|
||||
svg.append('g')
|
||||
.attr('transform', `translate(0,${height - margin.bottom})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(d3.timeHour.every(2))
|
||||
.tickFormat(d3.timeFormat("%H:%M")));
|
||||
|
||||
svg.append('g')
|
||||
.attr('class', 'grid')
|
||||
.attr('transform', `translate(0,${height - margin.bottom})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(d3.timeMinute.every(10))
|
||||
.tickSize(-5)
|
||||
.tickFormat(''));
|
||||
|
||||
if (traces.value && traces.value.length > 0) {
|
||||
const colorScale = d3.scaleOrdinal()
|
||||
.domain(traces.value.map((_, i) => i))
|
||||
.range(d3.schemeCategory10);
|
||||
traces.value.forEach((trace, index) => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const span = trace.root_span[0];
|
||||
const startTime = new Date(span.start_time);
|
||||
const endTime = new Date(span.end_time);
|
||||
const duration = endTime - startTime;
|
||||
|
||||
if (startTime >= oneDayAgo && startTime <= now) {
|
||||
svg.append('rect')
|
||||
.attr('x', x(startTime))
|
||||
.attr('y', margin.top + 30)
|
||||
.attr('width', Math.max(3, x(endTime) - x(startTime)))
|
||||
.attr('height', 20)
|
||||
.attr('fill', colorScale(index))
|
||||
.attr('rx', 2)
|
||||
.attr('opacity', 0.7)
|
||||
.on('mouseover', function () {
|
||||
d3.select(this).attr('opacity', 1);
|
||||
})
|
||||
.on('mouseout', function () {
|
||||
d3.select(this).attr('opacity', 0.7);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function renderTimelineVisualization() {
|
||||
if (!selectedSpan.value) return '';
|
||||
|
||||
const currentTrace = traceTree.value.find(t => t.trace_id === selectedSpan.value.trace_id);
|
||||
if (!currentTrace) return '';
|
||||
|
||||
const rootSpan = currentTrace.root_span?.[0] || currentTrace;
|
||||
let minTime = new Date(rootSpan.start_time).getTime();
|
||||
let maxTime = new Date(rootSpan.end_time).getTime();
|
||||
|
||||
const timelineContainer = document.createElement('div');
|
||||
timelineContainer.className = 'trace-timeline';
|
||||
timelineContainer.style.height = '60px';
|
||||
timelineContainer.style.marginBottom = '20px';
|
||||
timelineContainer.style.width = '100%';
|
||||
|
||||
const svg = d3.select(timelineContainer)
|
||||
.append('svg')
|
||||
.attr('width', '100%')
|
||||
.attr('height', '100%')
|
||||
.attr('viewBox', '0 0 1000 60');
|
||||
|
||||
const margin = { top: 10, right: 0, bottom: 30, left: 0 };
|
||||
const width = 1000 - margin.left - margin.right;
|
||||
const height = 60 - margin.top - margin.bottom;
|
||||
|
||||
const g = svg.append('g')
|
||||
.attr('transform', `translate(${margin.left},${margin.top})`);
|
||||
|
||||
|
||||
const x = d3.scaleTime()
|
||||
.domain([new Date(minTime), new Date(maxTime)])
|
||||
.range([0, width]);
|
||||
|
||||
g.append('g')
|
||||
.attr('class', 'axis axis--x')
|
||||
.attr('transform', `translate(0,${height})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(5)
|
||||
.tickFormat(d3.timeFormat("%H:%M:%S.%L")));
|
||||
|
||||
g.selectAll(".grid-line")
|
||||
.data(x.ticks(5))
|
||||
.enter().append("line")
|
||||
.attr("class", "grid-line")
|
||||
.attr("x1", d => x(d))
|
||||
.attr("x2", d => x(d))
|
||||
.attr("y1", 0)
|
||||
.attr("y2", height)
|
||||
.attr("stroke", "#eee")
|
||||
.attr("stroke-width", 1);
|
||||
|
||||
const timelineHtml = timelineContainer.outerHTML;
|
||||
|
||||
function renderSpans(span, depth = 0, rowIndex = 0) {
|
||||
const spanStart = new Date(span.start_time).getTime();
|
||||
const spanEnd = new Date(span.end_time).getTime();
|
||||
const position = Math.min(13, Math.max(5, ((spanStart - minTime) / (maxTime - minTime)) * 10 * 0.9 + 5));
|
||||
const width = Math.min(92, Math.max(2, ((spanEnd - spanStart) / (maxTime - minTime)) * 100 * 0.9 + 2));
|
||||
//const position = ((spanStart - minTime) / (maxTime - minTime)) * 10 * 0.9 + 5;
|
||||
//const width = ((spanEnd - spanStart) / (maxTime - minTime)) * 100 * 0.9 + 2;
|
||||
|
||||
const minWidth = 0.5;
|
||||
const adjustedWidth = Math.max(width, minWidth);
|
||||
|
||||
const row = rowIndex * 24;
|
||||
|
||||
let childrenHtml = '';
|
||||
let nextRowIndex = rowIndex + 1;
|
||||
|
||||
if (span.children && span.children.length > 0) {
|
||||
childrenHtml = span.children.map(child => {
|
||||
const childHtml = renderSpans(child, depth + 1, nextRowIndex);
|
||||
nextRowIndex += countSpans(child);
|
||||
return childHtml;
|
||||
}).join('');
|
||||
}
|
||||
return `
|
||||
<div class="span-visualization"
|
||||
style="top: ${row}px;
|
||||
left: ${position}%;
|
||||
width: ${adjustedWidth}%;
|
||||
background: ${span.status.code === 'StatusCode.ERROR' ? '#F56C6C' : '#409EFF'};
|
||||
opacity: ${span.span_id === selectedSpan.value.span_id ? 1 : 0.6}"
|
||||
onclick="window.handleSpanClick.call(this, ${JSON.stringify(span).replace(/"/g, '"')})">
|
||||
<span class="span-label">${span.duration_ms} ${span.name}</span>
|
||||
</div>
|
||||
${childrenHtml}
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<h3>Timeline Visualization</h3>
|
||||
${timelineHtml}
|
||||
<div class="span-visualization-container" style="height: ${traceTree.value.length * 24 + 100}px">
|
||||
${renderSpans(rootSpan)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function countSpans(span) {
|
||||
let count = 1;
|
||||
if (span.children && span.children.length > 0) {
|
||||
span.children.forEach(child => {
|
||||
count += countSpans(child);
|
||||
});
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
async function fetchTraces() {
|
||||
try {
|
||||
const response = await fetch('/api/trace/list');
|
||||
const data = await response.json();
|
||||
traces.value = data.data;
|
||||
buildTraceTree();
|
||||
initTimeline();
|
||||
} catch (error) {
|
||||
console.error('Error loading traces:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function buildTraceTree() {
|
||||
const tree = [];
|
||||
traces.value.forEach(trace => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const root = buildSpanTree(trace.root_span[0]);
|
||||
tree.push(root);
|
||||
}
|
||||
});
|
||||
traceTree.value = tree;
|
||||
}
|
||||
|
||||
function buildSpanTree(span) {
|
||||
const node = {
|
||||
...span,
|
||||
children: []
|
||||
};
|
||||
|
||||
if (span.children && span.children.length > 0) {
|
||||
span.children.forEach(child => {
|
||||
node.children.push(buildSpanTree(child));
|
||||
});
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
function handleNodeClick(data) {
|
||||
selectedSpan.value = data;
|
||||
nextTick(() => {
|
||||
renderTimelineVisualization();
|
||||
});
|
||||
}
|
||||
|
||||
function handleSpanClick(data) {
|
||||
selectedSpan.value = data;
|
||||
dialogVisible.value = true;
|
||||
if (!expandedNodes.value.includes(data.span_id)) {
|
||||
expandedNodes.value.push(data.span_id);
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(timestamp) {
|
||||
return timestamp.split('.')[0];
|
||||
}
|
||||
|
||||
function formatAttributes(attrs) {
|
||||
return JSON.stringify(attrs, null, 2);
|
||||
}
|
||||
|
||||
function formatStacktrace(stacktrace) {
|
||||
if (!stacktrace) return 'No stacktrace available';
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(stacktrace), null, 2);
|
||||
} catch {
|
||||
return stacktrace;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchTraces();
|
||||
//setInterval(fetchTraces, 5000);
|
||||
window.handleSpanClick = handleSpanClick;
|
||||
});
|
||||
|
||||
return {
|
||||
traces,
|
||||
traceTree,
|
||||
selectedSpan,
|
||||
expandedNodes,
|
||||
treeProps,
|
||||
handleNodeClick,
|
||||
handleSpanClick,
|
||||
formatTime,
|
||||
formatAttributes,
|
||||
dialogVisible,
|
||||
renderTimelineVisualization,
|
||||
searchTraceId,
|
||||
searchByTraceId,
|
||||
showStacktrace,
|
||||
formatStacktrace
|
||||
};
|
||||
}
|
||||
}).use(ElementPlus).component('search', Search).mount('#app');
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
import { request } from '@/utils/http';
|
||||
|
||||
export const fetchTraceData = (traceId: string) => {
|
||||
return request(`/api/trace/agent?trace_id=${traceId}`);
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
import { request } from '../utils/http';
|
||||
|
||||
/**
|
||||
* 工作空间树节点数据结构
|
||||
*/
|
||||
export interface WorkspaceTreeResponse {
|
||||
id: string; // 节点ID
|
||||
name: string; // 节点名称
|
||||
type: string; // 节点类型 (dir/file)
|
||||
parentId: string | null; // 父节点ID
|
||||
depth: number; // 节点深度
|
||||
expanded: boolean; // 是否展开
|
||||
children: WorkspaceTreeResponse[]; // 子节点列表
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Artifact的请求参数
|
||||
*/
|
||||
export interface ArtifactQueryRequest {
|
||||
artifact_types: string[]; // Artifact类型
|
||||
artifact_ids: string[]; // Artifact ID
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建Artifact的请求参数
|
||||
*/
|
||||
export interface ArtifactCreateRequest {
|
||||
name: string; // Artifact名称
|
||||
type: string; // Artifact类型
|
||||
content: any; // Artifact内容
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建Artifact的响应数据
|
||||
*/
|
||||
export interface ArtifactCreateResponse {
|
||||
id: string; // 创建的Artifact ID
|
||||
status: 'success' | 'failed'; // 操作状态
|
||||
message?: string; // 可选的状态信息
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取工作空间树
|
||||
*/
|
||||
export const getWorkspaceTree = (sessionId: string) =>
|
||||
request(`api/workspaces/${sessionId}/tree`);
|
||||
|
||||
|
||||
/**
|
||||
* 获取工作空间Artifacts
|
||||
*/
|
||||
export const getWorkspaceArtifacts = (sessionId: string, body: ArtifactQueryRequest) =>
|
||||
request(`api/workspaces/${sessionId}/artifacts`, {
|
||||
method: 'POST',
|
||||
body
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* 创建工作空间Artifact
|
||||
*/
|
||||
export const createArtifact = (workspaceId: string, body: ArtifactCreateRequest) =>
|
||||
request(`api/workspaces/${workspaceId}/artifacts`, {
|
||||
method: 'POST',
|
||||
body
|
||||
});
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1 @@
|
||||
export const DEFAULT_NAME = '';
|
||||
@@ -0,0 +1,4 @@
|
||||
declare module '*.less' {
|
||||
const classes: { [key: string]: string };
|
||||
export default classes;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
body{
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export const useAgentId = () => {
|
||||
const [agentId, setAgentId] = useState<string>('');
|
||||
|
||||
// 从URL参数中获取agent ID
|
||||
const getAgentIdFromURL = (): string => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
return urlParams.get('agentid') || '';
|
||||
};
|
||||
|
||||
// 更新URL参数中的agent ID
|
||||
const updateURLAgentId = (id: string) => {
|
||||
const url = new URL(window.location.href);
|
||||
if (id) {
|
||||
url.searchParams.set('agentid', id);
|
||||
} else {
|
||||
url.searchParams.delete('agentid');
|
||||
}
|
||||
window.history.replaceState({}, '', url.toString());
|
||||
};
|
||||
|
||||
// 设置新的agent ID并更新URL
|
||||
const setAgentIdAndUpdateURL = (id: string) => {
|
||||
setAgentId(id);
|
||||
updateURLAgentId(id);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// 初始化时检查URL中是否有agent ID
|
||||
const urlAgentId = getAgentIdFromURL();
|
||||
|
||||
if (urlAgentId) {
|
||||
// 如果URL中有agent ID,使用它
|
||||
setAgentId(urlAgentId);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
agentId,
|
||||
setAgentIdAndUpdateURL,
|
||||
updateURLAgentId,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
export const useSessionId = () => {
|
||||
const [sessionId, setSessionId] = useState<string>('');
|
||||
|
||||
// 从URL参数中获取session ID
|
||||
const getSessionIdFromURL = (): string => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
return urlParams.get('session_id') || '';
|
||||
};
|
||||
|
||||
// 更新URL参数中的session ID
|
||||
const updateURLSessionId = (id: string) => {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('session_id', id);
|
||||
window.history.replaceState({}, '', url.toString());
|
||||
};
|
||||
|
||||
// 生成新的session ID并更新URL
|
||||
const generateNewSessionId = (): string => {
|
||||
const newId = uuidv4();
|
||||
setSessionId(newId);
|
||||
updateURLSessionId(newId);
|
||||
console.log('generateNewSessionId', newId);
|
||||
return newId;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// 初始化时检查URL中是否有session ID
|
||||
const urlSessionId = getSessionIdFromURL();
|
||||
|
||||
if (urlSessionId) {
|
||||
// 如果URL中有session ID,使用它
|
||||
setSessionId(urlSessionId);
|
||||
} else {
|
||||
// 如果URL中没有session ID,生成一个新的
|
||||
generateNewSessionId();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
setSessionId,
|
||||
generateNewSessionId,
|
||||
updateURLSessionId,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { HashRouter } from 'react-router-dom'
|
||||
import './global.less'
|
||||
import Router from './router'
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<HashRouter>
|
||||
<Router />
|
||||
</HashRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
.ant-bubble-content .ant-bubble-content-filled{
|
||||
background-color: red;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
.defaultbox{
|
||||
position: relative;
|
||||
.btn-workspace{
|
||||
position: absolute;
|
||||
top: -40px;
|
||||
right: 0;
|
||||
}
|
||||
.pre-wrap{
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.action-btn {
|
||||
color: #1890ff;
|
||||
cursor: pointer;
|
||||
transition: color 0.3s;
|
||||
padding: 0 4px;
|
||||
|
||||
&:hover {
|
||||
color: #40a9ff;
|
||||
}
|
||||
|
||||
&:active {
|
||||
color: #096dd9;
|
||||
}
|
||||
}
|
||||
.ant-collapse{
|
||||
// width: 668px;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { MenuUnfoldOutlined } from '@ant-design/icons';
|
||||
import { Button, Collapse, Space, message } from 'antd';
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import type { ToolCardData } from '../utils';
|
||||
import './index.less';
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
data: ToolCardData;
|
||||
onOpenWorkspace: (data: ToolCardData) => void;
|
||||
}
|
||||
|
||||
const CardDefault: React.FC<Props> = ({ sessionId, data, onOpenWorkspace }) => {
|
||||
// 当前展开的面板keys
|
||||
const [activeKeys, setActiveKeys] = useState<string[]>([]);
|
||||
|
||||
// 处理复制
|
||||
const handleCopy = useCallback(
|
||||
async (panelKey: string) => {
|
||||
try {
|
||||
const content = panelKey === '1' ? data.arguments : data.results;
|
||||
await navigator.clipboard.writeText(content);
|
||||
message.success('Copy Successful');
|
||||
} catch (error) {
|
||||
message.error('Copy Failed');
|
||||
}
|
||||
},
|
||||
[data]
|
||||
);
|
||||
// 打开workspace
|
||||
const handleOpenWorkspace = useCallback(() => {
|
||||
if (onOpenWorkspace) {
|
||||
onOpenWorkspace(data);
|
||||
}
|
||||
}, [onOpenWorkspace, sessionId, data]);
|
||||
|
||||
//操作按钮
|
||||
const renderExtra = useCallback(
|
||||
(panelKey: string) => (
|
||||
<Space size="small" onClick={(e) => e.stopPropagation()}>
|
||||
<span className="action-btn" onClick={() => handleCopy(panelKey)}>
|
||||
Copy
|
||||
</span>
|
||||
</Space>
|
||||
),
|
||||
[handleCopy]
|
||||
);
|
||||
|
||||
const items = [
|
||||
{
|
||||
key: '1',
|
||||
label: 'tool_call_arguments',
|
||||
extra: renderExtra('1'),
|
||||
children: (
|
||||
<pre className="pre-wrap">
|
||||
<code>{data.arguments}</code>
|
||||
</pre>
|
||||
)
|
||||
},
|
||||
{
|
||||
key: '2',
|
||||
label: 'tool_call_result',
|
||||
extra: renderExtra('2'),
|
||||
children: (
|
||||
<pre className="pre-wrap">
|
||||
<code>{data.results}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="defaultbox">
|
||||
{data?.artifacts?.length > 0 && (
|
||||
<Button type="link" className="btn-workspace" icon={<MenuUnfoldOutlined />} onClick={handleOpenWorkspace}>
|
||||
View Workspace
|
||||
</Button>
|
||||
)}
|
||||
<Collapse activeKey={activeKeys} onChange={(keys) => setActiveKeys(Array.isArray(keys) ? keys : [keys])} items={items} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(CardDefault);
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
.cardwrap {
|
||||
background-color: #eee;
|
||||
border-radius: 10px;
|
||||
padding: 10px;
|
||||
position: relative;
|
||||
.btn-workspace {
|
||||
position: absolute;
|
||||
top: -38px;
|
||||
right: -6px;
|
||||
}
|
||||
.card-length {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
.ant-tag {
|
||||
max-width: 480px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
padding: 0 10px;
|
||||
border-radius: 8px;
|
||||
line-height: 24px;
|
||||
}
|
||||
.check-icon {
|
||||
color: #1890ff;
|
||||
margin-right: 8px;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.cardbox {
|
||||
// width: 668px;
|
||||
// width: 648px;
|
||||
overflow-x: auto;
|
||||
margin-top: 10px;
|
||||
.card-item {
|
||||
width: 175px;
|
||||
min-width: 175px;
|
||||
// margin-bottom: 16px;
|
||||
.ant-card-head {
|
||||
padding: 0 14px;
|
||||
min-height: 50px;
|
||||
}
|
||||
.ant-card-body {
|
||||
padding: 10px 14px 12px;
|
||||
.desc {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
& + .card-item {
|
||||
margin-left: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { CheckOutlined, MenuUnfoldOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { Button, Card, Flex, Tag, Typography } from 'antd';
|
||||
import React, { useCallback } from 'react';
|
||||
import type { ToolCardData } from '../utils';
|
||||
import './index.less';
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
data: ToolCardData;
|
||||
onOpenWorkspace?: (data: ToolCardData) => void;
|
||||
}
|
||||
|
||||
interface ItemInterface {
|
||||
title: string;
|
||||
snippet: string;
|
||||
link?: string;
|
||||
}
|
||||
|
||||
const cardLinkList: React.FC<Props> = ({ sessionId, data, onOpenWorkspace }) => {
|
||||
const items = data?.card_data?.search_items;
|
||||
|
||||
const cardItems = Array.isArray(items) ? items.filter((item) => item?.title && item?.link) : [];
|
||||
// 打开workspace
|
||||
const handleOpenWorkspace = useCallback(() => {
|
||||
if (onOpenWorkspace) {
|
||||
onOpenWorkspace(data);
|
||||
}
|
||||
}, [onOpenWorkspace, sessionId, data]);
|
||||
|
||||
return (
|
||||
<div className="cardwrap bg">
|
||||
<Button type="link" className="btn-workspace" icon={<MenuUnfoldOutlined />} onClick={handleOpenWorkspace}>
|
||||
View Workspace
|
||||
</Button>
|
||||
<Flex justify="space-between" align="center" className="card-length">
|
||||
<Tag icon={<SearchOutlined />}>{`search keywords: ${data?.card_data?.query || ''}`}</Tag>
|
||||
<Flex align="center">
|
||||
<CheckOutlined className="check-icon" />
|
||||
{cardItems.length} results
|
||||
</Flex>
|
||||
</Flex>
|
||||
<div className="border-box">
|
||||
<Flex className="cardbox">
|
||||
{cardItems?.map((item: ItemInterface, index: number) => (
|
||||
<Card title={item?.title} key={index} className="card-item" onClick={() => item?.link && window.open(item?.link, '_blank', 'noopener,noreferrer')}>
|
||||
<Typography.Paragraph className="desc" ellipsis={{ rows: 3, tooltip: typeof item?.snippet === 'string' ? item?.snippet : '' }}>
|
||||
{item?.snippet}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Text ellipsis={{ tooltip: typeof item?.link === 'string' ? item?.link : '' }}>{item?.link}</Typography.Text>
|
||||
</Card>
|
||||
))}
|
||||
</Flex>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default cardLinkList;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
.markdownbox{
|
||||
p>strong{
|
||||
padding-left: 5px;
|
||||
}
|
||||
pre{
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import CardDefault from './cardDefault';
|
||||
import CardLinkList from './cardLinkList';
|
||||
import './index.less';
|
||||
import type { ToolCardData } from './utils';
|
||||
import { extractToolCards } from './utils';
|
||||
|
||||
interface BubbleItemProps {
|
||||
sessionId: string;
|
||||
data: string;
|
||||
trace_id: string;
|
||||
onOpenWorkspace?: (data: ToolCardData) => void;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
const BubbleItem: React.FC<BubbleItemProps> = ({ sessionId, data, onOpenWorkspace, isLoading = false }) => {
|
||||
// 用于记录上次打开的workspace数据,避免重复调用
|
||||
const lastWorkspaceDataRef = useRef<ToolCardData | null>(null);
|
||||
|
||||
// 修改openWorkspace函数,直接调用外部回调
|
||||
const openWorkspace = (data: ToolCardData) => {
|
||||
if (onOpenWorkspace) {
|
||||
onOpenWorkspace(data);
|
||||
}
|
||||
};
|
||||
|
||||
const { segments } = extractToolCards(data);
|
||||
|
||||
// 比较两个workspace数据是否相同
|
||||
const isWorkspaceDataEqual = (data1: ToolCardData | null, data2: ToolCardData | null): boolean => {
|
||||
if (!data1 && !data2) return true;
|
||||
if (!data1 || !data2) return false;
|
||||
|
||||
// 比较关键字段来判断是否为同一个workspace
|
||||
return (
|
||||
data1.tool_call_id === data2.tool_call_id &&
|
||||
data1.artifacts?.length === data2.artifacts?.length &&
|
||||
JSON.stringify(data1.artifacts) === JSON.stringify(data2.artifacts)
|
||||
);
|
||||
};
|
||||
|
||||
// 自动打开workspace的逻辑 - 只在流式输出过程中自动打开
|
||||
useEffect(() => {
|
||||
// 只有在流式输出过程中才自动打开workspace
|
||||
if (!isLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 查找最新的具有workspace功能的tool_card(不区分card类型)
|
||||
const toolCardSegments = segments.filter(segment => segment.type === 'tool_card');
|
||||
|
||||
// 从最后一个开始查找,找到第一个有artifacts的tool_card
|
||||
const latestWorkspaceCard = toolCardSegments
|
||||
.slice()
|
||||
.reverse()
|
||||
.find(segment => {
|
||||
return segment.type === 'tool_card' &&
|
||||
segment.data?.artifacts?.length > 0;
|
||||
});
|
||||
|
||||
if (latestWorkspaceCard && latestWorkspaceCard.type === 'tool_card' && onOpenWorkspace) {
|
||||
const currentWorkspaceData = latestWorkspaceCard.data;
|
||||
|
||||
// 检查当前workspace数据是否与上次相同
|
||||
if (!isWorkspaceDataEqual(lastWorkspaceDataRef.current, currentWorkspaceData)) {
|
||||
// 更新记录的workspace数据
|
||||
lastWorkspaceDataRef.current = currentWorkspaceData;
|
||||
|
||||
// 使用requestAnimationFrame确保在下一帧渲染后打开workspace
|
||||
const frameId = requestAnimationFrame(() => {
|
||||
openWorkspace(currentWorkspaceData);
|
||||
});
|
||||
|
||||
return () => cancelAnimationFrame(frameId);
|
||||
} else {
|
||||
console.log("latest workspace opened!", currentWorkspaceData, lastWorkspaceDataRef.current)
|
||||
}
|
||||
}
|
||||
}, [segments, onOpenWorkspace, openWorkspace, isLoading]);
|
||||
|
||||
// console.log('segments:', segments);
|
||||
return (
|
||||
<div className="card">
|
||||
{segments.map((segment, index) => {
|
||||
if (segment.type === 'text') {
|
||||
return (
|
||||
<div className="markdownbox" key={`text-${index}`}>
|
||||
<ReactMarkdown>{segment.content}</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
} else if (segment.type === 'tool_card') {
|
||||
const cardType = segment.data?.card_type;
|
||||
if (cardType === 'tool_call_card_link_list') {
|
||||
return <CardLinkList key={`tool-${index}`} sessionId={sessionId} data={segment.data} onOpenWorkspace={openWorkspace} />;
|
||||
} else {
|
||||
return <CardDefault key={`tool-${index}`} sessionId={sessionId} data={segment.data} onOpenWorkspace={openWorkspace} />;
|
||||
}
|
||||
}
|
||||
})}
|
||||
{/* 移除内部的Drawer */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BubbleItem;
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
export interface ToolCardData {
|
||||
tool_type: string;
|
||||
tool_name: string;
|
||||
function_name: string;
|
||||
tool_call_id: string;
|
||||
arguments: string;
|
||||
results: string;
|
||||
card_type: string;
|
||||
card_data: any;
|
||||
artifacts: any[];
|
||||
}
|
||||
|
||||
type ContentSegment =
|
||||
| { type: 'text'; content: string }
|
||||
| { type: 'tool_card'; data: ToolCardData; raw: string };
|
||||
|
||||
export interface ParsedContent {
|
||||
segments: ContentSegment[];
|
||||
}
|
||||
|
||||
export const extractToolCards = (content: string): ParsedContent => {
|
||||
const toolCardRegex = /(.*?)(```tool_card\s*({[\s\S]*?})\s*```)/gs;
|
||||
const segments: ContentSegment[] = [];
|
||||
let lastIndex = 0;
|
||||
|
||||
let match;
|
||||
while ((match = toolCardRegex.exec(content)) !== null) {
|
||||
const [, textBefore, fullToolCard, toolCardJson] = match;
|
||||
|
||||
// 添加文本内容
|
||||
if (textBefore) {
|
||||
segments.push({
|
||||
type: 'text',
|
||||
content: textBefore.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// 添加工具卡片
|
||||
try {
|
||||
segments.push({
|
||||
type: 'tool_card',
|
||||
data: JSON.parse(toolCardJson),
|
||||
raw: fullToolCard.trim()
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Failed to parse tool_card JSON:', e);
|
||||
// 如果解析失败,仍保留原始文本
|
||||
segments.push({
|
||||
type: 'text',
|
||||
content: fullToolCard.trim()
|
||||
});
|
||||
}
|
||||
|
||||
lastIndex = toolCardRegex.lastIndex;
|
||||
}
|
||||
|
||||
// 添加最后剩余的文本内容
|
||||
const remainingText = content.slice(lastIndex);
|
||||
if (remainingText.trim()) {
|
||||
segments.push({
|
||||
type: 'text',
|
||||
content: remainingText.trim()
|
||||
});
|
||||
}
|
||||
|
||||
return { segments };
|
||||
};
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
.tracebox {
|
||||
padding: 16px;
|
||||
|
||||
.mermaid {
|
||||
width: 80%;
|
||||
max-width: 700px;
|
||||
margin: 0 auto;
|
||||
text-align: center;
|
||||
}
|
||||
.trace-id{
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import React, { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import mermaid from 'mermaid';
|
||||
import { fetchTraceData } from '@/api/trace';
|
||||
import { treeToMermaid } from './mermaidUtils';
|
||||
import './index.less';
|
||||
|
||||
interface TraceProps {
|
||||
traceId?: string;
|
||||
drawerVisible?: boolean;
|
||||
}
|
||||
|
||||
const Trace: React.FC<TraceProps> = ({ traceId, drawerVisible }) => {
|
||||
const diagramRef = useRef<HTMLDivElement>(null);
|
||||
const [mermaidCode, setMermaidCode] = useState<string>('');
|
||||
const isFetching = useRef(false);
|
||||
|
||||
const renderError = (message: string) => {
|
||||
return `graph TD\n A[${message}]`;
|
||||
};
|
||||
|
||||
const handleFetchTrace = useCallback(async () => {
|
||||
if (!traceId || isFetching.current) return;
|
||||
isFetching.current = true;
|
||||
try {
|
||||
const result = await fetchTraceData(traceId);
|
||||
if (!result?.data) throw new Error('Invalid trace data format');
|
||||
|
||||
const mermaidData = treeToMermaid(result.data);
|
||||
if (!mermaidData.includes('graph') && !mermaidData.includes('flowchart')) {
|
||||
throw new Error(`Invalid mermaid data format`);
|
||||
}
|
||||
setMermaidCode(mermaidData);
|
||||
} catch (error) {
|
||||
console.error('Trace processing error:', error);
|
||||
setMermaidCode(renderError(error instanceof Error ? error.message : 'Data Processing Error'));
|
||||
} finally {
|
||||
isFetching.current = false;
|
||||
}
|
||||
}, [traceId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (traceId && drawerVisible) {
|
||||
handleFetchTrace();
|
||||
}
|
||||
return () => {
|
||||
// Cleanup if component unmounts during fetch
|
||||
};
|
||||
}, [traceId, drawerVisible, handleFetchTrace]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mermaidCode) return;
|
||||
|
||||
const renderMermaid = async () => {
|
||||
try {
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'loose'
|
||||
});
|
||||
|
||||
if (diagramRef.current) {
|
||||
diagramRef.current.innerHTML = mermaidCode;
|
||||
await mermaid.run({
|
||||
nodes: [diagramRef.current],
|
||||
suppressErrors: true
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Mermaid error:', error);
|
||||
setMermaidCode(renderError(error instanceof Error ? error.message : 'Rendering Error'));
|
||||
}
|
||||
};
|
||||
|
||||
renderMermaid();
|
||||
}, [mermaidCode]);
|
||||
|
||||
return (
|
||||
<div className="tracebox">
|
||||
<div ref={diagramRef} className="mermaid">
|
||||
{mermaidCode ||
|
||||
`graph TD
|
||||
A[loading...]`}
|
||||
</div>
|
||||
<p className='trace-id'>traceId: {traceId}</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Trace;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
interface TraceNode {
|
||||
show_name: string;
|
||||
span_id?: string;
|
||||
duration_ms?: number;
|
||||
children?: TraceNode[];
|
||||
}
|
||||
|
||||
export function treeToMermaid(input: any): string {
|
||||
let output = 'flowchart TD\n';
|
||||
const processedNodes = new Set<string>();
|
||||
|
||||
function processNode(node: TraceNode, parentId?: string) {
|
||||
if (!node?.show_name) return;
|
||||
|
||||
const rawNodeId = `${node.show_name}_${node.span_id || ''}`.replace(/\s+/g, '_');
|
||||
const cleanNodeId = rawNodeId.replace(/[^a-zA-Z0-9_]/g, '_');
|
||||
|
||||
if (!processedNodes.has(cleanNodeId)) {
|
||||
const cleanName = node.show_name
|
||||
.replace(/[^a-zA-Z0-9-\s\-_.,]/g, '')
|
||||
.trim();
|
||||
|
||||
output += ` ${cleanNodeId}["${cleanName}"]\n`;
|
||||
processedNodes.add(cleanNodeId);
|
||||
}
|
||||
|
||||
if (parentId) {
|
||||
const cleanParentId = parentId.replace(/[^a-zA-Z0-9_]/g, '_');
|
||||
const duration = node.duration_ms ? `${node.duration_ms.toFixed(2)}ms` : '';
|
||||
output += ` ${cleanParentId} -->|${duration}| ${cleanNodeId}\n`;
|
||||
}
|
||||
|
||||
if (node.children && node.children.length > 0) {
|
||||
node.children.forEach((child: TraceNode) => processNode(child, cleanNodeId));
|
||||
}
|
||||
}
|
||||
|
||||
if (!input) return output;
|
||||
|
||||
const rootNode: TraceNode = {
|
||||
show_name: 'Trace Root',
|
||||
span_id: 'root',
|
||||
children: [] as TraceNode[]
|
||||
};
|
||||
|
||||
if (input.data && Array.isArray(input.data)) {
|
||||
rootNode.children = input.data;
|
||||
} else if (Array.isArray(input)) {
|
||||
rootNode.children = input;
|
||||
} else {
|
||||
rootNode.children = [input];
|
||||
}
|
||||
|
||||
processNode(rootNode);
|
||||
|
||||
return output;
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import React, { useState, useMemo, useEffect, useCallback } from 'react';
|
||||
import { ThoughtChain } from '@ant-design/x';
|
||||
import type { ThoughtChainProps, ThoughtChainItem } from '@ant-design/x';
|
||||
import { Card, Typography, message } from 'antd';
|
||||
import { fetchTraceData } from '@/api/trace';
|
||||
|
||||
const { Paragraph } = Typography;
|
||||
|
||||
interface TraceProps {
|
||||
traceId?: string;
|
||||
drawerVisible?: boolean;
|
||||
}
|
||||
|
||||
type TraceNodeStatus = 'success' | 'pending' | 'error';
|
||||
|
||||
interface TraceNode {
|
||||
id: string;
|
||||
status?: TraceNodeStatus;
|
||||
show_name: string;
|
||||
children?: TraceNode[];
|
||||
description?: string;
|
||||
event_id: string;
|
||||
summary?: string;
|
||||
token_usage?: number;
|
||||
input_tokens?: number;
|
||||
output_tokens?: number;
|
||||
use_tools?: string[];
|
||||
}
|
||||
|
||||
const Trace: React.FC<TraceProps> = ({ traceId, drawerVisible }) => {
|
||||
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
|
||||
const [traceData, setTraceData] = useState<TraceNode[]>([]);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
if (!traceId || !drawerVisible) return;
|
||||
try {
|
||||
const res = await fetchTraceData(traceId);
|
||||
|
||||
const validateStatus = (status?: string): TraceNodeStatus | undefined => {
|
||||
return status === 'success' || status === 'pending' || status === 'error' ? (status as TraceNodeStatus) : undefined;
|
||||
};
|
||||
|
||||
const validatedData = (res.data || []).map((item: TraceNode) => ({
|
||||
...item,
|
||||
status: validateStatus(item.status)
|
||||
}));
|
||||
setTraceData(validatedData);
|
||||
// Expand the first node by default
|
||||
if (validatedData?.[0]?.event_id) {
|
||||
setExpandedKeys([validatedData[0].event_id]);
|
||||
}
|
||||
} catch (err) {
|
||||
message.error('Failed to fetch trace data');
|
||||
console.error(err);
|
||||
}
|
||||
}, [traceId, drawerVisible]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const renderNodeContent = useCallback(
|
||||
(node: TraceNode) => (
|
||||
<>
|
||||
{node.token_usage && <p>token_usage: {node.token_usage}</p>}
|
||||
{node.input_tokens && <p>input_tokens: {node.input_tokens}</p>}
|
||||
{node.output_tokens && <p>output_tokens: {node.output_tokens}</p>}
|
||||
{node.use_tools?.length && <p>use_tools: {node.use_tools.join(', ')}</p>}
|
||||
{node.summary && (
|
||||
<Typography>
|
||||
<Paragraph>
|
||||
<pre>{JSON.stringify(JSON.parse(node.summary), null, 2)}</pre>
|
||||
</Paragraph>
|
||||
</Typography>
|
||||
)}
|
||||
{node.children?.length ? <ThoughtChain items={convertToItems(node.children)} /> : null}
|
||||
</>
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
const convertToItems = useCallback(
|
||||
(nodes: TraceNode[]): ThoughtChainItem[] => {
|
||||
return nodes.map((node) => ({
|
||||
key: node.event_id,
|
||||
title: node.show_name,
|
||||
description: node.event_id,
|
||||
content: renderNodeContent(node),
|
||||
status: node.status || 'pending'
|
||||
}));
|
||||
},
|
||||
[renderNodeContent]
|
||||
);
|
||||
|
||||
const items = useMemo(() => convertToItems(traceData), [traceData, convertToItems]);
|
||||
|
||||
const collapsible: ThoughtChainProps['collapsible'] = useMemo(() => {
|
||||
return {
|
||||
expandedKeys,
|
||||
onExpand: (keys: string[]) => setExpandedKeys(keys)
|
||||
};
|
||||
}, [expandedKeys]);
|
||||
|
||||
return (
|
||||
<Card style={{ width: 650 }}>
|
||||
<ThoughtChain items={items} collapsible={collapsible} />
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default Trace;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import React from 'react';
|
||||
import { Tooltip, Typography } from 'antd';
|
||||
import { Position, Handle } from '@xyflow/react';
|
||||
import type { CustomNodeData } from './TraceXY.types';
|
||||
|
||||
interface CustomNodeProps {
|
||||
data: {
|
||||
data: CustomNodeData;
|
||||
};
|
||||
isFirst?: boolean;
|
||||
isLast?: boolean;
|
||||
}
|
||||
|
||||
const CustomNode: React.FC<CustomNodeProps> = ({ data, isFirst, isLast }) => {
|
||||
const nodeData: CustomNodeData = data || {};
|
||||
const summary = nodeData.summary
|
||||
? (typeof nodeData.summary === 'string'
|
||||
? JSON.parse(nodeData.summary).summary
|
||||
: nodeData.summary?.summary) || ''
|
||||
: '';
|
||||
const tooltipContent = nodeData.event_id ? (
|
||||
<div className="Tooltipbox">
|
||||
{summary.length > 100 ? summary : ''}
|
||||
<div>{nodeData.event_id}</div>
|
||||
</div>
|
||||
) : null;
|
||||
return (
|
||||
<Tooltip title={tooltipContent} placement="bottom" className="Tooltipbox">
|
||||
<div className="custom-node">
|
||||
<Typography.Paragraph className="summary" ellipsis={{ rows: 4 }}>
|
||||
{summary}
|
||||
</Typography.Paragraph>
|
||||
<div className="name">{nodeData.show_name || 'Unnamed Node'}</div>
|
||||
{!isFirst && (
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
/>
|
||||
)}
|
||||
{!isLast && (
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
id="bottom"
|
||||
/>
|
||||
)}
|
||||
{nodeData.sourceHandle?.includes('right') && (
|
||||
<Handle type="source" position={Position.Right} id="right" />
|
||||
)}
|
||||
{nodeData.sourceHandle?.includes('left') && (
|
||||
<Handle type="source" position={Position.Left} id="left" />
|
||||
)}
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
export default CustomNode;
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import type { Node, Edge } from '@xyflow/react';
|
||||
|
||||
export interface CustomNodeData {
|
||||
show_name?: string;
|
||||
event_id?: string;
|
||||
summary?: string | { summary: string };
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface NodeData extends Node {
|
||||
data: CustomNodeData;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface EdgeData extends Edge {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface TraceXYProps {
|
||||
traceId?: string;
|
||||
traceQuery?: string;
|
||||
drawerVisible?: boolean;
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
.traceXYbox {
|
||||
@box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
@border-radius: 8px;
|
||||
@transition: all 0.3s ease;
|
||||
@text-color: #222;
|
||||
@border-color: #d9d9d9;
|
||||
@light-bg: #f8f9fa;
|
||||
@node-bg: linear-gradient(135deg, #fff, #f8f8f8);
|
||||
@primary-color: #1890ff;
|
||||
|
||||
width: 80%;
|
||||
max-width: 700px;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
top: -20px;
|
||||
background: @light-bg;
|
||||
border-radius: @border-radius;
|
||||
box-shadow: @box-shadow;
|
||||
overflow: hidden;
|
||||
|
||||
|
||||
.react-flow__node {
|
||||
width: 300px;
|
||||
min-width: 14.5%;
|
||||
text-align: center;
|
||||
max-width: 30%;
|
||||
@node-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
|
||||
@node-hover-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
@node-selected-shadow: 0 0 0 2px fade(@primary-color, 20%);
|
||||
border: 1px solid @border-color;
|
||||
border-radius: @border-radius;
|
||||
// padding: 12px;
|
||||
background: @node-bg;
|
||||
box-shadow: @node-shadow;
|
||||
font-size: 10px;
|
||||
// transition: @transition;
|
||||
margin-bottom: 25px;
|
||||
|
||||
&:hover {
|
||||
box-shadow: @node-hover-shadow;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
&-selected {
|
||||
border-color: @primary-color;
|
||||
box-shadow: @node-selected-shadow;
|
||||
}
|
||||
.desc {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
.react-flow__handle{
|
||||
background-color: #ccc;
|
||||
}
|
||||
.react-flow__edge-path {
|
||||
stroke: #ddd;
|
||||
stroke-width: 2;
|
||||
animation: dashdraw 0.5s linear;
|
||||
}
|
||||
|
||||
|
||||
.react-flow__controls {
|
||||
box-shadow: @box-shadow;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.trace-id {
|
||||
position: absolute;
|
||||
bottom: 15px;
|
||||
right: 15px;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
padding: 6px 12px;
|
||||
border-radius: 20px;
|
||||
font-size: 10px;
|
||||
color: #666;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #eee;
|
||||
}
|
||||
|
||||
@keyframes dashdraw {
|
||||
from {
|
||||
stroke-dashoffset: 100;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// .ant-tooltip-content {
|
||||
// width: 420px;
|
||||
// }
|
||||
.Tooltipbox {
|
||||
padding: 5px 8px;
|
||||
.summary {
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
}
|
||||
pre {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
//edge click no changes
|
||||
.virtual-node-edge,
|
||||
.node-edge {
|
||||
&:hover,
|
||||
&-selected {
|
||||
box-shadow: none !important;
|
||||
transform: none !important;
|
||||
border-color: transparent !important;
|
||||
}
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
//virtual-node hidden handle
|
||||
// .react-flow__handle {
|
||||
// background-color: #999;
|
||||
// &.virtual-handle-target {
|
||||
// width: 0px;
|
||||
// height: 0px;
|
||||
// min-width: 0;
|
||||
// min-height: 0;
|
||||
// border: none;
|
||||
// }
|
||||
// }
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
ReactFlow,
|
||||
Background,
|
||||
Controls,
|
||||
ReactFlowProvider,
|
||||
applyNodeChanges
|
||||
} from '@xyflow/react';
|
||||
import type { NodeChange } from '@xyflow/react';
|
||||
import CustomNode from './CustomNode';
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import { fetchTraceData } from '@/api/trace';
|
||||
import { getLayoutedElements } from './layoutUtils';
|
||||
import './index.less';
|
||||
import type { TraceXYProps, NodeData, EdgeData } from './TraceXY.types';
|
||||
|
||||
const nodeTypes = {
|
||||
customNode: CustomNode
|
||||
};
|
||||
const TraceXY: React.FC<TraceXYProps> = ({ traceId, drawerVisible }) => {
|
||||
const [nodes, setNodes] = useState<NodeData[]>([]);
|
||||
const [edges, setEdges] = useState<EdgeData[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const onNodesChange = useCallback((changes: NodeChange[]) => {
|
||||
setNodes((nds) => {
|
||||
const updatedNodes = applyNodeChanges(changes, nds);
|
||||
return updatedNodes.map((node) => ({
|
||||
...node,
|
||||
type: node.type || 'customNode',
|
||||
data: (node as NodeData).data
|
||||
})) as NodeData[];
|
||||
});
|
||||
}, []);
|
||||
|
||||
const processNodes = useCallback((rawNodes: any[] = []): NodeData[] => {
|
||||
return rawNodes.map((node) => ({
|
||||
id: node.span_id || node.id || '',
|
||||
type: 'customNode',
|
||||
position: node.position || { x: 0, y: 0 },
|
||||
data: {
|
||||
...node.data,
|
||||
label: node.show_name,
|
||||
summary: node.summary || '',
|
||||
show_name: node.show_name,
|
||||
event_id: node.event_id
|
||||
}
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const processEdges = useCallback((rawEdges: any[] = []): EdgeData[] => {
|
||||
return rawEdges.map((edge) => ({
|
||||
id: `${edge.source}-${edge.target}`,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
className: 'node-edge',
|
||||
type: 'smoothstep'
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const loadAndLayoutElements = useCallback(async () => {
|
||||
if (!traceId || !drawerVisible) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await fetchTraceData(traceId);
|
||||
const nodesWithPosition = processNodes(result?.nodes || []);
|
||||
const edgesWithId = processEdges(result?.edges || []);
|
||||
|
||||
const { nodes: layoutedNodes, edges: layoutedEdges } = await getLayoutedElements(
|
||||
nodesWithPosition,
|
||||
edgesWithId
|
||||
);
|
||||
|
||||
setNodes(layoutedNodes);
|
||||
setEdges(layoutedEdges);
|
||||
} catch (err) {
|
||||
setError('Failed to load trace data, please try again later.');
|
||||
console.error('Failed to fetch and build trace elements:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [traceId, drawerVisible, processNodes, processEdges]);
|
||||
|
||||
useEffect(() => {
|
||||
loadAndLayoutElements();
|
||||
}, [loadAndLayoutElements]);
|
||||
|
||||
return (
|
||||
<div className="traceXYbox" style={{ height: '100%', width: '100%' }}>
|
||||
{loading && <div className="loading-indicator">Loading...</div>}
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
{!loading && !error && nodes.length === 0 && (
|
||||
<div className="empty-state">No trace data available</div>
|
||||
)}
|
||||
{nodes.length > 0 && (
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
nodesDraggable
|
||||
onNodesChange={onNodesChange}
|
||||
snapToGrid={true}
|
||||
snapGrid={[15, 15]}
|
||||
fitView
|
||||
minZoom={0.1}
|
||||
maxZoom={2}
|
||||
>
|
||||
<Background gap={16} />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const TraceXYWithProvider: React.FC<TraceXYProps> = (props) => (
|
||||
<ReactFlowProvider>
|
||||
<TraceXY {...props} />
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
|
||||
export default TraceXYWithProvider;
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import dagre from 'dagre';
|
||||
|
||||
const calculateEdgeLength = (
|
||||
sourcePos: { x: number; y: number },
|
||||
targetPos: { x: number; y: number }
|
||||
): number => Math.hypot(targetPos.x - sourcePos.x, targetPos.y - sourcePos.y);
|
||||
|
||||
export const getLayoutedElements = (nodes: any[], edges: any[]) => {
|
||||
const dagreGraph = new dagre.graphlib.Graph();
|
||||
dagreGraph.setDefaultEdgeLabel(() => ({}));
|
||||
dagreGraph.setGraph({
|
||||
rankdir: 'TB',
|
||||
nodesep: 50,
|
||||
ranksep: 50
|
||||
});
|
||||
|
||||
nodes.forEach((node) => {
|
||||
dagreGraph.setNode(node.id, { width: 200, height: 100 });
|
||||
});
|
||||
|
||||
edges.forEach((edge) => {
|
||||
dagreGraph.setEdge(edge.source, edge.target);
|
||||
});
|
||||
|
||||
dagre.layout(dagreGraph);
|
||||
|
||||
edges.forEach((edge) => {
|
||||
const sourceNode = nodes.find((n) => n.id === edge.source);
|
||||
const targetNode = nodes.find((n) => n.id === edge.target);
|
||||
if (!sourceNode || !targetNode) return;
|
||||
|
||||
const sourcePos = dagreGraph.node(edge.source);
|
||||
const targetPos = dagreGraph.node(edge.target);
|
||||
const length = calculateEdgeLength(sourcePos, targetPos);
|
||||
|
||||
if (length > 300) {
|
||||
const direction = targetPos.x > sourcePos.x ? 'right' : 'left';
|
||||
|
||||
sourceNode.data = sourceNode.data || {};
|
||||
sourceNode.data.sourceHandle = sourceNode.data.sourceHandle || [];
|
||||
|
||||
sourceNode.data.sourceHandle.push(direction);
|
||||
edge.sourceHandle = direction;
|
||||
}
|
||||
});
|
||||
|
||||
const updatedNodes = nodes.map((node) => {
|
||||
const position = dagreGraph.node(node.id);
|
||||
return {
|
||||
...node,
|
||||
position: {
|
||||
x: position.x - 100,
|
||||
y: position.y - 50
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
nodes: updatedNodes,
|
||||
edges: edges
|
||||
};
|
||||
};
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
.workspacebox {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
.btn {
|
||||
color: #555;
|
||||
height: 28px;
|
||||
background-color: #daffd5;
|
||||
border-radius: 10px;
|
||||
position: fixed;
|
||||
top: 14px;
|
||||
right: 380px;
|
||||
&:hover {
|
||||
color: #555 !important;
|
||||
border: 1px solid #daffd5 !important;
|
||||
background-color: #f6ffed !important;
|
||||
}
|
||||
}
|
||||
&.border,
|
||||
.border {
|
||||
border: 1px solid #c1c1c1;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.tabbox {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
margin-bottom: 12px;
|
||||
.num {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
text-align: center;
|
||||
line-height: 30px;
|
||||
border-radius: 50%;
|
||||
margin-right: 10px;
|
||||
background-color: #efefef;
|
||||
}
|
||||
.tab {
|
||||
width: 29%;
|
||||
padding: 5px 10px;
|
||||
cursor: pointer;
|
||||
&.active {
|
||||
.num {
|
||||
background-color: #c4efa6;
|
||||
color: #555;
|
||||
}
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: 14px;
|
||||
}
|
||||
.desc {
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
}
|
||||
}
|
||||
}
|
||||
.listwrap {
|
||||
background-color: #fafafa;
|
||||
.title {
|
||||
text-align: center;
|
||||
line-height: 40px;
|
||||
border-bottom: 1px solid #a7a7a7;
|
||||
}
|
||||
.listbox {
|
||||
.list {
|
||||
padding: 10px 14px;
|
||||
.name {
|
||||
font-size: 14px;
|
||||
margin-bottom: 3px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
&::before {
|
||||
display: inline-block;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
margin-right: 5px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid #999;
|
||||
background-color: #d8d8d8;
|
||||
}
|
||||
}
|
||||
.desc,
|
||||
.link {
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
}
|
||||
.desc {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
&:not(:last-child) {
|
||||
border-bottom: 1px solid #a7a7a7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import { getWorkspaceArtifacts } from '@/api/workspace';
|
||||
import { Image, Typography } from 'antd';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import type { ToolCardData } from '../../BubbleItem/utils';
|
||||
import './index.less';
|
||||
|
||||
interface ArtifactItem {
|
||||
snippet: string;
|
||||
link: string;
|
||||
key: string;
|
||||
title: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface WorkspaceProps {
|
||||
sessionId: string;
|
||||
toolCardData: ToolCardData;
|
||||
}
|
||||
|
||||
const Workspace: React.FC<WorkspaceProps> = ({ sessionId, toolCardData }) => {
|
||||
const [artifacts, setArtifacts] = useState<ArtifactItem[]>([]);
|
||||
const [imgUrl, setImgUrl] = useState<string | undefined>();
|
||||
const isLinkListCard = toolCardData?.card_type === 'tool_call_card_link_list';
|
||||
|
||||
// 用于缓存上次的请求参数,避免重复调用
|
||||
const lastRequestRef = useRef<{
|
||||
sessionId: string;
|
||||
artifactType: string;
|
||||
artifactId: string;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!toolCardData) return; // 如果没有 toolCardData,直接退出
|
||||
|
||||
const fetchWorkspaceArtifacts = async () => {
|
||||
try {
|
||||
const artifactType = toolCardData.artifacts?.[0]?.artifact_type;
|
||||
const artifactId = toolCardData.artifacts?.[0]?.artifact_id;
|
||||
|
||||
if (!artifactType || !artifactId) {
|
||||
console.warn('Invalid artifact data');
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否与上次请求参数相同
|
||||
const currentRequest = {
|
||||
sessionId,
|
||||
artifactType,
|
||||
artifactId
|
||||
};
|
||||
|
||||
if (lastRequestRef.current &&
|
||||
lastRequestRef.current.sessionId === currentRequest.sessionId &&
|
||||
lastRequestRef.current.artifactType === currentRequest.artifactType &&
|
||||
lastRequestRef.current.artifactId === currentRequest.artifactId) {
|
||||
// 参数相同,跳过重复请求
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新缓存的请求参数
|
||||
lastRequestRef.current = currentRequest;
|
||||
|
||||
const data = await getWorkspaceArtifacts(sessionId, {
|
||||
artifact_types: [artifactType],
|
||||
artifact_ids: [artifactId]
|
||||
});
|
||||
|
||||
const content = data?.data?.[0]?.content;
|
||||
|
||||
if (isLinkListCard) {
|
||||
setArtifacts(Array.isArray(content) ? content : []);
|
||||
} else {
|
||||
setImgUrl(content);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch workspace artifacts:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchWorkspaceArtifacts();
|
||||
}, [sessionId, toolCardData, isLinkListCard]);
|
||||
|
||||
const renderArtifactsList = () => (
|
||||
<div className="listbox">
|
||||
{artifacts.map((item, index) => (
|
||||
<div className="list" key={index}>
|
||||
<Typography.Link href={item?.link} target="_blank">
|
||||
<Typography.Paragraph className="name" ellipsis={{ rows: 1 }}>
|
||||
{item?.title}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Paragraph className="desc" ellipsis={{ rows: 3 }}>
|
||||
{item?.snippet}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Paragraph className="link" ellipsis={{ rows: 1 }}>
|
||||
{item?.link}
|
||||
</Typography.Paragraph>
|
||||
</Typography.Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderImage = () => <Image preview={false} src={imgUrl} alt="Workspace Artifact" />;
|
||||
|
||||
return (
|
||||
<div className="workspacebox">
|
||||
<div className="border listwrap">
|
||||
{isLinkListCard ? renderArtifactsList() : renderImage()}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Workspace;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
.chatPrompt{
|
||||
.ant-prompts-label {
|
||||
color: #000000e0 !important;
|
||||
}
|
||||
.ant-prompts-desc {
|
||||
color: #000000a6 !important;
|
||||
width: 100%;
|
||||
}
|
||||
.ant-prompts-icon {
|
||||
color: #000000a6 !important;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
Prompts as AntDesignPrompts,
|
||||
} from '@ant-design/x';
|
||||
|
||||
import './index.less';
|
||||
|
||||
interface IPromptsProps {
|
||||
items: any[];
|
||||
onItemClick: (item: any) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const Prompts = (props: IPromptsProps) => {
|
||||
const { items, onItemClick, className } = props;
|
||||
return (
|
||||
<AntDesignPrompts
|
||||
items={items}
|
||||
styles={{
|
||||
item: {
|
||||
flex: 1,
|
||||
backgroundImage: 'linear-gradient(123deg, #e5f4ff 0%, #efe7ff 100%)',
|
||||
borderRadius: 12,
|
||||
border: 'none',
|
||||
},
|
||||
subItem: { background: '#ffffffa6' },
|
||||
}}
|
||||
onItemClick={(info) => {
|
||||
onItemClick(info.data.description as string )
|
||||
}}
|
||||
className={className || "chatPrompt"}
|
||||
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default Prompts;
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
.welcome-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
background-color: #ffffff;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
bottom: 50px;
|
||||
}
|
||||
|
||||
.content {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.logo-title-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
|
||||
img {
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
.aworld-link {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: #1677ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.input-area {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.text-input {
|
||||
border-radius: 20px;
|
||||
padding: 12px 50px 50px 20px;
|
||||
border: 1px solid #d9d9d9;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.submit-button {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
bottom: 12px;
|
||||
width: 40px !important;
|
||||
height: 40px !important;
|
||||
background-color: #000000;
|
||||
border: none;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.submit-button:hover,
|
||||
.submit-button:focus {
|
||||
background-color: rgba(0, 0, 0, 0.7) !important;
|
||||
}
|
||||
|
||||
.submit-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
background-color: rgba(0, 0, 0, 0.1) !important;
|
||||
}
|
||||
|
||||
.submit-button:disabled:hover,
|
||||
.submit-button:disabled:focus {
|
||||
opacity: 0.5;
|
||||
background-color: rgba(0, 0, 0, 0.1) !important;
|
||||
}
|
||||
|
||||
.controls-area {
|
||||
width: 100%;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
|
||||
.model-select {
|
||||
width: 100%;
|
||||
// width: fit-content;
|
||||
height: 44px;
|
||||
border-radius: 50px;
|
||||
|
||||
.ant-select-selector {
|
||||
border-radius: 12px !important;
|
||||
padding-left: 12px !important;
|
||||
border: 1px solid #d9d9d9 !important;
|
||||
}
|
||||
|
||||
.ant-select-selection-item {
|
||||
padding-right: 24px !important;
|
||||
}
|
||||
|
||||
.ant-select-arrow {
|
||||
right: 15px;
|
||||
}
|
||||
}
|
||||
|
||||
.select-item {
|
||||
line-height: 30px;
|
||||
|
||||
small {
|
||||
margin-left: 10px;
|
||||
color: #b8b8b8;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.icon-right {
|
||||
color: #d9d9d9;
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { ArrowUpOutlined, RightOutlined } from '@ant-design/icons';
|
||||
import { Button, Col, Flex, Input, Row, Select, Typography } from 'antd';
|
||||
import React, { useState } from 'react';
|
||||
import logo from '../../../assets/aworld_logo.png';
|
||||
import './index.less';
|
||||
|
||||
const { Title } = Typography;
|
||||
|
||||
interface WelcomeProps {
|
||||
onSubmit: (value: string) => void;
|
||||
models: Array<{ label: string; value: string }>;
|
||||
selectedModel: string;
|
||||
onModelChange: (value: string) => void;
|
||||
modelsLoading: boolean;
|
||||
}
|
||||
|
||||
const Welcome: React.FC<WelcomeProps> = ({
|
||||
onSubmit,
|
||||
models,
|
||||
selectedModel,
|
||||
onModelChange,
|
||||
modelsLoading,
|
||||
}) => {
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (inputValue.trim()) onSubmit(inputValue);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="welcome-container">
|
||||
<div className="content">
|
||||
<Row justify="center">
|
||||
<Col>
|
||||
<div className="logo-title-container">
|
||||
<img src={logo} alt="AWorld Logo" width="46" height="46" />
|
||||
<Title level={1} style={{ margin: 0 }}>
|
||||
<a
|
||||
href="https://github.com/inclusionAI/AWorld"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="aworld-link"
|
||||
>
|
||||
Hello{' '}AWorld
|
||||
</a>
|
||||
</Title>
|
||||
</div>
|
||||
</Col>
|
||||
</Row>
|
||||
<div className="input-area">
|
||||
<Input.TextArea
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Ask or input / use skills"
|
||||
autoSize={{ minRows: 3, maxRows: 5 }}
|
||||
className="text-input"
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
shape="circle"
|
||||
onClick={() => {
|
||||
if (inputValue.trim()) onSubmit(inputValue);
|
||||
}}
|
||||
icon={<ArrowUpOutlined />}
|
||||
className="submit-button"
|
||||
disabled={inputValue.trim() === ''}
|
||||
/>
|
||||
</div>
|
||||
<div className="controls-area">
|
||||
<Select
|
||||
value={selectedModel}
|
||||
onChange={onModelChange}
|
||||
options={models}
|
||||
loading={modelsLoading}
|
||||
placeholder="Select a model"
|
||||
className="model-select"
|
||||
showSearch
|
||||
filterOption={(input, option) =>
|
||||
(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
optionRender={(option) => (
|
||||
<div className="select-item">
|
||||
<Flex justify="space-between">
|
||||
<div>
|
||||
<strong>{option.label}</strong>
|
||||
<small>{option.value}</small>
|
||||
</div>
|
||||
<RightOutlined className="icon-right" />
|
||||
</Flex>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Welcome;
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
.react-flow__node-customNode {
|
||||
border-radius: 6px;
|
||||
|
||||
.custom-node {
|
||||
// background: #fadddb;
|
||||
// border: 2px solid #E6A5AD;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
min-width: 200px;
|
||||
max-width: 360px;
|
||||
&-header {
|
||||
font-weight: bold;
|
||||
// color: #d58690;
|
||||
border-bottom: 1px solid #eee;
|
||||
padding-bottom: 5px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
&-content {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
.custom-node-io {
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Handle, Position, useNodes, useReactFlow } from '@xyflow/react';
|
||||
import type { Node, NodeProps } from '@xyflow/react';
|
||||
import { deleteNode } from '@/pages/xyflow/utils/nodeUtils';
|
||||
import { Tag, Drawer, Dropdown } from 'antd';
|
||||
import { EllipsisOutlined, DeleteOutlined, CopyOutlined } from '@ant-design/icons';
|
||||
import { NodeEditor } from '../NodeEditor';
|
||||
|
||||
interface NodeIOItem {
|
||||
id: string;
|
||||
label: string;
|
||||
type: 'string' | 'number' | 'boolean';
|
||||
defaultValue?: string;
|
||||
}
|
||||
|
||||
interface CustomNodeData
|
||||
extends Node<{
|
||||
id: string;
|
||||
label: string;
|
||||
content?: React.ReactNode;
|
||||
input?: NodeIOItem[];
|
||||
output?: NodeIOItem[];
|
||||
nodeType?: 'start' | 'end' | 'default';
|
||||
}> {}
|
||||
|
||||
interface CustomNodeProps extends NodeProps<CustomNodeData> {}
|
||||
|
||||
export const CustomNode: React.FC<CustomNodeProps> = ({ id, data }) => {
|
||||
const { label, content, input, output } = data;
|
||||
const nodes = useNodes();
|
||||
const reactFlowInstance = useReactFlow();
|
||||
const { setNodes } = reactFlowInstance;
|
||||
|
||||
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
|
||||
const [pendingData, setPendingData] = useState<Partial<CustomNodeData['data']>>({});
|
||||
const [editingData, setEditingData] = useState({
|
||||
content: typeof content === 'string' ? content : '',
|
||||
input: input || []
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
setEditingData({
|
||||
content: typeof content === 'string' ? content : '',
|
||||
input: input || []
|
||||
});
|
||||
}, [content, input]);
|
||||
|
||||
const handleNodeClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setIsDrawerOpen(true);
|
||||
};
|
||||
const handleDrawerClose = (e: React.MouseEvent | React.KeyboardEvent) => {
|
||||
if ('stopPropagation' in e) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
if (Object.keys(pendingData).length > 0) {
|
||||
setNodes((nds) =>
|
||||
nds.map((node) => {
|
||||
if (node.id === id) {
|
||||
return {
|
||||
...node,
|
||||
data: {
|
||||
...node.data,
|
||||
...pendingData
|
||||
}
|
||||
};
|
||||
}
|
||||
return node;
|
||||
})
|
||||
);
|
||||
}
|
||||
setIsDrawerOpen(false);
|
||||
};
|
||||
const renderIO = (title: string, items?: NodeIOItem[]) => {
|
||||
return (
|
||||
<div className="custom-node-io">
|
||||
<span>{title}:</span>
|
||||
{items?.map((item) => (
|
||||
<Tag key={item.label}>
|
||||
{item.type}.<strong>{item.label}</strong>
|
||||
</Tag>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="custom-node" onClick={handleNodeClick}>
|
||||
<div className="custom-node-header">
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
|
||||
<span>{label}</span>
|
||||
{data.nodeType !== 'start' && data.nodeType !== 'end' && (
|
||||
<Dropdown
|
||||
menu={{
|
||||
items: [
|
||||
{
|
||||
key: 'delete',
|
||||
label: '删除',
|
||||
icon: <DeleteOutlined />,
|
||||
onClick: (e) => {
|
||||
e.domEvent.stopPropagation();
|
||||
deleteNode(nodes, setNodes, id);
|
||||
}
|
||||
},
|
||||
{
|
||||
key: 'duplicate',
|
||||
label: '创建副本',
|
||||
icon: <CopyOutlined />,
|
||||
onClick: (e) => {
|
||||
e.domEvent.stopPropagation();
|
||||
alert('暂不支持');
|
||||
}
|
||||
}
|
||||
]
|
||||
}}
|
||||
trigger={['click']}
|
||||
>
|
||||
<EllipsisOutlined
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</Dropdown>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="custom-node-body">
|
||||
<div className="custom-node-content">
|
||||
<div>{editingData.content || 'Custom Node Content'}</div>
|
||||
{data.nodeType !== 'end' && renderIO('输入', input)}
|
||||
{data.nodeType !== 'start' && renderIO('输出', output)}
|
||||
</div>
|
||||
</div>
|
||||
{data.nodeType !== 'start' && <Handle type="target" position={Position.Left} />}
|
||||
{data.nodeType !== 'end' && <Handle type="source" position={Position.Right} />}
|
||||
<Drawer
|
||||
title={label}
|
||||
placement="right"
|
||||
closable={true}
|
||||
maskClosable={true}
|
||||
onClose={handleDrawerClose}
|
||||
open={isDrawerOpen}
|
||||
width={500}
|
||||
keyboard={true}
|
||||
>
|
||||
<NodeEditor
|
||||
node={{
|
||||
id,
|
||||
position: { x: 0, y: 0 },
|
||||
data: { ...data, ...editingData }
|
||||
}}
|
||||
onUpdate={(updatedNode) => {
|
||||
setPendingData((prev) => ({
|
||||
...prev,
|
||||
...updatedNode.data
|
||||
}));
|
||||
}}
|
||||
onClose={() => handleDrawerClose({ stopPropagation: () => {} } as React.MouseEvent)}
|
||||
/>
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { Controls, ControlButton } from '@xyflow/react';
|
||||
import { PlusOutlined, SaveOutlined, FolderOutlined, ReloadOutlined, GlobalOutlined, UndoOutlined, RedoOutlined } from '@ant-design/icons';
|
||||
import type { FC } from 'react';
|
||||
interface FlowControlsProps {
|
||||
isStraightLine: boolean;
|
||||
showMinimap: boolean;
|
||||
onToggleLine: () => void;
|
||||
onSave: () => void;
|
||||
onLoad: () => void;
|
||||
onAutoLayout: () => void;
|
||||
onToggleMinimap: () => void;
|
||||
onAddNode: () => void;
|
||||
onUndo: () => void;
|
||||
onRedo: () => void;
|
||||
}
|
||||
|
||||
export const FlowControls: FC<FlowControlsProps> = ({
|
||||
isStraightLine,
|
||||
showMinimap,
|
||||
onToggleLine,
|
||||
onSave,
|
||||
onLoad,
|
||||
onAutoLayout,
|
||||
onToggleMinimap,
|
||||
onAddNode,
|
||||
onUndo,
|
||||
onRedo
|
||||
}) => {
|
||||
return (
|
||||
<Controls style={{ left: '50%', transform: 'translateX(-50%)' }}>
|
||||
<ControlButton onClick={onToggleLine} title={isStraightLine ? 'Switch to curved line' : 'Switch to straight line'}>
|
||||
{isStraightLine ? '—' : '~'}
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onSave} title="Save flowchart">
|
||||
<SaveOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onLoad} title="Load flowchart">
|
||||
<FolderOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onAutoLayout} title="Auto Layout">
|
||||
<ReloadOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onUndo} title="Undo">
|
||||
<UndoOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onRedo} title="Redo">
|
||||
<RedoOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onToggleMinimap} title={showMinimap ? 'Hide minimap' : 'Show minimap'}>
|
||||
<GlobalOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onAddNode} title="Add Node">
|
||||
<PlusOutlined />
|
||||
</ControlButton>
|
||||
</Controls>
|
||||
);
|
||||
};
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
.node-editor {
|
||||
&-content {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
&-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
&-collapse {
|
||||
margin-top: 16px;
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
import React, { useCallback, useMemo } from 'react';
|
||||
import { Button, Input, Table, Select, Collapse } from 'antd';
|
||||
import type { ColumnType } from 'antd/es/table';
|
||||
import './index.less';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import type { Node } from '@xyflow/react';
|
||||
|
||||
const { Option } = Select;
|
||||
|
||||
interface NodeIOItem {
|
||||
id: string;
|
||||
label: string;
|
||||
type: 'string' | 'number' | 'boolean';
|
||||
defaultValue?: string;
|
||||
}
|
||||
|
||||
interface NodeEditorProps {
|
||||
node: Node<{
|
||||
id: string;
|
||||
label: string;
|
||||
content?: React.ReactNode;
|
||||
input?: NodeIOItem[];
|
||||
output?: NodeIOItem[];
|
||||
}>;
|
||||
onUpdate: (node: Node) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export const NodeEditor: React.FC<NodeEditorProps> = ({ node, onUpdate }) => {
|
||||
const [editingContent, setEditingContent] = React.useState(
|
||||
typeof node.data.content === 'string' ? node.data.content : ''
|
||||
);
|
||||
const [editingInputs, setEditingInputs] = React.useState<NodeIOItem[]>(node.data.input || []);
|
||||
|
||||
React.useEffect(() => {
|
||||
setEditingContent(typeof node.data.content === 'string' ? node.data.content : '');
|
||||
setEditingInputs(node.data.input || []);
|
||||
}, [node.data.content, node.data.input]);
|
||||
|
||||
const handleUpdate = useCallback(
|
||||
(newData: Partial<typeof node.data>) => {
|
||||
onUpdate({
|
||||
...node,
|
||||
data: {
|
||||
...node.data,
|
||||
...newData
|
||||
}
|
||||
});
|
||||
},
|
||||
[node, onUpdate]
|
||||
);
|
||||
|
||||
const handleInputChange = useCallback(
|
||||
<K extends keyof NodeIOItem>(index: number, field: K, value: NodeIOItem[K]) => {
|
||||
const newInputs = [...editingInputs];
|
||||
newInputs[index][field] = value;
|
||||
setEditingInputs(newInputs);
|
||||
handleUpdate({ input: newInputs });
|
||||
},
|
||||
[editingInputs, handleUpdate]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>{editingContent}</div>
|
||||
|
||||
<Collapse defaultActiveKey={['input']} bordered={false} className="node-editor-collapse">
|
||||
<Collapse.Panel
|
||||
header="输入"
|
||||
key="input"
|
||||
extra={
|
||||
<Button
|
||||
className="node-editor-collapse-btn"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
const newInputs: NodeIOItem[] = [
|
||||
...editingInputs,
|
||||
{
|
||||
id: `input-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
label: '',
|
||||
type: 'string' as const,
|
||||
defaultValue: ''
|
||||
}
|
||||
];
|
||||
setEditingInputs(newInputs);
|
||||
handleUpdate({ input: newInputs });
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Table
|
||||
dataSource={editingInputs}
|
||||
rowKey={(record) => record.id}
|
||||
pagination={false}
|
||||
columns={useMemo<Array<ColumnType<NodeIOItem>>>(
|
||||
() => [
|
||||
{
|
||||
title: '变量名',
|
||||
dataIndex: 'label',
|
||||
render: (text: string, _: NodeIOItem, index: number) => (
|
||||
<Input
|
||||
key={index}
|
||||
value={text as 'string' | 'number' | 'boolean'}
|
||||
onChange={(e) => handleInputChange(index, 'label', e.target.value)}
|
||||
placeholder="Variable name"
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: '变量值',
|
||||
dataIndex: 'type',
|
||||
render: (text: string, _: NodeIOItem, index: number) => (
|
||||
<Select
|
||||
value={text as 'string' | 'number' | 'boolean'}
|
||||
style={{ width: '100%' }}
|
||||
onChange={(value: 'string' | 'number' | 'boolean') =>
|
||||
handleInputChange(index, 'type', value)
|
||||
}
|
||||
>
|
||||
<Option value="string">String</Option>
|
||||
<Option value="number">Number</Option>
|
||||
<Option value="boolean">Boolean</Option>
|
||||
</Select>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
dataIndex: 'defaultValue',
|
||||
render: (text: string | undefined, _record: NodeIOItem, index: number) => (
|
||||
<Input
|
||||
value={text}
|
||||
onChange={(e) => handleInputChange(index, 'defaultValue', e.target.value)}
|
||||
placeholder="Default value"
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
render: (_text, _record: NodeIOItem, index: number) => (
|
||||
<Button
|
||||
danger
|
||||
onClick={() => {
|
||||
const newInputs = editingInputs.filter((_, i) => i !== index);
|
||||
setEditingInputs(newInputs);
|
||||
handleUpdate({ input: newInputs });
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
],
|
||||
[handleInputChange, editingInputs, handleUpdate]
|
||||
)}
|
||||
/>
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
<Collapse defaultActiveKey={['output']} bordered={false} className="node-editor-collapse">
|
||||
<Collapse.Panel header="输出" key="output">
|
||||
<Input.TextArea
|
||||
value={editingContent || ''}
|
||||
onChange={(e) => {
|
||||
const newValue = e.target.value;
|
||||
setEditingContent(newValue);
|
||||
handleUpdate({ content: newValue });
|
||||
}}
|
||||
placeholder="Enter node content"
|
||||
autoSize={{ minRows: 3, maxRows: 10 }}
|
||||
/>
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Position } from '@xyflow/react';
|
||||
|
||||
export const initialNodes = [
|
||||
{
|
||||
id: '1',
|
||||
type: 'customNode',
|
||||
data: {
|
||||
label: 'Start Node',
|
||||
nodeType: 'start',
|
||||
content: '开始节点,用于设定工作流启动变量',
|
||||
input: [
|
||||
// { label: 'name', type: 'int' },
|
||||
// { label: 'age', type: 'Boolean' }
|
||||
]
|
||||
},
|
||||
position: { x: 0, y: 0 },
|
||||
style: { background: '#E8F8F5', border: '2px solid #1ABC9C', color: '#16A085' },
|
||||
sourcePosition: Position.Right,
|
||||
targetPosition: Position.Left
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
type: 'customNode',
|
||||
data: {
|
||||
label: 'End Node',
|
||||
nodeType: 'end',
|
||||
content: '结束节点,用于返回工作流运行结果',
|
||||
output: [
|
||||
// { label: 'name', type: 'int' },
|
||||
// { label: 'age', type: 'Boolean' }
|
||||
]
|
||||
},
|
||||
position: { x: 400, y: 0 },
|
||||
style: { background: '#FEF9E7', border: '2px solid #F7DC6F', color: '#D4AC0D' },
|
||||
sourcePosition: Position.Right,
|
||||
targetPosition: Position.Left
|
||||
}
|
||||
];
|
||||
export const initialEdges = [];
|
||||
@@ -0,0 +1,18 @@
|
||||
@import '@xyflow/react/dist/style.css';
|
||||
@import './components/CustomNode/index.less';
|
||||
|
||||
.react-flow__controls {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.react-flow__controls-button {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 6px;
|
||||
font-size: 16px;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import React, { useCallback, useState, useEffect, useRef } from 'react';
|
||||
import {
|
||||
ReactFlow,
|
||||
Background,
|
||||
MiniMap,
|
||||
useReactFlow,
|
||||
ReactFlowProvider,
|
||||
useNodesState,
|
||||
useEdgesState,
|
||||
} from '@xyflow/react';
|
||||
import type { Connection, Node, Edge } from '@xyflow/react';
|
||||
import { FlowControls } from './components/FlowControls';
|
||||
import { CustomNode } from './components/CustomNode/index';
|
||||
import { saveFlow, loadFlow } from './utils/flowStorageUtils';
|
||||
|
||||
import { initialNodes, initialEdges } from './constants';
|
||||
import { addNode } from './utils/nodeUtils';
|
||||
import { addEdge, deleteEdge, updateEdgeStyles } from './utils/edgeUtils';
|
||||
import { autoLayout } from './utils/layoutUtils';
|
||||
import { addHistory, onUndo, onRedo, initHistory, getCurrentHistory } from './utils/historyUtils';
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import './index.less';
|
||||
|
||||
const nodeTypes = {
|
||||
customNode: CustomNode,
|
||||
};
|
||||
|
||||
function FlowChart() {
|
||||
const [nodes, setNodes, onNodesChange] = useNodesState<Node>(initialNodes);
|
||||
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>(initialEdges);
|
||||
const [showMinimap, setShowMinimap] = useState(false);
|
||||
const [isStraightLine, setIsStraightLine] = useState(false);
|
||||
|
||||
// 初始化历史记录
|
||||
useEffect(() => {
|
||||
initHistory(nodes, edges);
|
||||
}, []);
|
||||
|
||||
const reactFlowInstance = useReactFlow();
|
||||
|
||||
const handleAddNode = useCallback(() => {
|
||||
addNode(nodes, (newNodes) => {
|
||||
setNodes(newNodes);
|
||||
});
|
||||
}, [nodes]);
|
||||
|
||||
const handleConnect = useCallback(
|
||||
(params: Connection) => {
|
||||
setEdges(addEdge(edges, params.source, params.target));
|
||||
},
|
||||
[edges]
|
||||
);
|
||||
|
||||
const handleAutoLayout = useCallback(() => {
|
||||
autoLayout(nodes, edges, setNodes, reactFlowInstance);
|
||||
}, [nodes, edges, setNodes, reactFlowInstance]);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
saveFlow(nodes, edges);
|
||||
}, [nodes, edges]);
|
||||
|
||||
const handleLoad = useCallback(() => {
|
||||
loadFlow(setNodes, setEdges);
|
||||
// 加载后重置历史记录
|
||||
setTimeout(() => {
|
||||
initHistory(nodes, edges);
|
||||
}, 0);
|
||||
}, [setNodes, setEdges, nodes, edges]);
|
||||
|
||||
const handleDeleteEdge = useCallback(
|
||||
(edgeId: string) => {
|
||||
setEdges(deleteEdge(edges, edgeId));
|
||||
},
|
||||
[edges, setEdges]
|
||||
);
|
||||
|
||||
// 自动保存历史记录(带严格防抖)
|
||||
const prevNodesRef = useRef<Node[]>([]);
|
||||
const prevEdgesRef = useRef<Edge[]>([]);
|
||||
useEffect(() => {
|
||||
const nodesChanged = JSON.stringify(prevNodesRef.current) !== JSON.stringify(nodes);
|
||||
const edgesChanged = JSON.stringify(prevEdgesRef.current) !== JSON.stringify(edges);
|
||||
|
||||
if (nodesChanged || edgesChanged) {
|
||||
const currentHistory = getCurrentHistory();
|
||||
if (
|
||||
(nodes.length > 0 || edges.length > 0) &&
|
||||
(!currentHistory ||
|
||||
JSON.stringify(currentHistory.nodes) !== JSON.stringify(nodes) ||
|
||||
JSON.stringify(currentHistory.edges) !== JSON.stringify(edges))
|
||||
) {
|
||||
addHistory(nodes, edges);
|
||||
}
|
||||
prevNodesRef.current = nodes;
|
||||
prevEdgesRef.current = edges;
|
||||
}
|
||||
}, [nodes, edges]);
|
||||
|
||||
const updatedEdges = updateEdgeStyles(edges, isStraightLine).map((edge) => ({
|
||||
...edge,
|
||||
label:
|
||||
edge.label &&
|
||||
React.cloneElement(edge.label as React.ReactElement, {
|
||||
onClick: (e: React.MouseEvent) => {
|
||||
(edge.label as React.ReactElement)?.props?.onClick?.(e);
|
||||
handleDeleteEdge(edge.id);
|
||||
},
|
||||
}),
|
||||
}));
|
||||
return (
|
||||
<div style={{ width: '100%', height: '100vh' }}>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={updatedEdges}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
onConnect={handleConnect}
|
||||
fitView
|
||||
nodesDraggable
|
||||
edgesFocusable
|
||||
panOnScroll
|
||||
nodeTypes={nodeTypes}
|
||||
>
|
||||
<Background />
|
||||
{showMinimap && <MiniMap />}
|
||||
<FlowControls
|
||||
isStraightLine={isStraightLine}
|
||||
showMinimap={showMinimap}
|
||||
onToggleLine={() => setIsStraightLine(!isStraightLine)}
|
||||
onSave={handleSave}
|
||||
onLoad={handleLoad}
|
||||
onAutoLayout={handleAutoLayout}
|
||||
onToggleMinimap={() => setShowMinimap(!showMinimap)}
|
||||
onAddNode={handleAddNode}
|
||||
onUndo={() => {
|
||||
const state = onUndo();
|
||||
if (state) {
|
||||
// 使用函数式更新确保立即应用状态
|
||||
setNodes(() => state.nodes);
|
||||
setEdges(() => state.edges);
|
||||
}
|
||||
}}
|
||||
onRedo={() => {
|
||||
const state = onRedo();
|
||||
if (state) {
|
||||
setNodes(state.nodes);
|
||||
setEdges(state.edges);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</ReactFlow>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function () {
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<FlowChart />
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import type { Edge } from '@xyflow/react';
|
||||
import { MarkerType } from '@xyflow/react';
|
||||
/**
|
||||
* Edge operation functions
|
||||
* adding、deleting
|
||||
*/
|
||||
export const addEdge = (edges: Edge[], source: string, target: string): Edge[] => {
|
||||
const newEdge = {
|
||||
id: `${source}-${target}-${Date.now()}`,
|
||||
source,
|
||||
target
|
||||
};
|
||||
|
||||
return [...edges, newEdge];
|
||||
};
|
||||
|
||||
export const deleteEdge = (edges: Edge[], edgeId: string): Edge[] => {
|
||||
return edges.filter((edge) => edge.id !== edgeId);
|
||||
};
|
||||
|
||||
export const updateEdgeStyles = (edges: Edge[], isStraightLine: boolean): Edge[] => {
|
||||
return edges.map((edge) => ({
|
||||
...edge,
|
||||
type: isStraightLine ? 'straight' : 'default',
|
||||
markerEnd: { type: MarkerType.ArrowClosed },
|
||||
style: {
|
||||
...edge.style,
|
||||
strokeWidth: 2,
|
||||
...(isStraightLine ? { stroke: '#b1b1b7', strokeDasharray: '0' } : {})
|
||||
}
|
||||
}));
|
||||
};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import type { Node, Edge } from '@xyflow/react';
|
||||
import { message } from 'antd';
|
||||
|
||||
export const saveFlow = (nodes: Node[], edges: Edge[]) => {
|
||||
const flowData = JSON.stringify({ nodes, edges });
|
||||
localStorage.setItem('flow-data', flowData);
|
||||
message.success('The flowchart layout has been saved!');
|
||||
};
|
||||
|
||||
export const loadFlow = (setNodes: (nodes: Node[]) => void, setEdges: (edges: Edge[]) => void) => {
|
||||
const flowData = localStorage.getItem('flow-data');
|
||||
if (flowData) {
|
||||
const { nodes, edges } = JSON.parse(flowData);
|
||||
setNodes(nodes);
|
||||
setEdges(edges);
|
||||
message.success('The flowchart layout has been loaded!');
|
||||
} else {
|
||||
message.info('No saved flowchart layout!');
|
||||
}
|
||||
};
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import type { Node, Edge } from '@xyflow/react';
|
||||
|
||||
// 流程图状态类型
|
||||
type FlowState = {
|
||||
nodes: Node[];
|
||||
edges: Edge[];
|
||||
};
|
||||
|
||||
// 操作历史栈
|
||||
let historyStack: FlowState[] = [];
|
||||
let currentIndex = -1;
|
||||
let isUndoRedoInProgress = false;
|
||||
|
||||
// 初始化历史记录
|
||||
export const initHistory = (nodes: Node[], edges: Edge[]) => {
|
||||
historyStack = [
|
||||
{
|
||||
nodes: JSON.parse(JSON.stringify(nodes)),
|
||||
edges: JSON.parse(JSON.stringify(edges))
|
||||
}
|
||||
];
|
||||
currentIndex = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* 添加新操作到历史记录
|
||||
*/
|
||||
export const addHistory = (nodes: Node[], edges: Edge[]) => {
|
||||
console.log('addHistory添加记录')
|
||||
if (isUndoRedoInProgress) {
|
||||
isUndoRedoInProgress = false;
|
||||
return;
|
||||
}
|
||||
const newState = {
|
||||
nodes: JSON.parse(JSON.stringify(nodes)),
|
||||
edges: JSON.parse(JSON.stringify(edges))
|
||||
};
|
||||
|
||||
// 更严格的状态变化检测
|
||||
const prevState = currentIndex >= 0 ? historyStack[currentIndex] : null;
|
||||
if (prevState && prevState.nodes.length === newState.nodes.length && prevState.edges.length === newState.edges.length && JSON.stringify(prevState.nodes) === JSON.stringify(newState.nodes) && JSON.stringify(prevState.edges) === JSON.stringify(newState.edges)) {
|
||||
console.log('[History] 状态未变化,跳过保存');
|
||||
return;
|
||||
}
|
||||
|
||||
// 清除当前索引之后的操作(如果有重做操作未执行)
|
||||
const removedCount = historyStack.length - (currentIndex + 1);
|
||||
historyStack.splice(currentIndex + 1);
|
||||
historyStack.push(newState);
|
||||
currentIndex = historyStack.length - 1;
|
||||
|
||||
console.log(`[History] 新增,currentIndex=${currentIndex}, 节点数=${nodes.length}, 边数=${edges.length}, 移除记录=${removedCount}, 调用栈:`);
|
||||
};
|
||||
|
||||
/**
|
||||
* 撤销操作
|
||||
*/
|
||||
export const onUndo = (): FlowState | null => {
|
||||
if (currentIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
isUndoRedoInProgress = true;
|
||||
const prevIndex = currentIndex - 1;
|
||||
const prevState = historyStack[prevIndex];
|
||||
|
||||
currentIndex = prevIndex;
|
||||
return {
|
||||
nodes: [...prevState.nodes],
|
||||
edges: [...prevState.edges]
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 重做操作
|
||||
*/
|
||||
export const onRedo = (): FlowState | null => {
|
||||
if (currentIndex >= historyStack.length - 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
isUndoRedoInProgress = true;
|
||||
currentIndex++;
|
||||
const nextState = historyStack[currentIndex];
|
||||
|
||||
return nextState;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取当前历史状态
|
||||
*/
|
||||
export const getCurrentHistory = (): FlowState | null => {
|
||||
if (currentIndex < 0) return null;
|
||||
return historyStack[currentIndex];
|
||||
};
|
||||
|
||||
/**
|
||||
* 清除历史记录
|
||||
*/
|
||||
export const clearHistory = () => {
|
||||
historyStack.length = 0;
|
||||
currentIndex = -1;
|
||||
};
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Auto layout
|
||||
* use dagre library
|
||||
*/
|
||||
import type { Node, Edge } from '@xyflow/react';
|
||||
import type { useReactFlow } from '@xyflow/react';
|
||||
import dagre from 'dagre';
|
||||
|
||||
export const autoLayout = (
|
||||
nodes: Node[],
|
||||
edges: Edge[],
|
||||
setNodes: (nodes: Node[]) => void,
|
||||
reactFlowInstance: ReturnType<typeof useReactFlow>
|
||||
): void => {
|
||||
const dagreGraph = new dagre.graphlib.Graph();
|
||||
dagreGraph.setDefaultEdgeLabel(() => ({}));
|
||||
const nodeWidth = 200;
|
||||
const nodeHeight = 100;
|
||||
|
||||
dagreGraph.setGraph({
|
||||
rankdir: 'LR',
|
||||
nodesep: 50,
|
||||
ranksep: 100
|
||||
});
|
||||
|
||||
nodes.forEach((node) => {
|
||||
dagreGraph.setNode(node.id, {
|
||||
width: nodeWidth,
|
||||
height: nodeHeight
|
||||
});
|
||||
});
|
||||
|
||||
edges.forEach((edge) => {
|
||||
dagreGraph.setEdge(edge.source, edge.target);
|
||||
});
|
||||
|
||||
dagre.layout(dagreGraph);
|
||||
|
||||
const updatedNodes = nodes.map((node) => {
|
||||
const layoutNode = dagreGraph.node(node.id);
|
||||
return {
|
||||
...node,
|
||||
position: {
|
||||
x: layoutNode.x,
|
||||
y: layoutNode.y
|
||||
}
|
||||
};
|
||||
});
|
||||
setNodes(updatedNodes);
|
||||
console.log('auto:', updatedNodes);
|
||||
console.log('edges:', edges);
|
||||
setTimeout(() => {
|
||||
reactFlowInstance.fitView();
|
||||
}, 0);
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user