Blog

Laravel + Jev: an intelligent router for AI apps

Build an intelligent router for AI applications with Laravel and Jev. Classify requests, choose workflows, and send only the right cases to an agent.

Francisco Gaona

Francisco Gaona

Founder and technical lead

When you start adding AI to an application, the first experiment is usually quite simple.

A message comes in, you send it to a model, and you wait for a response.

Then you want to do something more useful. Retrieve information, select a tool, create a record, execute an action, ask for confirmation, or send the case to a person.

And the prompt starts getting bigger:

Analyse the user's request.

Determine their intent.

Decide whether you need to retrieve information.

Choose the right tool.

Check whether the operation is sensitive.

Return valid JSON only.

Please.

The “please” is not mandatory, but by that point we are already negotiating with the machine.

Current models can return structured data and follow complex instructions, but we are using a model designed to generate text as the application’s router, authorisation system, and operations director.

That makes important decisions start living inside a huge prompt that nobody wants to touch.

We are trying a different approach in an application built with Laravel: using Jev to classify the request before deciding which part of the backend should handle it.

Jev proposes a route, and the backend decides what happens next. It does not answer the user.

The model was deciding too many things

An AI application can receive very different requests:

  • A question we can answer directly.
  • A query that needs information to be retrieved.
  • A request to change something in another system.
  • A request that must go through the agent.
  • An operation that requires confirmation.
  • A case that is too ambiguous to act on safely.

An LLM can classify all those situations and decide which tool to use, what information to retrieve, whether to execute an action, and how to respond afterwards. That does not mean we should give it all those responsibilities.

If we use the same model to interpret, route, authorise, and respond, we mix very different responsibilities. The application’s operating policy becomes hidden among natural-language instructions.

It looks fucking great in a demo.

In a real application, less glamorous questions start appearing:

  • What happens if two routes seem equally likely?
  • How much certainty do we need to execute an action?
  • What do we do if the provider does not respond?
  • How do we check afterwards why a route was chosen?
  • Can we change the policy without rewriting the entire prompt?
  • Can we test that decision?
  • Who authorised the model to act?

When routes, permissions, and actions depend on instructions hidden in a prompt, the problem becomes architectural.

What is Jev doing here?

Jev is TypeSafe’s System One model. Instead of generating a natural-language response, it receives a state and a set of typed questions. It then returns structured answers that the backend can use directly.

In practice, we define the routes and Jev indicates which one it considers most likely. The backend executes the corresponding flow if the validations and policy allow it; permissions, confirmations, and business rules still belong in the backend.

Jev offers three main types of questions:

  • Noul, to assess whether a statement is true and return a value between 0 and 1.
  • Choice, to select one option from several alternatives defined in advance.
  • Score, to score the state against an ordered scale that we describe.

We can send several questions about the same state in a single request. Jev evaluates them independently, which lets us separate intent, risk, urgency, or the need for review instead of putting everything into one monstrous question.

Jev does not replace the agent; it takes away a prior decision that perhaps we should never have given the agent in the first place.

Our case: Jev as a router

We put a classification layer before selecting the flow that will handle the request.

The conceptual flow looks like this:

User request
        ↓
Deterministic rules
        ↓
Jev classifies the intent
        ↓
The backend applies its policy
        ↓
Selects a route
        ↓
Direct answer, search, action, agent, or review

The exact routes depend on each application.

To explain the pattern, we can use these five:

  • direct: the backend can resolve the request without retrieving additional information.
  • search: we need to look up current, external, or private information.
  • action: the user wants to change something in another system.
  • agent: the request must continue through the agent flow.
  • review: there is not enough clarity or safety to continue automatically.

In Laravel, an illustrative classification could look like this:

use Laravel\Ai\Classification;
use Laravel\Ai\Classification\Boolean;
use Laravel\Ai\Classification\Choice;

$result = Classification::of([
    'message' => $message,
    'recent_context' => $recentContext,
    'available_tools' => $availableTools,
])
    ->question('route', new Choice(
        'Which route should handle this request?',
        [
            'direct' => 'The backend can answer without retrieving additional information.',
            'search' => 'The request requires current, private, or external information.',
            'action' => 'The user wants to change something in an external system.',
            'agent' => 'The request must continue through the agent workflow.',
        ],
    ))
    ->question('needs_review', new Boolean(
        'This request is ambiguous or risky enough to require human review.',
    ))
    ->classify();

The question is closed and the routes are defined in advance. Jev evaluates the state and returns a probability distribution; the backend interprets it and applies its own policy.

$route = $result['route'];
$needsReview = $result['needs_review'];

if ($needsReview->isTrue(threshold: 0.8)) {
    return Route::NeedsReview;
}

$selectedProbability = $route->probabilityOf($route->choice);

if ($selectedProbability < 0.75) {
    return Route::Fallback;
}

return match ($route->choice) {
    'direct' => Route::Direct,
    'search' => Route::Search,
    'action' => Route::Action,
    'agent' => Route::Agent,
};

The example is not our exact implementation, but it shows the division of responsibilities:

  • Jev classifies the request.
  • The backend interprets the result.
  • The policy determines whether we can continue.
  • The selected flow resolves the request.
  • Permissions and validations continue to apply to every operation.

Laravel builds the backend. The policy we write determines the decision.

A 0.92 does not mean Jev is right 92% of the time

A Choice response might return a distribution like this:

direct: 0.032
search: 0.083
action: 0.844
agent:  0.055

That does not necessarily mean the classification is correct. Nor does it mean that the backend can automatically execute any action.

Alongside the probabilities, Jev returns a field called confidence in Choice and Score responses.

The name makes it sound like a general measure of whether the model got the answer right, but it does not necessarily represent the probability that the answer is correct.

The Is Jev confident? analysis studied more than one million Jev responses. In Choice responses, the observed value of confidence closely followed a transformation of the winning option’s probability adjusted for the number of options. For Score, the analysis found a measure of concentration around the modal level. None of those findings proves that confidence represents the probability that Jev was right.

confidence describes characteristics of the returned distribution, but it does not prove that the answer is correct.

A distribution can be highly concentrated and still be wrong.

It can also happen that two quite different distributions produce a similar confidence value. In the case of Choice, adding options that receive almost no probability can change the value of confidence even when the main probability stays the same.

A value with several decimal places is not a guarantee.

That is why we would not use the confidence field as permission to execute an operation. At a minimum, we would consider:

  • The probability of the winning option.
  • The distance from the second option.
  • The complete distribution.
  • The number and quality of the defined routes.
  • The impact of an incorrect classification.
  • The results observed on our own cases.
  • Permissions, validations, and rules outside the model.

A reasonably clear classification may select which documentation to retrieve. To send a communication, modify data, or execute an operation that is difficult to reverse, it should be only one more signal.

Real confidence is measured with real results

If we want to claim that a classification with a certain probability is usually correct, we need labelled cases and observable results.

The basic process would be:

  1. Gather representative requests.
  2. Manually assign the correct route.
  3. Run the classification.
  4. Compare the prediction with the expected result.
  5. Analyse false positives, false negatives, and ambiguous cases.
  6. Adjust the questions, descriptions, and policy.
  7. Measure again.

With that data, we can talk about calibration inside our application.

The Bernoulli analysis also observed that repeated calls with the same content could produce different values. With very ambiguous questions, the winning option could even change. This is especially relevant when the first two options are close or the result falls near an operational threshold.

That is why a policy like this may be too simple:

if ($route->confidence >= 0.80) {
    return Route::Action;
}

We can consider the main probability and the separation from the second option:

$actionProbability = $route->probabilityOf('action');
$searchProbability = $route->probabilityOf('search');

$margin = $actionProbability - $searchProbability;

if ($actionProbability < 0.85 || $margin < 0.20) {
    return Route::NeedsReview;
}

return Route::Action;

The values are illustrative.

Real thresholds must be adjusted using our own data and according to the risk of the operation.

There is no universal number that automatically turns a prediction into a good decision.

That would be very convenient. It would also be pretty suspicious.

If an if can solve it, use an if

The initial inspiration for this pattern came from the way the There There team uses Jev to classify incoming email. They detect automatic replies, bounces, and spam before processing a message as a real request.

The order is what matters here: they run deterministic checks on the email headers first. If they find an unequivocal signal, they do not call a model. Jev only receives what the inexpensive rules could not resolve.

We apply the same principle to the router.

If a request contains a valid, unambiguous command, we do not need probabilistic classification.

If the user does not have permission to use a tool, Jev has no role in that decision either.

If we receive an automatic service health check, there is no need to ask an AI what the message intends.

if ($request->isHealthCheck()) {
    return Route::Direct;
}

if ($request->hasVerifiedCommand()) {
    return Route::Command;
}

if (! $user->canUseExternalTools()) {
    return Route::Agent;
}

Jev is for the cases where meaning matters:

  • “Find the latest project changes.”
  • “Add this to the tracker.”
  • “What happened with the payments integration?”
  • “Prepare a reply for the client.”
  • “I want to talk to someone because this is still failing.”

This is where a list of keywords quickly falls short.

The word “add” can indicate an action, except when the user is asking what should be added.

The word “find” can indicate a query, except when it is part of an explanation.

“Prepare a reply” may require the agent, but it does not necessarily mean that we should send anything.

Jev covers that gap when the decision depends on meaning and traditional rules start turning into an endless collection of words, languages, and exceptions.

Several small questions work better than one monstrous question

We could ask everything at once:

Analyse the intent, urgency, risk, permissions,
complexity, required tools, and decide what to do.

But that concentrates too many responsibilities in a single decision.

TypeSafe recommends working with atomic questions. When a decision depends on several independent factors, we can evaluate each factor separately and compose the results later in the backend.

For example:

$result = Classification::of([
    'message' => $message,
    'recent_context' => $recentContext,
    'available_tools' => $availableTools,
])
    ->questions([
        'route' => new Choice(
            'Which route should handle this request?',
            [
                'direct' => 'No additional information or agent intervention is required.',
                'search' => 'Information must be retrieved.',
                'action' => 'The user requests a change in an external system.',
                'agent' => 'The request must continue through the agent workflow.',
            ],
        ),
        'urgent' => new Boolean(
            'The request requires an immediate response.',
        ),
        'sensitive' => new Boolean(
            'The request involves sensitive data or a high-impact operation.',
        ),
        'needs_review' => new Boolean(
            'A person should review this request before the backend acts.',
        ),
    ])
    ->classify();

Jev evaluates the questions over the same state and keeps a separate response for each one.

The backend can then combine the results:

if ($result['sensitive']->isTrue(threshold: 0.7)) {
    return Route::NeedsReview;
}

if ($result['needs_review']->isTrue(threshold: 0.8)) {
    return Route::NeedsReview;
}

$route = $result['route'];

if ($route->probabilityOf($route->choice) < 0.75) {
    return Route::Fallback;
}

return Route::from($route->choice);

Jev evaluates concrete dimensions and the backend composes the final decision.

When our policy changes, we modify the code instead of adding another paragraph to the prompt.

The state can be more than the latest message

The route does not always depend only on what the user has just written.

It may also depend on:

  • The recent conversation context.
  • The available tools.
  • The current point in the process.
  • The capabilities enabled for that user.
  • Information retrieved earlier.
  • The applicable policy.

That is why we can represent the state with a structure:

Classification::of([
    'message' => $message,
    'recent_context' => $recentContext,
    'current_route' => $currentRoute,
    'available_tools' => $availableTools,
    'user_capabilities' => $userCapabilities,
]);

Jev accepts text, JSON objects, and arrays of text values as state. The current model works with textual input, so other formats must first be transformed into text or structured fields.

This does not mean that we should put the entire database into every classification.

The router needs the context relevant to selecting a route, not the application’s complete autobiography.

The more state we add, the more noise we can introduce and the harder it becomes to understand which information influenced the result.

If distinguishing between search and action requires sending forty pages of documentation, the question is probably badly designed.

Why we like this approach

This approach works because it keeps the decision space explicit.

The options are defined in advance

The backend knows which routes are available.

Jev cannot invent a route called:

deploy_to_production_and_hope_for_the_best

It can choose the wrong option, but we define the boundaries of the decision space.

Uncertainty stays visible

A written response can sound confident even when the decision is uncertain. The probability distribution makes cases like this visible:

search: 0.482
action: 0.443
agent:  0.08

The classification is unclear, so we can ask the user to clarify, apply a fallback, or send the request for review.

Thresholds belong to the business

Not all decisions require the same level of safety.

For selecting an internal category, we can accept more uncertainty.

To execute an external action, we can require a larger gap between options, check permissions, and ask for confirmation.

Thresholds stop being hidden in a sentence such as “act only when you are completely sure” and become visible, reviewable values.

The policy can be tested

We can write tests for how the backend reacts:

it('requires review for sensitive actions', function () {
    $decision = new RoutingDecision(
        route: 'action',
        routeProbability: 0.94,
        secondProbability: 0.03,
        sensitiveProbability: 0.86,
    );

    expect($this->policy->resolve($decision))
        ->toBe(Route::NeedsReview);
});

Evaluating the quality of the classification and checking how the backend reacts are different tasks. Keeping them separate makes the system easier to understand.

The agent steps in when it adds value

A request that needs context, reasoning, content generation, or tool coordination continues through the agent flow. A search goes through the search system. An action goes through permissions, validations, and confirmation. If the request can be resolved directly, we do not invoke the agent just to make the application feel more sophisticated.

Where we can screw it up

This pattern can also fail if we implement it badly.

Creating another giant prompt with a different name

If every question tries to decide intent, risk, urgency, tool, and policy in a two-hundred-word sentence, we have only changed the API. The questions, options, and descriptions should be concrete.

Confusing a concentrated distribution with a correct answer

A high probability does not turn a classification into a fact.

The Is Jev confident? analysis is especially useful here: the confidence field summarises properties of the response, but it does not prove that the prediction is calibrated against reality.

We need to measure decisions with our own data. Getting two internal labels wrong may be tolerable; getting it wrong before an irreversible operation is much less funny.

Adding filler options

In Choice, the number of options can influence the value of confidence. According to the Bernoulli analysis, adding alternatives that receive barely any probability can raise the reported value without necessarily improving the classification.

Routes should represent real alternatives. Adding twenty categories to make the number look more precise is still make-up, even if it comes in JSON.

Not saving the original results

If we store only:

route = action

we lose important information.

Where appropriate from a privacy and data-retention perspective, it is useful to record:

  • The selected route.
  • The complete distribution.
  • The difference between the leading options.
  • The other judgements used.
  • The model version.
  • The backend’s final decision.
  • Whether there was confirmation or review.
  • The outcome of the flow.

This lets us review what would have happened under a different policy and distinguish a classification error from a backend failure.

Not preparing a fallback

Jev is an external dependency: it may not respond, exceed the timeout, or return a classification that is too ambiguous. The application needs a fallback for those cases.

try {
    return $this->classifyAndRoute($state);
} catch (Throwable $exception) {
    Log::warning('Jev routing failed.', [
        'error' => $exception->getMessage(),
    ]);

    return Route::Fallback;
}

The fallback depends on the risk:

  • Continue through the general agent flow.
  • Ask for clarification.
  • Send the request for review.
  • Apply a safe route.
  • Tell the user that the operation cannot be executed.

We need to decide this before it fails.

Not controlling the version

TypeSafe offers aliases such as jev-latest, but those aliases can point to different versions over time. The response reports the specific version that processed the request. If we have tuned questions and thresholds against a particular behaviour, the documentation recommends considering a pinned version.

During testing, using the stable alias may be convenient.

In production, it is worth recording the version and testing changes before updating the router.

Turning the router into an authorisation system

Jev can classify that someone wants to create, send, modify, or delete something.

Jev does not decide whether that person has permission.

Authorisation remains in the backend:

if (! $user->can('create', Ticket::class)) {
    throw new AuthorizationException();
}

Classifying an intention does not authorise an operation. Mixing them is a remarkably effective way to end up explaining a fuck-up in a very serious meeting.

When we would use Jev

We see value in cases such as:

  • Classifying the intent of a request.
  • Choosing between several known flows.
  • Selecting a family of tools.
  • Detecting potentially urgent requests.
  • Flagging sensitive operations.
  • Deciding when to ask for clarification.
  • Determining whether a request should go through the agent.
  • Choosing which agent or capability should handle it.
  • Prioritising items within a process.
  • Sending ambiguous cases for review.

All of them involve a semantic decision with known options.

When we would not use it

We would not use Jev to:

  • Write the final response.
  • Summarise a document.
  • Generate code.
  • Maintain an open-ended conversation.
  • Produce creative content.
  • Resolve an exact condition.
  • Replace permissions and validations.
  • Authorise sensitive operations on its own.
  • Fix a business process we still do not know how to describe.

If a comparison, permission rule, or match solves the case, we use that. Nobody gives you a prize for putting AI in every function.

Jev classifies. The backend decides

Jev receives a state, evaluates concrete questions, and returns a distribution the backend can use. Then it steps aside. The agent remains useful for context, reasoning, conversation, and tool coordination; search retrieves information; integrations modify external systems; and traditional rules handle exact conditions. People keep the final say when a decision can have important consequences.

Jev occupies the middle ground: closed semantic decisions that are too flexible for a list of keywords, but that do not need to send the entire request to the agent just to discover what to do with it.

The division of labour is simple:

  1. Rules resolve what is obvious.
  2. Jev classifies what is ambiguous.
  3. The backend applies the policy.
  4. The agent works when it adds value.
  5. People review what is sensitive.

If the classification is not clear enough, we ask for context, use a fallback, or send the case for review. AI does not get the keys to the application.

References

Dealing with something similar?

Tell us what you want to build, fix, or decide. We will tell you what makes sense and what would be a waste of time.

Talk about your project

Contact form

The form is ready when you are.

Load the Microsoft form and tell us what you need.

Prefer email? Write to us directly.

Email us

Privacy preferences

We use essential technologies and, with your permission, functional services such as the contact form.