Skip to main content
Version: v1 (Current)

SystemAiModelService JSON Configuration Guide

SystemAiModelService uses a model's driver configuration to construct requests, map responses and select callback actions. Use bodyFormat for request templates, responseFormat for synchronous response mapping, and the webhook status/action settings described below for callbacks. The legacy webhookResponseFormat marker is not a standalone callback mapping engine.

Contents​

Service setup and transport​

This guide describes SystemAiModelService; it is not a universal contract for every AI/chat integration in the platform. Select a configured system model, then provide interface, session and input-message context through the service's setup methods. Keep service credentials on the server. Review model configuration alongside the interface and target provider.

The service selects transport from ai_provider (default vertex):

ProviderServer configuration and transport
vertexGoogle client using app.google_cloud_key and Cloud Platform scope.
gxp-diffusionJSON HTTP client with bearer token from app.diffusion_auth_token.
replicateJSON HTTP client with bearer token from services.replicate.api_token; missing token throws during setup.
rembgClient base URL/timeout from services.rembg; special multipart image request and binary-PNG response conversion.

Other provider values throw as unsupported in this service. Ordinary requests concatenate driver baseUrl and defaultCommand and POST the formatted JSON. Configure that complete endpoint deliberately; the service does not insert a missing separator. Request exceptions propagate, with diagnostic logging that can include response headers/body. Do not assume the driver provides its own retry policy or sanitized logs; check the calling job and protect diagnostics.

sendMessage() returns true after its processing path returns; it does not itself verify non-empty generated content. sendMessageSync() returns raw response data plus the response-message reference after refresh. Parsing, response persistence, token-usage/billing and input-message metadata updates occur in sequence, without a whole-operation transaction shown here. A later failure does not prove an earlier response write or provider request was rolled back. Reconcile message and billing state before repeating a failed generation.

bodyFormat​

bodyFormat is the request payload template, not a fixed instances/parameters schema. Match the selected provider's actual payload shape. Scalars pass through; lists and associative objects are recursively formatted. An associative object with a type key is interpreted as a formatter descriptor, so wrap provider objects that have their own literal type in a literal descriptor.

Supported request sources​

Descriptor typeSource
interfaceBuilt-in interface fields (name, model, system_prompt, negative_prompt) or a dot path in custom settings. Asset return modes require their configured field name and project-owned asset.
sessionposter_name and attendee_id, otherwise a dot path in session metadata.
messageprompt, remote_identifier, attachment (base64), attachment_mime, attachment_uri, signed_url; otherwise a dot path in message metadata. Media helpers may access storage.
attendeeAttendee model/resource prepared from the session, with user_avatar_url appended and attendee fields made visible. Names depend on that model; full_name falls back to first_name + last_name. Missing names return null. Verify project field definitions and personal-data handling.
stringSupplied value.
concatConcatenate descriptor values without an implicit separator. Add spaces explicitly.
literalPreserve the wrapped object's own keys, including type, while resolving nested values. Use another wrapper for a deeper object with its own type.
response_uriPrepare/use the response message's attachment root and append /model_response. Its value is ignored; it does not read a provider response attachment.
webhook_urlGenerated callback URL using the interface ID and server webhook domain/protocol configuration; returns null without interface context.

Unknown descriptor types resolve to null before defaults. A descriptor's default takes precedence over a driver default keyed by its scalar value; defaults apply when the resolved value is null, not when it is false, zero or an empty string. addSpace accepts prepend, append or both (another truthy value appends). Supported casts are int, float and object; another cast leaves the value unchanged. These transformations are not provider-schema validation.

Request template example​

This example requires an initialized service with interface system prompt System instructions and current message prompt Reader question. It exercises formatting only and is not a complete driver or a provider request specification:

{
"instances": [
{
"prompt": {
"type": "concat",
"value": [
{"type": "interface", "value": "system_prompt"},
{"type": "string", "value": "\nUser input: "},
{"type": "message", "value": "prompt"}
]
}
}
],
"parameters": {
"samples": {"type": "string", "value": "2", "cast": "int"},
"output": {"type": "literal", "value": {"type": "text", "enabled": true}}
}
}

The formatted prompt is System instructions\nUser input: Reader question, with an actual newline; samples is integer 2 and output retains type: text. Formatting a template does not authenticate, dispatch a request, persist a response or prove that the selected provider accepts it. Avoid resolving storage/callback descriptors in a simple formatting probe unless that probe deliberately supplies their dependencies.

responseFormat​

Response mapping uses top-level response keys containing fields lists, not the request template's typed-value descriptors. There is no generic response json, date, list or concat conversion in the reviewed extraction path.

For each configured top-level key, the parser proceeds only when that key exists with a non-null value in the decoded response and its configuration has an array fields. With multiple: true, each array item is processed separately. Without multiple, it processes the value at that key, or the entire response when useRoot: true. useRoot does not bypass the top-level key-presence check. This is not JSON Schema validation; match each selected value's shape to the extraction configuration.

An empty format processes the full decoded response as metadata. Invalid JSON or a decoded non-array response is logged and skipped, rather than necessarily raising an exception to the caller. A non-empty format with no matching keys can also produce no mapped message. Check actual response-message state; transport success does not establish usable generated content.

Response mapping example​

For a provider response with a candidates array whose items have content.parts, use:

{
"candidates": {
"multiple": true,
"fields": [
{
"name": "prompt",
"key": "content.parts",
"findFirst": {"type": "text", "path": "text"}
}
]
}
}

Given an item with content.parts equal to [{"text":"First answer"},{"text":"Second answer"}], this maps First answer to the message prompt. It does not concatenate text parts. Multiple candidate items are processed individually; that does not mean multiple text parts of one candidate become separate messages.

Field extraction and destinations​

Field configurationBehavior
name + keyExtract a dot path from the selected object and assign its destination.
key: selfJSON-encode the selected object, except an attachment destination uses attachment handling.
key: self-objectPreserve the selected object without JSON encoding.
findFirstSearch the array at key and return a path from the first matching part. Missing/non-array parts return null.
name: attachmentConvert base64 by default, or fetch a URL when field type is download_link; optional mimeKey or mime controls MIME, default PNG. This can perform storage/network work.

Direct destinations are prompt, attachment, attachment_upload_status and remote_identifier. name: metadata merges an object into metadata; other names become metadata keys. A JSON string is not automatically decoded merely by setting type: json. Supply the required object shape and test it before persistence.

findFirst.type supports text, inlineData, file (matching fileData), functionCall and functionResponse. It stops at the first part containing the selected property, even if the extraction path inside that part resolves to null. It does not continue searching for a later usable value. mimePath can obtain MIME from the matched part for an attachment. A matching function-call part is data extraction, not authorization to execute a tool.

For an inline image, this field descriptor belongs inside the selected response mapping's fields array:

{
"name": "attachment",
"key": "content.parts",
"findFirst": {
"type": "inlineData",
"path": "inlineData.data",
"mimePath": "inlineData.mimeType"
}
}

Here mimePath is relative to the matched part; mimeKey, when supplied on the field, is relative to the selected response object. The matched MIME takes precedence for attachment processing when it is non-null; otherwise the field's mimeKey result is used when configured, or mime/default image/png when no mimeKey is configured. A missing mimeKey path is not a guaranteed PNG fallback. This descriptor illustrates extraction, not a complete driver or a tested provider/file-transfer request.

The first processed result updates an existing response message when one is available and the service has not switched to new-message mode. After that update, further results require session context to create additional messages; without it they log a warning. With no existing response message, a session is required from the outset. There is no non-empty-prompt guard in this persistence branch: a selected empty object or null extracted field must not be treated as a successfully generated answer merely because a message was saved. Invalid JSON or unmatched top-level keys can instead avoid processing altogether.

The generation event is dispatched before the shown message persistence branch; attachments and completion events have further model/queue behavior. Verify actual records and attachment readiness separately from events, formatter probes or HTTP success.

webhookResponseFormat​

Callback route and authentication​

When webhook routes are enabled, the configured webhook domain exposes POST /webhook/v1/ai-response/{ai_interface}. The route inherits the webhook middleware group, including AuthenticateWebhook and route binding. This ordinary route uses X-Webhook-Secret, matching the server's configured webhook or orchestrator secret; the controller's API-key/provider-auth annotations do not implement an additional provider-signature check. Have a maintainer verify non-empty configured secrets and actual gateway/provider header delivery before enabling callbacks.

The controller returns 422 for an empty body or invalid JSON. It constructs the selected model service and processes the original JSON string synchronously, then returns 200 with message: success if processing returns. An unknown/missing correlation identifier can produce no action or a lookup failure; a successful acknowledgement does not establish content was updated. Service/provider setup can fail before callback actions run. Confirm interface/project correlation and duplicate-delivery handling in the deployed integration; shared-secret admission alone is not message ownership validation.

Status actions​

The name is misleading in the current service: the presence of webhookResponseFormat can trigger response-message preparation before the initial request, but processWebhookResponse does not directly parse that object as the callback mapping. Callback handling uses webhookMessageStatus, webhookMessageIdentifier and webhookStatusActions; individual actions provide their own responseFormat.

The callback processor reads a top-level status key (default status) and identifier key (default id). These settings are direct keys, not dot-path extraction. A truthy identifier is looked up against message remote_identifier; a missing matching record raises a lookup failure. The inspected service lookup is not itself scoped by interface/project, and finding a record is not callback authentication. Review the actual callback controller's authentication, scope and correlation behavior before enabling a provider integration.

Actions are selected from the matching status entry, falling back to default when that entry is absent. They run in configured order; an unknown method logs a warning. Supported handlers include:

Action methodCurrent behavior
retrieveAttachmentGET from action baseUrl with {remote_identifier} substitution when requestMethod is exactly GET; otherwise POST the formatted action body. Parse its response with the action's responseFormat.
updateMessageParse the callback body with the action's responseFormat.
sendCreatedEventReload the response message and emit its model-created event; not proof that downstream listeners finished.
shareToSocialStream, shareToAiInterfacePresent as TODO handlers in the inspected service; do not rely on them to publish content.

The documented HTTP controller supplies the original JSON string. Direct service callers can supply a string or array, but the response parser calls JSON decoding on its input. Do not infer that an array callback works through every action path merely from the entry-point signature. Test the actual serialized callback/controller/action chain, duplicate delivery, unknown status/identifier and provider errors with synthetic data. Neither configuration presence nor a callback HTTP acknowledgement establishes persisted content, safe replay or completed downstream processing. For a new integration, define a stable provider event/job identity and retain an external delivery record, reconcile that identity to the intended interface/project/message, and specify which status transitions can be replayed. Do not mark a delivery complete merely on receipt; verify the expected persisted result. These are integration requirements, not deduplication features supplied by this service.

Best practices​

Keep JSON valid: explain configuration in accompanying documentation rather than adding comments inside JSON. Version the model/driver configuration together with representative provider payloads. Test request formatting, response extraction, persistence and actual provider acceptance separately. Use isolated fixtures and mock transport for routine tests; credentials remain server-side.

Troubleshooting​

SymptomCheck
Missing request valuesSource context, supported descriptor name, default handling and literal objects with their own type.
HTTP success but no outputResponse key/fields mapping, multiple/useRoot selection and actual message persistence.
Only one text part appearsfindFirst deliberately returns the first matching part, without concatenation.
Callback acknowledged but unchangedCorrelation identifier, status-action selection and whether the action actually maps or persists data.
Callback rejectedHeader delivery, non-empty configured shared secrets, valid JSON and interface binding.
Error followed by a duplicate generationReconcile remote request, response records, attachments and billing before retrying; no whole-operation rollback/replay guarantee is established here.
Unexpected sharing failureThe two share action handlers are TODOs in this service, not supported publishing operations.

Verification scope​

The documented formatter, response extraction/persistence branches, provider setup and callback admission/action contracts completed source and fresh-reader review on 2026-10-15. Separate offline fixtures cover request formatting (one case/six assertions), intercepted response processing/extraction (one/five), and shared-header middleware with non-empty synthetic configuration (one/four). They do not execute provider authentication/network, attachment conversion/storage, message persistence/billing, a full routed callback, correlation tenancy or duplicate delivery. Verify those behaviors in the target integration before release.