LightAgent 0.4.2__tar.gz → 0.4.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {lightagent-0.4.2 → lightagent-0.4.4}/LightAgent/la_core.py +95 -68
- {lightagent-0.4.2 → lightagent-0.4.4}/PKG-INFO +286 -40
- {lightagent-0.4.2 → lightagent-0.4.4}/README.de.md +34 -5
- {lightagent-0.4.2 → lightagent-0.4.4}/README.es.md +34 -5
- {lightagent-0.4.2 → lightagent-0.4.4}/README.fr.md +34 -5
- {lightagent-0.4.2 → lightagent-0.4.4}/README.ja.md +34 -5
- {lightagent-0.4.2 → lightagent-0.4.4}/README.ko.md +34 -5
- {lightagent-0.4.2 → lightagent-0.4.4}/README.md +31 -5
- {lightagent-0.4.2 → lightagent-0.4.4}/README.pt.md +34 -5
- {lightagent-0.4.2 → lightagent-0.4.4}/README.ru.md +14 -0
- {lightagent-0.4.2 → lightagent-0.4.4}/README.zh-CN.md +43 -10
- {lightagent-0.4.2 → lightagent-0.4.4}/pyproject.toml +1 -1
- {lightagent-0.4.2 → lightagent-0.4.4}/LICENSE +0 -0
- {lightagent-0.4.2 → lightagent-0.4.4}/LightAgent/__init__.py +0 -0
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
|
|
4
4
|
"""
|
|
5
5
|
作者: [weego/WXAI-Team]
|
|
6
|
-
版本: 0.4.
|
|
7
|
-
最后更新: 2025-
|
|
6
|
+
版本: 0.4.4
|
|
7
|
+
最后更新: 2025-10-14
|
|
8
8
|
"""
|
|
9
9
|
|
|
10
10
|
import asyncio
|
|
@@ -30,7 +30,7 @@ from mcp.client.sse import sse_client
|
|
|
30
30
|
from mcp.client.stdio import stdio_client
|
|
31
31
|
from openai.types.chat import ChatCompletionChunk
|
|
32
32
|
|
|
33
|
-
__version__ = "0.4.
|
|
33
|
+
__version__ = "0.4.4" # 你可以根据需要设置版本号
|
|
34
34
|
|
|
35
35
|
|
|
36
36
|
# openai.langfuse_auth_check()
|
|
@@ -242,13 +242,14 @@ class LoggerManager:
|
|
|
242
242
|
|
|
243
243
|
trace_info = f"[TraceID: {self.traceid}] " if self.traceid else ""
|
|
244
244
|
log_message = f"{trace_info}{action}: {data}"
|
|
245
|
+
safe_msg = log_message.encode('utf-8', 'ignore').decode('utf-8')
|
|
245
246
|
|
|
246
247
|
if level == "DEBUG":
|
|
247
|
-
self.logger.debug(
|
|
248
|
+
self.logger.debug(safe_msg)
|
|
248
249
|
elif level == "INFO":
|
|
249
|
-
self.logger.info(
|
|
250
|
+
self.logger.info(safe_msg)
|
|
250
251
|
elif level == "ERROR":
|
|
251
|
-
self.logger.error(
|
|
252
|
+
self.logger.error(safe_msg)
|
|
252
253
|
|
|
253
254
|
def set_traceid(self, traceid: str):
|
|
254
255
|
"""设置当前跟踪ID"""
|
|
@@ -423,7 +424,7 @@ class MCPClientManager:
|
|
|
423
424
|
|
|
424
425
|
|
|
425
426
|
class LightAgent:
|
|
426
|
-
__version__ = "0.4.
|
|
427
|
+
__version__ = "0.4.4" # 将版本号放在类中
|
|
427
428
|
|
|
428
429
|
def __init__(
|
|
429
430
|
self,
|
|
@@ -605,12 +606,12 @@ class LightAgent:
|
|
|
605
606
|
try:
|
|
606
607
|
tool_func = self.tool_loader.load_tool(tool)
|
|
607
608
|
self.tool_registry.register_tool(tool_func)
|
|
608
|
-
self.
|
|
609
|
+
self.log("DEBUG", "load_tools", {"tool": tool, "status": "success"})
|
|
609
610
|
except Exception as e:
|
|
610
|
-
self.
|
|
611
|
+
self.log("ERROR", "load_tools", {"tool": tool, "error": str(e)})
|
|
611
612
|
elif callable(tool) and hasattr(tool, "tool_info"):
|
|
612
613
|
if self.tool_registry.register_tool(tool):
|
|
613
|
-
self.
|
|
614
|
+
self.log("DEBUG", "register_tool", {"tool": tool.__name__, "status": "success"})
|
|
614
615
|
|
|
615
616
|
async def setup_mcp(
|
|
616
617
|
self,
|
|
@@ -622,7 +623,15 @@ class LightAgent:
|
|
|
622
623
|
if self.mcp_setting and not self.mcp_client:
|
|
623
624
|
self.mcp_client = MCPClientManager(self.mcp_setting, self.tool_registry)
|
|
624
625
|
await self.mcp_client.register_mcp_tool()
|
|
625
|
-
self.
|
|
626
|
+
self.log("INFO", "setup_mcp", "MCP 模块初始化成功")
|
|
627
|
+
|
|
628
|
+
def log(self, level, action, data):
|
|
629
|
+
"""
|
|
630
|
+
日志打印入口
|
|
631
|
+
"""
|
|
632
|
+
if not self.debug:
|
|
633
|
+
return
|
|
634
|
+
self.logger.log(level, action, data)
|
|
626
635
|
|
|
627
636
|
def run(
|
|
628
637
|
self,
|
|
@@ -648,8 +657,9 @@ class LightAgent:
|
|
|
648
657
|
"""
|
|
649
658
|
# 设置跟踪ID
|
|
650
659
|
traceid = uuid4().hex
|
|
651
|
-
self.logger
|
|
652
|
-
|
|
660
|
+
if self.debug and hasattr(self, 'logger'): # 仅在 debug=True 且 logger 存在时记录日志
|
|
661
|
+
self.logger.set_traceid(traceid)
|
|
662
|
+
self.log("INFO", "run_start", {"query": query, "user_id": user_id, "stream": stream})
|
|
653
663
|
|
|
654
664
|
# 初始化历史记录
|
|
655
665
|
history = history or []
|
|
@@ -679,13 +689,17 @@ class LightAgent:
|
|
|
679
689
|
if self.tree_of_thought:
|
|
680
690
|
tot_response, active_tools = self.run_thought(query)
|
|
681
691
|
system_prompt += f"\n##以下是问题的补充说明\n{tot_response}"
|
|
682
|
-
self.
|
|
692
|
+
self.log("DEBUG", "tree_of_thought", {"response": tot_response, "active_tools": active_tools})
|
|
683
693
|
|
|
694
|
+
# 在用户查询后追加 "no_think"
|
|
695
|
+
# modified_query = query + "/no_think"
|
|
684
696
|
# 准备API参数
|
|
685
|
-
self.chat_params =
|
|
697
|
+
self.chat_params = {
|
|
686
698
|
"model": self.model,
|
|
687
|
-
"messages": [{"role": "system", "content": system_prompt}] + history + [
|
|
688
|
-
|
|
699
|
+
"messages": [{"role": "system", "content": system_prompt}] + history + [
|
|
700
|
+
{"role": "user", "content": query}],
|
|
701
|
+
"stream": stream,
|
|
702
|
+
"extra_body": {"enable_thinking": False}
|
|
689
703
|
}
|
|
690
704
|
|
|
691
705
|
# 添加参数
|
|
@@ -704,7 +718,7 @@ class LightAgent:
|
|
|
704
718
|
self.chat_params["session_id"] = traceid
|
|
705
719
|
|
|
706
720
|
# 调用模型
|
|
707
|
-
self.
|
|
721
|
+
self.log("DEBUG", "first_request_params", {"params": self.chat_params})
|
|
708
722
|
response = self.client.chat.completions.create(**self.chat_params)
|
|
709
723
|
return self._core_run_logic(response, stream, max_retry)
|
|
710
724
|
|
|
@@ -750,7 +764,7 @@ class LightAgent:
|
|
|
750
764
|
output = ""
|
|
751
765
|
function_call_name = ""
|
|
752
766
|
tool_calls = response.choices[0].message.tool_calls
|
|
753
|
-
self.
|
|
767
|
+
self.log("DEBUG", "non_stream tool_calls", {"tool_calls": tool_calls})
|
|
754
768
|
|
|
755
769
|
# 遍历所有工具调用
|
|
756
770
|
for tool_call in tool_calls:
|
|
@@ -758,7 +772,7 @@ class LightAgent:
|
|
|
758
772
|
|
|
759
773
|
# 尝试自动修复常见转义问题
|
|
760
774
|
fixed_args = function_call.arguments.replace('\\"', '"').replace('\\\\', '\\')
|
|
761
|
-
self.
|
|
775
|
+
self.log("DEBUG", "non_stream function_call", {"function_call": fixed_args})
|
|
762
776
|
|
|
763
777
|
# 解析函数参数
|
|
764
778
|
function_args = json.loads(fixed_args)
|
|
@@ -807,14 +821,14 @@ class LightAgent:
|
|
|
807
821
|
pass # 如果不是 JSON 字符串,保持原样
|
|
808
822
|
single_tool_response = combined_response # 处理单个工具的方法
|
|
809
823
|
|
|
810
|
-
self.
|
|
811
|
-
|
|
824
|
+
self.log("INFO", "non_stream single_tool_response",
|
|
825
|
+
{"single_tool_response": single_tool_response})
|
|
812
826
|
|
|
813
827
|
# 将单个工具的响应结果添加到列表中
|
|
814
828
|
tool_responses.append(single_tool_response)
|
|
815
829
|
|
|
816
830
|
# 将所有工具调用的结果合并为一个字符串
|
|
817
|
-
self.
|
|
831
|
+
self.log("DEBUG", "non_stream tool_responses", {"tool_responses": tool_responses})
|
|
818
832
|
|
|
819
833
|
combined_tool_response = "\n".join(tool_responses)
|
|
820
834
|
|
|
@@ -834,14 +848,14 @@ class LightAgent:
|
|
|
834
848
|
else:
|
|
835
849
|
# 返回最终回复
|
|
836
850
|
reply = response.choices[0].message.content
|
|
837
|
-
self.
|
|
851
|
+
self.log("INFO", "non_stream final_reply", {"reply": reply})
|
|
838
852
|
return reply
|
|
839
853
|
|
|
840
854
|
# 更新响应
|
|
841
855
|
if function_call_name == 'finish':
|
|
842
856
|
return # 如果最后调用了finish工具,则结束生成器
|
|
843
857
|
# print("params:",self.chat_params)
|
|
844
|
-
self.
|
|
858
|
+
self.log("DEBUG", "non_stream chat-completions params", {"params": self.chat_params})
|
|
845
859
|
|
|
846
860
|
try:
|
|
847
861
|
response = self.client.chat.completions.create(**self.chat_params)
|
|
@@ -849,7 +863,7 @@ class LightAgent:
|
|
|
849
863
|
print(f"An error occurred: {e}")
|
|
850
864
|
|
|
851
865
|
# 重试次数用尽
|
|
852
|
-
self.
|
|
866
|
+
self.log("ERROR", "max_retry_reached", {"message": "Failed to generate a valid response."})
|
|
853
867
|
return "Failed to generate a valid response."
|
|
854
868
|
|
|
855
869
|
def _run_stream_logic(self, response, max_retry) -> Generator[str, None, None]:
|
|
@@ -862,11 +876,24 @@ class LightAgent:
|
|
|
862
876
|
finish_called = False # 标记是否调用了finish工具
|
|
863
877
|
|
|
864
878
|
for chunk in response:
|
|
865
|
-
|
|
879
|
+
|
|
880
|
+
if chunk.choices and len(chunk.choices) > 0:
|
|
881
|
+
choice = chunk.choices[0]
|
|
882
|
+
|
|
883
|
+
if choice and hasattr(choice.delta, "reasoning_content") and choice.delta.reasoning_content is not None:
|
|
884
|
+
reasoning_content = choice.delta.reasoning_content or ""
|
|
885
|
+
|
|
886
|
+
if reasoning_content:
|
|
887
|
+
output += reasoning_content
|
|
888
|
+
|
|
889
|
+
if choice and hasattr(choice.delta, "content") and choice.delta.content is not None:
|
|
890
|
+
content = choice.delta.content or ""
|
|
891
|
+
|
|
866
892
|
if content:
|
|
867
|
-
yield chunk # 流式返回内容
|
|
868
893
|
output += content
|
|
869
894
|
|
|
895
|
+
yield chunk # 流式返回内容
|
|
896
|
+
|
|
870
897
|
try:
|
|
871
898
|
# 检查是否有工具调用
|
|
872
899
|
if chunk.choices and chunk.choices[0].delta.tool_calls:
|
|
@@ -889,7 +916,7 @@ class LightAgent:
|
|
|
889
916
|
tool_calls[tool_call_index]["arguments"] += tool_call_delta.function.arguments
|
|
890
917
|
|
|
891
918
|
except (IndexError, AttributeError, KeyError) as e:
|
|
892
|
-
self.
|
|
919
|
+
self.log("ERROR", "tool_call_error", {
|
|
893
920
|
"error": str(e),
|
|
894
921
|
"traceback": traceback.format_exc()
|
|
895
922
|
})
|
|
@@ -897,13 +924,13 @@ class LightAgent:
|
|
|
897
924
|
# 如果流式输出结束
|
|
898
925
|
finish_reason = chunk.choices[0].finish_reason if chunk.choices else None
|
|
899
926
|
if finish_reason == "stop" and not any(tc["name"] for tc in tool_calls):
|
|
900
|
-
self.
|
|
927
|
+
self.log("INFO", "stream_response", {"output": output})
|
|
901
928
|
return # 结束生成器
|
|
902
929
|
|
|
903
930
|
# 如果工具调用结束
|
|
904
931
|
elif finish_reason in ("tool_calls", "stop") and any(tc["name"] for tc in tool_calls):
|
|
905
932
|
# 遍历所有工具调用
|
|
906
|
-
self.
|
|
933
|
+
self.log("DEBUG", "stream tool_calls", {"tool_calls": tool_calls})
|
|
907
934
|
for tool_call in tool_calls:
|
|
908
935
|
if tool_call["name"]: # 确保工具调用有名称
|
|
909
936
|
tool_name = tool_call["name"]
|
|
@@ -922,7 +949,7 @@ class LightAgent:
|
|
|
922
949
|
"title": tool_title,
|
|
923
950
|
"arguments": arguments,
|
|
924
951
|
}
|
|
925
|
-
self.
|
|
952
|
+
self.log("INFO", "stream function_call", {"tool_call_start": tool_call_info})
|
|
926
953
|
# 将工具的调用信息推送给开发者
|
|
927
954
|
yield tool_call_info
|
|
928
955
|
|
|
@@ -940,7 +967,7 @@ class LightAgent:
|
|
|
940
967
|
for json_obj in json_objects:
|
|
941
968
|
# 尝试自动修复常见转义问题
|
|
942
969
|
fixed_args = json_obj.replace('\\"', '"').replace('\\\\', '\\')
|
|
943
|
-
self.
|
|
970
|
+
self.log("DEBUG", "stream fixed_args", {"fixed_args": fixed_args})
|
|
944
971
|
|
|
945
972
|
# 解析参数
|
|
946
973
|
function_args = json.loads(fixed_args)
|
|
@@ -965,8 +992,8 @@ class LightAgent:
|
|
|
965
992
|
"title": tool_title,
|
|
966
993
|
"output": chunk,
|
|
967
994
|
}
|
|
968
|
-
self.
|
|
969
|
-
|
|
995
|
+
self.log("DEBUG", "stream tool_output",
|
|
996
|
+
{"tool_output": tool_output})
|
|
970
997
|
yield tool_output
|
|
971
998
|
# 将工具的调用信息推送给开发者
|
|
972
999
|
if tool_name == 'finish':
|
|
@@ -987,8 +1014,8 @@ class LightAgent:
|
|
|
987
1014
|
yield tool_output
|
|
988
1015
|
|
|
989
1016
|
# 记录工具响应
|
|
990
|
-
self.
|
|
991
|
-
|
|
1017
|
+
self.log("INFO", "stream single_tool_response",
|
|
1018
|
+
{"single_tool_response": single_tool_response})
|
|
992
1019
|
|
|
993
1020
|
# 将单个工具的响应结果保存到列表中
|
|
994
1021
|
tool_responses.append(single_tool_response)
|
|
@@ -996,18 +1023,18 @@ class LightAgent:
|
|
|
996
1023
|
# 检查是否调用了finish工具
|
|
997
1024
|
if tool_name == 'finish':
|
|
998
1025
|
finish_called = True
|
|
999
|
-
self.
|
|
1026
|
+
self.log("INFO", "finish_tool_called", {"response": combined_response})
|
|
1000
1027
|
|
|
1001
1028
|
except json.JSONDecodeError as e:
|
|
1002
1029
|
error_msg = f"JSON解析错误: {str(e)}\n参数: {arguments}"
|
|
1003
|
-
self.
|
|
1004
|
-
|
|
1030
|
+
self.log("ERROR", "json_decode_error",
|
|
1031
|
+
{"tool": tool_name, "title": tool_title, "error": error_msg})
|
|
1005
1032
|
tool_responses.append(error_msg)
|
|
1006
1033
|
yield {"name": tool_name, "title": tool_title, "error": error_msg}
|
|
1007
1034
|
|
|
1008
1035
|
except Exception as e:
|
|
1009
1036
|
error_msg = f"工具调用错误: {str(e)}\n{traceback.format_exc()}"
|
|
1010
|
-
self.
|
|
1037
|
+
self.log("ERROR", "tool_execution_error", {
|
|
1011
1038
|
"tool": tool_name,
|
|
1012
1039
|
"title": tool_title,
|
|
1013
1040
|
"error": error_msg
|
|
@@ -1040,12 +1067,12 @@ class LightAgent:
|
|
|
1040
1067
|
)
|
|
1041
1068
|
|
|
1042
1069
|
# 创建新的响应流
|
|
1043
|
-
self.
|
|
1070
|
+
self.log("DEBUG", "stream next_request_params", {"params": self.chat_params})
|
|
1044
1071
|
response = self.client.chat.completions.create(**self.chat_params)
|
|
1045
1072
|
break
|
|
1046
1073
|
|
|
1047
1074
|
# 重试次数用尽
|
|
1048
|
-
self.
|
|
1075
|
+
self.log("ERROR", "max_retry_reached", {"message": "Failed to generate a valid response."})
|
|
1049
1076
|
yield "Failed to generate a valid response."
|
|
1050
1077
|
|
|
1051
1078
|
def _handle_task_transfer(
|
|
@@ -1065,9 +1092,9 @@ class LightAgent:
|
|
|
1065
1092
|
intent = self._detect_intent(query, light_swarm)
|
|
1066
1093
|
if intent and intent.get("transfer_to"):
|
|
1067
1094
|
target_agent_name = intent["transfer_to"]
|
|
1068
|
-
self.
|
|
1095
|
+
self.log("INFO", "detect_intent", {"intent": intent})
|
|
1069
1096
|
if target_agent_name == self.name:
|
|
1070
|
-
self.
|
|
1097
|
+
self.log("INFO", "self_transfer_detected", {"target_agent": target_agent_name})
|
|
1071
1098
|
return None # 如果是自身,直接返回 None
|
|
1072
1099
|
if stream:
|
|
1073
1100
|
return self._handle_task_transfer_stream(light_swarm.agents[target_agent_name], query, light_swarm)
|
|
@@ -1089,18 +1116,18 @@ class LightAgent:
|
|
|
1089
1116
|
:param light_swarm: LightSwarm 实例。
|
|
1090
1117
|
:return: 生成器,用于流式输出。
|
|
1091
1118
|
"""
|
|
1092
|
-
self.
|
|
1119
|
+
self.log("INFO", "transfer_to_agent", {"from": self.name, "to": target_agent.name, "context": context})
|
|
1093
1120
|
|
|
1094
1121
|
# 检查目标代理是否有效
|
|
1095
1122
|
if not hasattr(target_agent, 'run'):
|
|
1096
|
-
self.
|
|
1123
|
+
self.log("ERROR", "invalid_target_agent", {"target_agent": target_agent})
|
|
1097
1124
|
yield "Failed to transfer task: invalid target agent"
|
|
1098
1125
|
return
|
|
1099
1126
|
|
|
1100
1127
|
try:
|
|
1101
1128
|
yield from target_agent.run(context, light_swarm=light_swarm, stream=True)
|
|
1102
1129
|
except Exception as e:
|
|
1103
|
-
self.
|
|
1130
|
+
self.log("ERROR", "run_failed", {"error": str(e)})
|
|
1104
1131
|
raise # 重新抛出异常以便调试
|
|
1105
1132
|
|
|
1106
1133
|
def _handle_task_transfer_non_stream(
|
|
@@ -1117,11 +1144,11 @@ class LightAgent:
|
|
|
1117
1144
|
:param light_swarm: LightSwarm 实例。
|
|
1118
1145
|
:return: 字符串,表示非流式输出结果。
|
|
1119
1146
|
"""
|
|
1120
|
-
self.
|
|
1147
|
+
self.log("INFO", "transfer_to_agent", {"from": self.name, "to": target_agent.name, "context": context})
|
|
1121
1148
|
|
|
1122
1149
|
# 检查目标代理是否有效
|
|
1123
1150
|
if not hasattr(target_agent, 'run'):
|
|
1124
|
-
self.
|
|
1151
|
+
self.log("ERROR", "invalid_target_agent", {"target_agent": target_agent})
|
|
1125
1152
|
return "Failed to transfer task: invalid target agent"
|
|
1126
1153
|
|
|
1127
1154
|
try:
|
|
@@ -1130,7 +1157,7 @@ class LightAgent:
|
|
|
1130
1157
|
return "".join(result) # 将生成器转换为字符串
|
|
1131
1158
|
return result
|
|
1132
1159
|
except Exception as e:
|
|
1133
|
-
self.
|
|
1160
|
+
self.log("ERROR", "run_failed", {"error": str(e)})
|
|
1134
1161
|
raise # 重新抛出异常以便调试
|
|
1135
1162
|
|
|
1136
1163
|
def _build_context(self, related_memories):
|
|
@@ -1147,7 +1174,7 @@ class LightAgent:
|
|
|
1147
1174
|
return ""
|
|
1148
1175
|
|
|
1149
1176
|
prompt = f"\n##用户偏好 \n用户之前提到了\n{memory_context}。"
|
|
1150
|
-
self.
|
|
1177
|
+
self.log("DEBUG", "related_memories", {"memory_context": memory_context})
|
|
1151
1178
|
return prompt
|
|
1152
1179
|
|
|
1153
1180
|
def _build_agent_memory(self, agent_memories):
|
|
@@ -1165,7 +1192,7 @@ class LightAgent:
|
|
|
1165
1192
|
return ""
|
|
1166
1193
|
|
|
1167
1194
|
prompt = f"\n##以下是解决该问题的相关补充信息:\n{memory_context}。"
|
|
1168
|
-
self.
|
|
1195
|
+
self.log("DEBUG", "agent_memories", {"memory_context": memory_context})
|
|
1169
1196
|
return prompt
|
|
1170
1197
|
|
|
1171
1198
|
def run_thought(self, query: str) -> tuple:
|
|
@@ -1178,7 +1205,7 @@ class LightAgent:
|
|
|
1178
1205
|
current_date = now.strftime("%Y-%m-%d")
|
|
1179
1206
|
current_time = now.strftime("%H:%M:%S")
|
|
1180
1207
|
system_prompt = f"""你是一个智能助手,请根据用户输入的问题,结合工具使用计划,生成一个思维树,并按照思维树依次调用工具步骤,最终生成一个最终回答。\n 今日的日期: {current_date} 当前时间: {current_time} \n 工具列表: {tools}"""
|
|
1181
|
-
self.
|
|
1208
|
+
self.log("DEBUG", "run_thought", {"system_prompt": system_prompt})
|
|
1182
1209
|
|
|
1183
1210
|
try:
|
|
1184
1211
|
# 1. 第一次请求,生成初始的工具使用计划
|
|
@@ -1187,7 +1214,7 @@ class LightAgent:
|
|
|
1187
1214
|
stream=False)
|
|
1188
1215
|
response = self.tot_client.chat.completions.create(**params)
|
|
1189
1216
|
thought_response = response.choices[0].message.content
|
|
1190
|
-
self.
|
|
1217
|
+
self.log("DEBUG", "thought_response", {"response": thought_response})
|
|
1191
1218
|
|
|
1192
1219
|
# 2. 第二次请求,请求大模型反思并生成新的工具使用规划
|
|
1193
1220
|
reflection_prompt = "请反思你的回答,请严格按照<工具列表>中的工具来规划,不可以创造其他新的工具。请输出新的任务规划,不要输出其他分析和回答。"
|
|
@@ -1196,10 +1223,10 @@ class LightAgent:
|
|
|
1196
1223
|
{"role": "assistant", "content": thought_response},
|
|
1197
1224
|
{"role": "user", "content": reflection_prompt}
|
|
1198
1225
|
], stream=False)
|
|
1199
|
-
self.
|
|
1226
|
+
self.log("DEBUG", "reflection_params", {"params": reflection_params})
|
|
1200
1227
|
reflection_response = self.tot_client.chat.completions.create(**reflection_params)
|
|
1201
1228
|
refined_content = reflection_response.choices[0].message.content
|
|
1202
|
-
self.
|
|
1229
|
+
self.log("DEBUG", "reflection_response", {"response": refined_content})
|
|
1203
1230
|
|
|
1204
1231
|
# 获取工具的使用集合
|
|
1205
1232
|
tool_reflection_prompt = """请严格按以下要求执行:
|
|
@@ -1221,21 +1248,21 @@ class LightAgent:
|
|
|
1221
1248
|
stream=False
|
|
1222
1249
|
)
|
|
1223
1250
|
|
|
1224
|
-
self.
|
|
1251
|
+
self.log("DEBUG", "tool_reflection_params", {"params": tool_reflection_params})
|
|
1225
1252
|
tool_reflection_response = self.tot_client.chat.completions.create(**tool_reflection_params)
|
|
1226
1253
|
tool_reflection_result = tool_reflection_response.choices[0].message.content
|
|
1227
|
-
self.
|
|
1254
|
+
self.log("DEBUG", "tool_reflection_result", {"result": tool_reflection_result})
|
|
1228
1255
|
|
|
1229
1256
|
# 3.执行自适应工具过滤
|
|
1230
1257
|
current_tools = []
|
|
1231
1258
|
if self.filter_tools:
|
|
1232
1259
|
current_tools = self.tool_registry.filter_tools(tool_reflection_result)
|
|
1233
|
-
self.
|
|
1260
|
+
self.log("DEBUG", "current_tools", {"get_tools": current_tools})
|
|
1234
1261
|
|
|
1235
1262
|
return refined_content, current_tools
|
|
1236
1263
|
|
|
1237
1264
|
except Exception as e:
|
|
1238
|
-
self.
|
|
1265
|
+
self.log("ERROR", "run_thought_failure", {"error": str(e)})
|
|
1239
1266
|
raise RuntimeError(f"思维链执行失败: {str(e)}") from e
|
|
1240
1267
|
|
|
1241
1268
|
def _detect_intent(self, query: str, light_swarm=None) -> Optional[Dict]:
|
|
@@ -1272,7 +1299,7 @@ class LightAgent:
|
|
|
1272
1299
|
messages=[{"role": "system", "content": prompt}]
|
|
1273
1300
|
)
|
|
1274
1301
|
intent = response.choices[0].message.content
|
|
1275
|
-
self.
|
|
1302
|
+
self.log("DEBUG", "detect_intent", {"intent": intent})
|
|
1276
1303
|
|
|
1277
1304
|
# # 使用正则表达式解析意图
|
|
1278
1305
|
# match = re.search(r"transfer to (\w+)", intent, re.IGNORECASE)
|
|
@@ -1304,11 +1331,11 @@ class LightAgent:
|
|
|
1304
1331
|
:param stream: 是否启用流式输出。
|
|
1305
1332
|
:return: 如果 stream=True,返回生成器;否则返回完整结果字符串。
|
|
1306
1333
|
"""
|
|
1307
|
-
self.
|
|
1334
|
+
self.log("INFO", "transfer_to_agent", {"from": self.name, "to": target_agent.name, "context": context})
|
|
1308
1335
|
|
|
1309
1336
|
# 检查目标代理是否有效
|
|
1310
1337
|
if not hasattr(target_agent, 'run'):
|
|
1311
|
-
self.
|
|
1338
|
+
self.log("ERROR", "invalid_target_agent", {"target_agent": target_agent})
|
|
1312
1339
|
return "Failed to transfer task: invalid target agent"
|
|
1313
1340
|
#
|
|
1314
1341
|
# # 调用目标代理的 run 方法
|
|
@@ -1328,7 +1355,7 @@ class LightAgent:
|
|
|
1328
1355
|
return "".join(result) # 将生成器转换为字符串
|
|
1329
1356
|
return result
|
|
1330
1357
|
except Exception as e:
|
|
1331
|
-
self.
|
|
1358
|
+
self.log("ERROR", "run_failed", {"error": str(e)})
|
|
1332
1359
|
raise # 重新抛出异常以便调试
|
|
1333
1360
|
|
|
1334
1361
|
def create_tool(self, user_input: str, tools_directory: str = "tools"):
|
|
@@ -1405,19 +1432,19 @@ get_weather.tool_info = {
|
|
|
1405
1432
|
tool_code = tool_data.get("tool_code")
|
|
1406
1433
|
|
|
1407
1434
|
if not tool_name or not tool_code:
|
|
1408
|
-
self.
|
|
1435
|
+
self.log("ERROR", "invalid_tool_data", {"tool_data": tool_data})
|
|
1409
1436
|
continue
|
|
1410
1437
|
|
|
1411
1438
|
# 保存生成的代码到 tools 目录
|
|
1412
1439
|
tool_path = os.path.join(tools_directory, f"{tool_name}.py")
|
|
1413
1440
|
with open(tool_path, "w", encoding="utf-8") as f:
|
|
1414
1441
|
f.write(tool_code)
|
|
1415
|
-
self.
|
|
1442
|
+
self.log("INFO", "tool_created", {"tool_name": tool_name, "tool_path": tool_path})
|
|
1416
1443
|
|
|
1417
1444
|
# 自动加载新创建的工具
|
|
1418
1445
|
self.load_tools([tool_name], tools_directory)
|
|
1419
1446
|
except Exception as e:
|
|
1420
|
-
self.
|
|
1447
|
+
self.log("ERROR", "tool_creation_failed", {"error": str(e)})
|
|
1421
1448
|
|
|
1422
1449
|
|
|
1423
1450
|
class LightSwarm:
|