Prefill a Vue Form with Structured Output from a Laravel AI SDK Agent
Gentil Maliyamungu B. · 2026-11-15
Use a Laravel AI SDK structured output schema to draft form fields, validate them on the server, and merge them into a Vue form without overwriting user edits.
Not every AI feature needs to be a chat window. Often the most useful thing a model can do is fill in a form that a person then checks: a support ticket from a customer email, a product listing from a supplier description, an expense entry from a receipt.
In this tutorial a support agent pastes a customer message into a Vue form, clicks Draft with AI, and gets the subject, category, priority, order number, summary and a suggested reply filled in. The person stays in control:
- the model's output is validated on the server with the same rules as a human submission, and invalid fields are dropped, not shown;
- fields the person already typed in are never overwritten;
- AI-filled fields are marked until someone edits them;
- saving runs the same validation again, so a crafted request cannot skip it.
Tested with laravel/ai 1.4.0, Laravel 13.42, PHP 8.4 and Vue 3.5.
The agent and its schema
The Laravel AI SDK lets an agent return structured output by implementing HasStructuredOutput and describing the shape with Laravel's JSON schema builder:
php artisan make:agent TicketDraftAgent --structured
<?php
namespace App\Ai\Agents;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;
use Stringable;
class TicketDraftAgent implements Agent, HasStructuredOutput
{
use Promptable;
public const CATEGORIES = ['shipping', 'damaged_item', 'refund', 'other'];
public const PRIORITIES = ['low', 'normal', 'high'];
public function instructions(): Stringable|string
{
return <<<'TEXT'
You turn a customer's message into a draft support ticket for a small online shop.
Write the subject and summary in plain English, without inventing facts.
Only fill order_number if the customer wrote one; otherwise use null.
The suggested reply is a first draft for a human agent, not a promise.
TEXT;
}
public function schema(JsonSchema $schema): array
{
return [
'subject' => $schema->string()->max(80)->required(),
'category' => $schema->string()->enum(self::CATEGORIES)->required(),
'priority' => $schema->string()->enum(self::PRIORITIES)->required(),
'order_number' => $schema->string()->nullable()->required(),
'summary' => $schema->string()->required(),
'suggested_reply' => $schema->string()->required(),
];
}
}
The categories and priorities are class constants so the schema and the validation rules share one list.
order_number is both nullable() and required(). That means "always include the key, and use null when there is none", which is clearer for the model than leaving the key out. It also matches what strict structured output modes from providers such as OpenAI expect: every property listed as required, with optional values expressed as nullable.
What the provider receives
I ran this against an OpenAI-compatible endpoint and logged the request. The SDK turned the schema into a response_format like this (trimmed):
{
"type": "json_schema",
"json_schema": {
"name": "schema_definition",
"schema": {
"type": "object",
"additionalProperties": false,
"properties": {
"subject": { "type": "string", "maxLength": 80 },
"category": { "type": "string", "enum": ["shipping", "damaged_item", "refund", "other"] },
"priority": { "type": "string", "enum": ["low", "normal", "high"] },
"order_number": { "type": ["string", "null"] },
"summary": { "type": "string" },
"suggested_reply": { "type": "string" }
},
"required": ["subject", "category", "priority", "order_number", "summary", "suggested_reply"]
},
"strict": false
}
}
Note "strict": false. With that driver and the default settings, the provider is asked for this shape but not forced into it. Even with strict mode, maxLength and the business rules ("this order exists") are things you should check yourself. So the server treats the model's answer as user input.
The endpoint: prompt, then validate
At first I planned to stream the structured output so fields would fill in as they were generated. In 1.4.0 that is not possible yet. Calling stream() on an agent with structured output throws:
InvalidArgumentException: Streaming structured output is not currently supported.
So the endpoint uses prompt() and returns JSON. For a short form the wait is usually a few seconds, and a "Drafting…" state is enough.
<?php
namespace App\Http\Controllers;
use App\Ai\Agents\TicketDraftAgent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class TicketController extends Controller
{
/**
* The rules a ticket must pass, whether a human or the model filled it in.
*/
protected function rules(): array
{
return [
'subject' => ['required', 'string', 'max:80'],
'category' => ['required', Rule::in(TicketDraftAgent::CATEGORIES)],
'priority' => ['required', Rule::in(TicketDraftAgent::PRIORITIES)],
'order_number' => ['nullable', 'digits:4', 'exists:orders,number'],
'summary' => ['required', 'string', 'max:2000'],
'suggested_reply' => ['nullable', 'string', 'max:2000'],
];
}
public function draft(Request $request)
{
$validated = $request->validate([
'message' => ['required', 'string', 'max:5000'],
]);
$draft = (new TicketDraftAgent)->prompt($validated['message'])->toArray();
$errors = Validator::make($draft, $this->rules())->errors()->toArray();
return response()->json([
// Cast so an empty draft is still a JSON object, not [].
'draft' => (object) array_diff_key($draft, $errors),
'rejected' => array_keys($errors),
]);
}
public function store(Request $request)
{
$ticket = $request->validate($this->rules());
// A real app would create a Ticket model here.
return response()->json(['ticket' => $ticket], 201);
}
}
Route::view('/tickets/new', 'tickets');
Route::post('/tickets/draft', [TicketController::class, 'draft'])->middleware('throttle:ai');
Route::post('/tickets', [TicketController::class, 'store']);
A few points:
->toArray() on the structured response gives the decoded fields. The response also supports array access ($response['subject']).
- Invalid fields are dropped, not "fixed". If the model invents a category or an order number that does not exist, the client never sees that value, only its name in
rejected. The person fills it in.
- The
exists:orders,number rule matters most. A schema can make sure order_number is a string. Only your database can tell you whether that order exists.
throttle:ai is a named rate limiter for the endpoints that cost money (Limit::perMinute(30) per user or IP in AppServiceProvider).
When the model ignores the schema
I wanted to know what happens when a model answers with prose instead of JSON, so I made my test server reply "Sure! Here is a ticket for you." In 1.4.0, the gateways decode structured output leniently: they try plain JSON, then a fenced code block, and if nothing works they return an empty array without throwing. My endpoint then returned:
{"draft":{},"rejected":["subject","category","priority","summary"]}
Nothing broke. The form shows the human that the draft was ignored. That empty array is also why I cast draft to an object: without the cast, PHP's empty array becomes [] in JSON.
The Vue side: a draft request that only the latest call wins
// resources/js/composables/useTicketDraft.js
import { ref } from 'vue';
const csrf = () => document.querySelector('meta[name="csrf-token"]')?.content ?? '';
export function useTicketDraft() {
const loading = ref(false);
const error = ref(null);
let controller = null;
async function requestDraft(message) {
controller?.abort(); // a new request replaces an old one
controller = new AbortController();
loading.value = true;
error.value = null;
try {
const response = await fetch('/tickets/draft', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': csrf() },
body: JSON.stringify({ message }),
signal: controller.signal,
});
if (!response.ok) throw new Error(`Draft failed with ${response.status}`);
return await response.json(); // { draft, rejected }
} catch (e) {
if (e.name !== 'AbortError') error.value = e;
return null;
} finally {
loading.value = false;
}
}
return { loading, error, requestDraft, cancel: () => controller?.abort() };
}
Merging the draft without overwriting the human
The form keeps two sets: touched, the fields the person typed in, and aiFilled, the fields the model filled that nobody has edited yet.
<script setup>
import { reactive, ref } from 'vue';
import { useTicketDraft } from '../composables/useTicketDraft';
const fields = ['subject', 'category', 'priority', 'order_number', 'summary', 'suggested_reply'];
const customerMessage = ref('');
const form = reactive({ subject: '', category: '', priority: 'normal', order_number: '', summary: '', suggested_reply: '' });
const touched = reactive(new Set());
const aiFilled = reactive(new Set());
const rejected = ref([]);
const errors = ref({});
const saved = ref(false);
const { loading, error, requestDraft } = useTicketDraft();
function edit(field) {
touched.add(field);
aiFilled.delete(field);
}
async function draft() {
const result = await requestDraft(customerMessage.value);
if (!result) return;
for (const field of fields) {
// Never overwrite what the human already typed.
if (touched.has(field) || !(field in result.draft)) continue;
form[field] = result.draft[field] ?? '';
aiFilled.add(field);
}
rejected.value = result.rejected;
}
async function save() {
errors.value = {};
const response = await fetch('/tickets', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
},
body: JSON.stringify({ ...form, order_number: form.order_number || null }),
});
if (response.status === 422) {
errors.value = (await response.json()).errors;
return;
}
saved.value = response.ok;
}
</script>
Vue 3 makes a reactive Set work as you would hope: aiFilled.has('subject') in the template updates when the set changes.
The edit() handler runs on @input and @change. Those events fire only when a person interacts with the field. When the code sets form.subject from the draft, no input event fires, so AI-filled values do not count as edits.
The template, shortened to two fields:
<template>
<form class="space-y-3" @submit.prevent="save">
<label>
Customer message
<textarea v-model="customerMessage" name="message" rows="3" />
</label>
<button type="button" name="draft" :disabled="loading || !customerMessage.trim()" @click="draft">
{{ loading ? 'Drafting…' : 'Draft with AI' }}
</button>
<p v-if="error">Could not draft this ticket. Fill it in by hand.</p>
<p v-if="rejected.length">Ignored suggestions for: {{ rejected.join(', ') }}</p>
<fieldset :disabled="loading">
<label>
Subject <span v-if="aiFilled.has('subject')">AI draft</span>
<input v-model="form.subject" name="subject" @input="edit('subject')" />
</label>
<label>
Category <span v-if="aiFilled.has('category')">AI draft</span>
<select v-model="form.category" name="category" @change="edit('category')">
<option value="" disabled>Choose…</option>
<option value="shipping">Shipping</option>
<option value="damaged_item">Damaged item</option>
<option value="refund">Refund</option>
<option value="other">Other</option>
</select>
</label>
<!-- priority, order_number, summary, suggested_reply follow the same pattern -->
</fieldset>
<ul v-if="Object.keys(errors).length">
<li v-for="(messages, field) in errors" :key="field">{{ field }}: {{ messages[0] }}</li>
</ul>
<button type="submit" :disabled="loading">Create ticket</button>
<p v-if="saved">Ticket created.</p>
</form>
</template>
Disabling the fieldset while the draft request runs avoids a confusing case: the person types into a field, then the draft lands and fills the fields around it. If you want people to keep typing while the draft runs, remove the disabled. The touched check still protects their edits.
Design choices worth copying
Label AI content until a human touches it. The "AI draft" badge disappears when the person edits the field. It tells the reviewer which values nobody has checked yet.
Keep the suggested reply a draft. The schema calls it a suggestion, and the instructions say "not a promise". Nothing in this flow sends it to the customer. A person still has to copy it or click Send in your real ticket system.
Validate twice. draft() filters the model's output so the form does not show invalid values. store() validates everything again because the browser can send anything. Both use the same rules() method.
Do not invent missing data. The instructions tell the model to use null when there is no order number, and the exists rule catches the cases where it invents one anyway.
Testing it
The SDK can fake structured agents: pass an array of field values per expected prompt. These Pest tests cover the endpoint:
use App\Ai\Agents\TicketDraftAgent;
it('returns the structured draft from the agent', function () {
TicketDraftAgent::fake([[
'subject' => 'Cracked screen',
'category' => 'damaged_item',
'priority' => 'high',
'order_number' => '1002',
'summary' => 'Phone arrived cracked.',
'suggested_reply' => 'Sorry! Can you send a photo?',
]])->preventStrayPrompts();
$this->postJson('/tickets/draft', ['message' => 'My phone from order 1002 is cracked'])
->assertOk()
->assertJsonPath('draft.category', 'damaged_item')
->assertJsonPath('draft.order_number', '1002')
->assertJsonPath('rejected', []);
TicketDraftAgent::assertPrompted(fn ($prompt) => $prompt->contains('cracked'));
});
it('drops fields that fail validation', function () {
TicketDraftAgent::fake([[
'subject' => 'Broken item',
'category' => 'complaint', // not an allowed category
'priority' => 'high',
'order_number' => '7777', // no such order
'summary' => 'Arrived broken.',
'suggested_reply' => 'Sorry!',
]])->preventStrayPrompts();
$this->postJson('/tickets/draft', ['message' => 'Order 7777 arrived broken'])
->assertOk()
->assertJsonMissingPath('draft.category')
->assertJsonMissingPath('draft.order_number')
->assertJsonPath('rejected', ['category', 'order_number']);
});
preventStrayPrompts() makes the test fail if the code prompts the agent more often than you faked. Combined with Http::preventStrayRequests() in tests/Pest.php, no test can reach a real provider by accident.
The four endpoint tests (including the empty-draft case) pass. I also ran the Vue component with Vitest and happy-dom against the running Laravel app and a scripted OpenAI-compatible test server. The test types a subject, asks for a draft, and checks that the subject stays as typed, the other fields are filled, and saving shows "Ticket created." A second test checks that order 7777 is listed as ignored and the field stays empty.
Where to go next
- If your form is long and you want fields to appear progressively, watch the SDK's changelog for streaming structured output. Until then,
prompt() plus a loading state is the reliable option.
- For drafts that take longer, use the SDK's
queue() method and push the result to the browser with broadcasting.
- Log the
rejected list. If one field is rejected often, improve the instructions or the schema description for that field.
The model drafts and the human decides. The validation rules are what make that split hold.