Maplemx / Agently

[AI Agent Application Development Framework] - 🚀 Build AI agent native application in very few code 💬 Easy to interact with AI agent in code using structure data and chained-calls syntax 🧩 Enhance AI Agent using plugins instead of rebuild a whole new agent
http://agently.tech
Apache License 2.0
908 stars 100 forks source link

多agent error text {"error":{"code":"1214","message":"messages[4]:content和tool_calls 字段不能同时为空"}} #76

Closed ZohnSun closed 2 months ago

ZohnSun commented 2 months ago

我这里一共使用了三个agent:版本3.2.2.3

路由agent:判断用户意图,是否需要调用制度查询; 闲聊agent,就是一个正常的agent,做了一些配置 带有知识库向量查询的agent;

然后放在一个循环里面测试答案;基本 第一次:你好; 第二次:查XXXXX制度 第三次:我刚才问了什么问题, 每次到第三次就开始报错崩溃;

其中一段错误是: File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\zhipuai\core_http_client.py", line 251, in request raise self._make_status_error(err.response) from None zhipuai.core._errors.APIRequestFailedError: Error code: 400, with error text {"error":{"code":"1214","message":"messages[4]:content和tool_calls 字段不能同时为空"}}

正常第三次问题应该是先调用路由agent,是没用配置tool内容的,但这个错误让人很疑惑;

完整的错误信息: Exception in thread Thread-15: Traceback (most recent call last): File "D:\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "D:\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, self._kwargs) File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\Agently\Agent\Agent.py", line 232, in start_in_theard reply = loop.run_until_complete(self.start_async(request_type)) File "D:\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete return future.result() File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\Agently\Agent\Agent.py", line 220, in start_async raise(e) File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\Agently\Agent\Agent.py", line 173, in start_async event_generator = await self.request.get_event_generator(request_type) File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\Agently\Request\Request.py", line 116, in get_event_generator response_generator = await request_plugin_export"request_model" File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\Agently\plugins\request\ZhipuAI.py", line 193, in request_model return client.chat.completions.create(request_data) File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\zhipuai\api_resource\chat\completions.py", line 48, in create return self._post( File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\zhipuai\core_http_client.py", line 292, in post return self.request( File "D:\MyPythonCode\Agent_chat\venv\lib\site-packages\zhipuai\core_http_client.py", line 251, in request raise self._make_status_error(err.response) from None zhipuai.core._errors.APIRequestFailedError: Error code: 400, with error text {"error":{"code":"1214","message":"messages[4]:content和tool_calls 字段不能同时为空"}} Traceback (most recent call last): File "D:\MyPythonCode\Agent_chat\agent_llm\agent_role.py", line 192, in result=ai_response(question,history) File "D:\MyPythonCode\Agent_chat\agent_llm\agent_role.py", line 179, in ai_response if route_agent(question,history)=='制度流程查询': File "D:\MyPythonCode\Agent_chat\agent_llm\agent_role.py", line 18, in route_agent print('路由判断',route['intention']) TypeError: 'NoneType' object is not subscriptable

from agent_factory_api import agent_factory_zhipu
from agent_tool.milvus_tool import get_search_result

路由模型-对用户问题进行基础判断-分发至正确的其他agent
def route_agent(user_input,history):
route = (
agent_factory_zhipu.create_agent('rout')
.set_settings("model.ZhipuAI.options", {"model": "glm-4"})
.set_role("role", "你是一个路由助手,您的工作是结合上下文帮助用户找到合适的Agent代理来回答用户的问题")
.input(user_input)
.chat_history(history)
.output({
"intention": ("制度流程查询 | 绘图 | 闲聊 | 一般提问", "从'制度流程查询','绘图','闲聊','一般提问'中选择一项作为你对{user_input}的意图的判断结果")
}).start()
)
print('')
print(route)
print('')
print('路由判断',route['intention'])
return route['intention']

闲聊Agent
def get_agent_response_chatting(question:str,history):
agent_standard_senior = (
agent_factory_zhipu.create_agent('standard_role')
.set_settings("model.ZhipuAI.options", {"model": "glm-4"})

)
result=(
    # 全局配置
    agent_standard_senior.general("Output regulations", "根据提问方式匹配对应的输出语言,默认是中文")
    # 角色配置
    .role({
                "Name": "小智",
                "Task": "作为同事,根据上下文为用户解答问题,提供想法",
                "Position":'运营助理',
                "Model":'基于Transformer编码器-解码器架构的大语言模型'
            })
    # user_info: agent需要了解的用户相关的信息
    .user_info("The user you are talking to is a colleague of yours who is not very familiar with the system and issues. He needs your assistance in searching for information and answering questions")
    # abstract: 对于之前对话(尤其是较长对话)的总结信息
    .abstract(None)

    .chat_history(history)
    # input: 和本次请求相关的输入信息
    .input({
        "question": question
    })
    # info: 为本次请求提供的额外补充信息
    .info("用户的部门信息", ["", "", ""])
    .info("相关关键词", ["", ""])
    # instruct: 为本次请求提供的行动指导信息
    .instruct([
        "请使用{reply_style_expect}的回复风格,回复{question}提出的问题",
    ])
    # output: 对本次请求的输出提出格式和内容的要求
    .output({
        "reply": ("str", "对{question}的直接回复"),
        "next_questions": ([
            ("str",
             "根据{reply}内容,结合{user_info}提供的用户信息," +
             "给用户推荐的可以进一步提问的问题"
            )], "不少于3个"),
    })
    # start: 用于开始本次主要交互请求
    .start()
)
return result
制度流程查询Agent
def get_agent_response_processSystem(question,history):
def print_streaming_content(data: str):
print(data, end="")
tool_info = {
"tool_name": "流程制度查询工具",
"desc": "从知识库文档中查询公司流程及制度",
"args": {
"context": (
"str",
"要查询的相关制度流程内容,使用中文字符串"
)
},
"func": get_search_result
}
# 创建该生命周期智能体:考虑到文档查询用量,使用便宜的模型--穷啊
agent_standard_lower = (
agent_factory_zhipu.create_agent('knowledge_base_agent')
.set_settings("model.ZhipuAI.options", {"model": "glm-3-turbo"})

)
# doc=get_search_result(question)
result=(
    # 全局配置
    agent_standard_lower.general("Output regulations", "根据提问方式匹配对应的输出语言,默认是中文")
    # 工具配置
    .register_tool(
        tool_name=tool_info["tool_name"],
        desc=tool_info["desc"],
        args=tool_info["args"],
        func=tool_info["func"],
    )
    # 角色配置
    .role({
                "Name": "小智",
                "Task": "作为同事,根据上下文为用户查询流程制度和文档",
                "Position":'条理化总结制度文档的内容'
            })
    # user_info: agent需要了解的用户相关的信息
    .user_info("对公司制度流程不清楚,需要完整的了解其内容")
    # abstract: 对于之前对话(尤其是较长对话)的总结信息
    .abstract(None)
    # chat_history: 按照OpenAI消息列格式的对话记录list

    .chat_history(history)
    # input: 和本次请求相关的输入信息
    .input({
        "question": question,
    })

    # instruct: 为本次请求提供的行动指导信息
    .instruct([
        "请从{document_info}查询结果中找{question}的答案,条理化总结知识,同事告知文档来源Document_title",
    ])
    # output: 对本次请求的输出提出格式和内容的要求
    # .output({
    #     "reply": ("str", "请条目化的输出问题相关文档的内容,使用换行符分割"),
    #     "document_name": ([
    #         ("str",
    #          "流程制度文档中Document_title名称"
    #         )],)
    # })
    # start: 用于开始本次主要交互请求

     .on_delta(lambda data: print(data, end=""))
    .start()
)
return
def ai_response(question,history):
    if route_agent(question,history)=='制度流程查询':
        print('流程查询')
        return get_agent_response_processSystem(question,history)
    else:
        print('---')
        return get_agent_response_chatting(question,history)
if __name__ == '__main__':

    history=[]# { "role": "system", "content": "" }
    while True:
        question=input('请输入问题:')

        result=ai_response(question,history)
        history.append({"role": "user", "content": question})
        print('[ai:]')
        print(result)
        history.append({"role": "assistant", "content": result})
ZohnSun commented 2 months ago

我自己代码问题,通过DEBUG一步步发现,是自己的历史记录没有记录导致的