mirror of
https://github.com/InvoiceShelf/InvoiceShelf.git
synced 2026-07-16 22:05:20 +00:00
Second phase of the AI feature. Users can now open a slide-in chat drawer from the SiteHeader and ask natural-language questions about their company's invoices, customers, payments, and expenses. The LLM invokes pre-defined read-only tool functions (scoped to the current company at execute time) to fetch data and synthesize answers.
**Database** — new ai_conversations and ai_messages tables. Messages are stored in OpenAI's chat format so AiAssistantService serializes a conversation into an API request with zero translation. Columns: role, content, tool_call_id, tool_calls JSON, model, tokens_in, tokens_out. Conversations are scoped (company_id, user_id) — one user's chats are invisible to everyone else, even inside the same company. Foreign-key cascade deletes.
**Tool infrastructure** — AiTool abstract base + AiToolRegistry singleton (registered in a new AiServiceProvider). The base class enforces the security rule: every tool's execute() receives companyId and userId as injected parameters; tools' JSON schemas NEVER include a company_id field. An LLM physically cannot pass a company_id and escape tenancy. Modules can register their own tools by resolving the registry from their own ServiceProvider::boot().
**Nine built-in tools**: search_invoices, get_invoice, search_customers, get_customer, list_recent_payments, list_overdue_invoices, get_company_stats (aggregates for named periods), search_items, list_expense_categories. All read-only; no mutations. Each returns JSON-encodable data the LLM can parse.
**AiAssistantService orchestration loop** — the heart of Phase 2. Flow: persist user message → build payload from system prompt + recent history (40-message window) + new user message → call driver.chatCompletion with tools → if tool_calls, execute each one via the registry (with injected scope), persist tool result, loop → if plain text, persist and return. Hard cap at 5 iterations to prevent runaway LLMs. System prompt pins the assistant to this company's data and forbids mutation.
**Controllers + policy + rate limit** — POST /api/v1/ai/chat runs the orchestration loop. GET/PATCH/DELETE /api/v1/ai/conversations for CRUD. AiConversationPolicy enforces user_id+company_id match on every action. A new 'ai' RateLimiter in RouteServiceProvider throttles to 30 req/min per (user, company). New 'use ai' Gate defined in AppServiceProvider returns true for any authenticated user — the per-company kill-switch still goes through AiConfigurationService::resolveForCompany.
**Frontend** — new features/company/ai/ folder with a Pinia store (ai-chat.store.ts) holding drawer state, current conversation, messages, and loading flags. AiChatDrawer.vue is a slide-in panel teleported to <body>, mounted globally in CompanyLayout.vue when bootstrap reports ai.enabled && ai.chat_enabled. Sub-components: AiChatMessage (user bubbles vs assistant bubbles), AiChatMessageInput (Enter submits, Shift+Enter newline), AiChatConversationList (sidebar with 'new chat' button, rename, delete). A SparklesIcon button in SiteHeader toggles the drawer.
**Driver test double** — tests use a ScriptedAiDriver registered via AiDriverFactory::register('scripted', ...) that returns pre-queued AiChatResponse objects. Feature tests cover: happy path (new conversation + message persistence), tool-call loop (multi-round-trip with search_invoices), runaway-loop cap, driver-throws path, ai_enabled=NO rejection, chat role disabled rejection, per-user conversation visibility, cross-user policy enforcement, cascade delete.
388 tests pass (was 372, +16 new). Pint clean. npm run build clean. Phase 3 (WYSIWYG text generation popup) is the remaining follow-up.
113 lines
4.2 KiB
PHP
113 lines
4.2 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Ai\Tools;
|
|
|
|
/**
|
|
* Abstract base class for read-only AI tools invokable by the chat assistant.
|
|
*
|
|
* Tools are what the LLM "calls" to fetch data when answering a user question.
|
|
* Every tool is a small, well-typed PHP function:
|
|
*
|
|
* - `name()` — snake_case identifier passed to the LLM
|
|
* - `description()` — one-sentence description; this is how the LLM decides
|
|
* when to invoke the tool. Write it like documentation, not marketing.
|
|
* - `parameterSchema()` — JSON schema for the parameters the LLM can pass.
|
|
* Must NEVER include a `company_id` field — scoping is injected at execute
|
|
* time from the caller's session. This is the v1 prompt-injection defense.
|
|
* - `execute()` — actually runs the query. Receives the resolved `$companyId`
|
|
* and `$userId` from the session, plus the arguments the LLM chose.
|
|
*
|
|
* Tools are **read-only** by contract. There is intentionally no mutation
|
|
* surface in v1 — the chat assistant cannot create, update, or delete
|
|
* anything, no matter what the LLM is told. Any attempt to add a mutation
|
|
* tool should go through a separate design review.
|
|
*/
|
|
abstract class AiTool
|
|
{
|
|
/** Stable identifier sent to the LLM. Use snake_case. */
|
|
abstract public function name(): string;
|
|
|
|
/**
|
|
* Natural-language description the LLM uses to decide when to call this tool.
|
|
*
|
|
* Keep it one sentence, written in imperative mood, describing what you get
|
|
* back. Good examples:
|
|
*
|
|
* - "Search invoices by customer, status, or free-text query."
|
|
* - "Fetch full details for a customer by ID, including their address and totals."
|
|
*
|
|
* Avoid marketing language and hedging. The LLM pays close attention to
|
|
* this string.
|
|
*/
|
|
abstract public function description(): string;
|
|
|
|
/**
|
|
* JSON schema for the arguments the LLM may pass.
|
|
*
|
|
* Shape matches OpenAI's function-calling parameters schema — an object
|
|
* with a `properties` map and a `required` array. Tools that take no
|
|
* arguments should return a bare `['type' => 'object', 'properties' => (object) []]`.
|
|
*
|
|
* Critical: do NOT include `company_id` or `user_id` in the schema.
|
|
* Scoping is the host's responsibility and is injected at execute time.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
abstract public function parameterSchema(): array;
|
|
|
|
/**
|
|
* Run the tool with the given arguments, scoped to the caller's session.
|
|
*
|
|
* Implementations MUST query within the given `$companyId` and never trust
|
|
* any company/user identifier the LLM tries to sneak into `$arguments`.
|
|
*
|
|
* @param array<string, mixed> $arguments Parsed from the LLM's tool_call JSON
|
|
* @param int $companyId Injected from the current session — authoritative
|
|
* @param int $userId Injected from the current session
|
|
* @return mixed Anything JSON-encodable; will be serialized and sent back to the LLM
|
|
*/
|
|
abstract public function execute(array $arguments, int $companyId, int $userId): mixed;
|
|
|
|
/**
|
|
* Convert this tool into an OpenAI-style tools array entry.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function toOpenAiToolSchema(): array
|
|
{
|
|
return [
|
|
'type' => 'function',
|
|
'function' => [
|
|
'name' => $this->name(),
|
|
'description' => $this->description(),
|
|
'parameters' => $this->parameterSchema(),
|
|
],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Normalize a model date field (which may be a string OR a Carbon instance
|
|
* depending on model casts) to a YYYY-MM-DD string for tool output.
|
|
*
|
|
* Many InvoiceShelf models store dates as raw strings; others cast to Carbon.
|
|
* Centralizing this avoids cast-guessing in every tool.
|
|
*/
|
|
protected function asDate(mixed $value): ?string
|
|
{
|
|
if ($value === null || $value === '') {
|
|
return null;
|
|
}
|
|
|
|
if (is_object($value) && method_exists($value, 'toDateString')) {
|
|
return $value->toDateString();
|
|
}
|
|
|
|
// String like '2026-04-11' or '2026-04-11 00:00:00' — keep the date part only.
|
|
if (is_string($value)) {
|
|
return substr($value, 0, 10);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|