81 lines
2.3 KiB
Python
81 lines
2.3 KiB
Python
from flask import jsonify, request
|
|
from flask_jwt_extended import jwt_required
|
|
from . import api_bp
|
|
from ..models import Tool, AgentTool
|
|
from ..schemas import (
|
|
ToolSchema,
|
|
ToolCreateSchema,
|
|
AgentToolSchema,
|
|
AgentToolCreateSchema,
|
|
)
|
|
from ..services import ToolService
|
|
|
|
|
|
tool_schema = ToolSchema()
|
|
tool_create_schema = ToolCreateSchema()
|
|
agent_tool_schema = AgentToolSchema()
|
|
agent_tool_create_schema = AgentToolCreateSchema()
|
|
|
|
|
|
@api_bp.route("/tools", methods=["GET"])
|
|
@jwt_required()
|
|
def get_tools():
|
|
tools = Tool.query.all()
|
|
return jsonify(tool_schema.dump(tools, many=True))
|
|
|
|
|
|
@api_bp.route("/tools", methods=["POST"])
|
|
@jwt_required()
|
|
def create_tool():
|
|
data = request.get_json()
|
|
errors = tool_create_schema.validate(data)
|
|
if errors:
|
|
return jsonify({"error": errors}), 400
|
|
|
|
try:
|
|
tool = ToolService.create_tool(data)
|
|
return jsonify(tool_schema.dump(tool)), 201
|
|
except ValueError as e:
|
|
return jsonify({"error": str(e)}), 400
|
|
|
|
|
|
@api_bp.route("/tools/<int:tool_id>", methods=["GET"])
|
|
@jwt_required()
|
|
def get_tool(tool_id):
|
|
tool = Tool.query.get(tool_id)
|
|
if not tool:
|
|
return jsonify({"error": "工具不存在"}), 404
|
|
return jsonify(tool_schema.dump(tool))
|
|
|
|
|
|
@api_bp.route("/agents/<int:agent_id>/tools", methods=["GET"])
|
|
@jwt_required()
|
|
def get_agent_tools(agent_id):
|
|
agent_tools = AgentTool.query.filter_by(agent_id=agent_id).all()
|
|
return jsonify(agent_tool_schema.dump(agent_tools, many=True))
|
|
|
|
|
|
@api_bp.route("/agents/<int:agent_id>/tools", methods=["POST"])
|
|
@jwt_required()
|
|
def add_agent_tool(agent_id):
|
|
data = request.get_json()
|
|
errors = agent_tool_create_schema.validate(data)
|
|
if errors:
|
|
return jsonify({"error": errors}), 400
|
|
|
|
try:
|
|
agent_tool = ToolService.add_tool_to_agent(agent_id, data["tool_id"])
|
|
return jsonify(agent_tool_schema.dump(agent_tool)), 201
|
|
except ValueError as e:
|
|
return jsonify({"error": str(e)}), 400
|
|
|
|
|
|
@api_bp.route("/agents/<int:agent_id>/tools/<int:tool_id>", methods=["DELETE"])
|
|
@jwt_required()
|
|
def remove_agent_tool(agent_id, tool_id):
|
|
try:
|
|
ToolService.remove_tool_from_agent(agent_id, tool_id)
|
|
return jsonify({"message": "工具已移除"})
|
|
except ValueError as e:
|
|
return jsonify({"error": str(e)}), 400
|