From API to AI Agent: Turning a Laravel Backend Into a Tool-Using System
说明与用途
将 Laravel 后端转变为面向工具的系统,通过暴露可调用的 Action 类、使用 PHP 属性生成工具模式、在工具内部执行授权检查并将执行任务放入队列,避免了昂贵的 HTTP 调用、数据泄露,并确保代理行为可靠。
问题
Exposing Laravel REST routes to an LLM creates expensive, unpredictable, and insecure agent behavior because agents interpret JSON schemas, not HTTP semantics, leading to token overuse, validation errors, and authorization bypasses.
结果
By shifting from HTTP routes to action‑centric tools, the team reduced token costs, eliminated validation errors, prevented PII leaks, and achieved a reliable, maintainable agent integration.
工作流
- 1. Stop exposing HTTP routes to the agent; expose invokable Action classes as tools.
- 2. Annotate Action classes and parameters with PHP 8 attributes (AgentTool, ToolParam).
- 3. Build a ToolRegistry that reflects on attributes to generate OpenAI/Anthropic JSON schemas.
- 4. Inject user context and enforce Laravel Gates/Policies inside each tool to prevent authorization bypass.
- 5. Structure tool outputs as strict JSON to keep context size small and avoid prompt injection.
- 6. Wrap tool execution in a retry‑safe loop and offload long‑running tasks to Laravel queues.
- 7. Add observability: log agent thoughts, tool calls, and outcomes for debugging.
证据
If you just expose your Laravel routes to an LLM, you aren't building an agent. You're building a very expensive, highly unpredictable curl client.
Decouple your business logic from your HTTP controllers and expose invokable Action classes as tools.
Inject the authorization context explicitly into the agent loop, and enforce Laravel Gates or Policies inside the tool execution boundary.
- 记录日期: 2026-09-11T04:46:40.784Z