liunux4odoo 42aa900566
优化工具定义;添加 openai 兼容的统一 chat 接口 (#3570)
- 修复:
    - Qwen Agent 的 OutputParser 不再抛出异常,遇到非 COT 文本直接返回
    - CallbackHandler 正确处理工具调用信息

- 重写 tool 定义方式:
    - 添加 regist_tool 简化 tool 定义:
        - 可以指定一个用户友好的名称
        - 自动将函数的 __doc__ 作为 tool.description
	- 支持用 Field 定义参数,不再需要额外定义 ModelSchema
        - 添加 BaseToolOutput 封装 tool	返回结果,以便同时获取原始值、给LLM的字符串值
        - 支持工具热加载(有待测试)

- 增加 openai 兼容的统一 chat 接口,通过 tools/tool_choice/extra_body 不同参数组合支持:
    - Agent 对话
    - 指定工具调用(如知识库RAG)
    - LLM 对话

- 根据后端功能更新 webui
2024-03-29 11:55:32 +08:00

42 lines
1.2 KiB
Python

from __future__ import annotations
from typing import List
from fastapi import APIRouter, Request, Body
from chatchat.configs import logger
from chatchat.server.utils import BaseResponse, get_tool, get_tool_config
tool_router = APIRouter(prefix="/tools", tags=["Toolkits"])
@tool_router.get("/", response_model=BaseResponse)
async def list_tools():
tools = get_tool()
data = {t.name: {
"name": t.name,
"title": t.title,
"description": t.description,
"args": t.args,
"config": get_tool_config(t.name),
} for t in tools.values()}
return {"data": data}
@tool_router.post("/call", response_model=BaseResponse)
async def call_tool(
name: str = Body(examples=["calculate"]),
tool_input: dict = Body({}, examples=[{"text": "3+5/2"}]),
):
if tool := get_tool(name):
try:
result = await tool.ainvoke(tool_input)
return {"data": result}
except Exception:
msg = f"failed to call tool '{name}'"
logger.error(msg, exc_info=True)
return {"code": 500, "msg": msg}
else:
return {"code": 500, "msg": f"no tool named '{name}'"}