Last reviewed: November 8, 2026 (Asia/Shanghai); primary references fetched November 8 UTC.
Direct answer
CometAPI request parameter cost controls need to govern the final outbound request. Accept a small application input, reject fields the caller cannot control, and construct the provider payload explicitly from validated values and trusted server policy. Calculate any budget reservation from that completed payload, then send the same body without another client-options merge.
The failure can be one line of ordinary application code. This illustrative pattern lets caller options replace an approved model or output ceiling:
payload = {"model": approved_model, "max_completion_tokens": 256}
payload.update(client_options) # Can replace the values already checked.
Moving trusted settings to the end of the merge protects those particular keys, but still admits additional fields the policy never reviewed. A caller might add a candidate count, tool definition, processing tier, or a second output-limit field. A request can satisfy the provider’s schema while exceeding the application’s authority to spend.
The OWASP Mass Assignment Cheat Sheet recommends dedicated input objects containing only fields the caller may edit and explicit field allowlists. Applying that principle here means keeping the browser’s feature request separate from the much broader provider request.
Who this is for
This guide is for backend engineers and cost owners operating a text feature through CometAPI. It focuses on request construction between the authenticated application route and the outbound dispatcher, especially helpers that accept arbitrary options or forward a browser body.
The sample uses Python 3.12 and Pydantic v2. Its policy values are illustrative application choices. The local checks use synthetic inputs and a fake dispatcher; no authenticated model request, billing result, or deployment is reported.
Key takeaways
- Expose feature inputs such as a prompt and a bounded length preference.
- Keep model selection, tools, instruction roles, and transport configuration under server control.
- Reject unexpected fields instead of forwarding a general options dictionary.
- Build and serialize the final body before reserving its covered cost.
- Test rejected requests at the outbound handoff, where zero dispatches can be observed.
- Recheck the permitted request shape when the model, adapter, or feature changes.
Contract details to verify
Decide who owns each field
For a short-summary feature, a small ownership table makes the policy reviewable:
| Field or capability | Authority in this example | Enforcement |
|---|---|---|
| Prompt text | Authenticated caller | Require text, reject blank input, apply a local length ceiling |
| Desired output allowance | Caller within a server-set range | Integer from 32 through 512; default 256 |
| Model and reasoning setting | Server policy | Fixed reviewed model and effort |
| Conversation roles and instructions | Application | Construct messages explicitly |
| Candidate count, tools, and processing tier | Unavailable through this feature | Reject these fields in application input |
| Endpoint, credentials, and retry configuration | Server deployment | Keep outside the request body supplied by the caller |
An authenticated caller still needs authorization for the feature and its budget. A schema cannot establish account ownership or spending entitlement. Resolve those from the authenticated server context before admission. If users can select a quality profile, authorize a named profile and map it to a server-owned configuration; do not treat the profile as permission to forward arbitrary provider parameters.
Keep the existing model allowlist workflow for choosing approved routes. This boundary ensures the constructed request continues to express that choice.
Verify the selected route’s parameter meanings
The current CometAPI chat reference
documents model, messages, output controls, candidate count, reasoning settings, and streaming. It shows reasoning_effort: "low" and max_completion_tokens for GPT-6 Astra. The output limit includes reasoning and visible output. A 256-token allowance therefore does not promise 256 visible answer tokens. Verify model access and supported settings in the account before enabling this particular route.
The same reference describes n as the number of completion choices and gives a default of one. The sample omits it and relies on that documented default; the caller cannot add it. Reverify defaults and supported parameters for the exact model and adapter before deployment. Do not transplant this payload into a different endpoint family without reviewing its contract.
Define a closed application input
Save this as request_policy.py. The helper receives the application’s decoded JSON object. It validates that original object before any permissive model or filtering step can discard unexpected fields.
import json
from pydantic import BaseModel, ConfigDict, Field
class SummaryInput(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
prompt: str = Field(min_length=1, max_length=8000)
output_tokens: int = Field(default=256, ge=32, le=512)
def prepare_body(decoded: object) -> bytes:
if type(decoded) is not dict:
raise ValueError("invalid_request")
value = SummaryInput.model_validate(decoded)
if not value.prompt.strip():
raise ValueError("invalid_request")
payload = {
"model": "gpt-6-astra",
"messages": [
{
"role": "developer",
"content": "Summarize the supplied text briefly.",
},
{"role": "user", "content": value.prompt},
],
"max_completion_tokens": value.output_tokens,
"reasoning_effort": "low",
"stream": False,
}
return json.dumps(
payload, ensure_ascii=False, allow_nan=False, separators=(",", ":")
).encode("utf-8")
The official Pydantic configuration reference
documents two separate settings used here. Extra inputs are ignored by default; extra="forbid" raises a validation error. Strict configuration disables the normal attempt to coerce values to their annotated types. This feature consequently rejects an output allowance supplied as "256", true, or 256.0 in the decoded Python object.
The public name output_tokens is deliberately translated to the reviewed provider field. The client cannot submit max_tokens, max_completion_tokens, or max_output_tokens alongside it. There is no options or extra_body escape hatch, and the helper never copies the original dictionary into the payload.
The 8,000-character ceiling bounds this feature’s accepted text length. It is neither an input-token count nor a request-byte limit. Apply a separate ingress body-byte limit before JSON decoding, and calculate the final input’s token exposure using the selected route’s method. If nested input objects are added, give each its own explicit field policy; an unrestricted nested dictionary recreates the forwarding problem.
Reserve against the completed request
Pass the prepared body to the controlled dispatcher as bytes. Any cost calculation must inspect that completed request, including application instructions, model, output allowance, and every enabled billable capability. Do not estimate from the browser’s prompt alone and add instructions or tools afterward.
Use the site’s atomic budget reservation workflow for concurrent admission and settlement. This helper supplies a bounded request shape; it does not implement a monetary ledger or make request volume finite.
After admission, send those same prepared bytes. If another layer changes the model, context, cap, or enabled capabilities, rebuild the request and obtain a reservation covering the new attempt before dispatch. Avoid serializing a shared mutable dictionary later, after the reservation was calculated.
Happy-path operator workflow
Authenticate the caller and authorize the summary feature. Enforce ingress limits, decode the JSON, and pass the original dictionary to prepare_body. With {"prompt":"A short note.","output_tokens":256}, the helper constructs a non-streaming GPT-6 Astra request with server-authored instructions, low reasoning effort, and a 256-token completion allowance.
Calculate covered cost from that body and the reviewed rate revision, reserve it, and dispatch once through the configured server endpoint. Keep endpoint and credentials outside user input. Associate the attempt with its policy revision, model, applied cap, reservation, and eventual usage evidence.
CometAPI documents monitoring the response’s usage field for cost control. Use reported usage and the applicable rates for settlement, then reconcile with billing records. A local estimate and a successful response do not establish a final invoice amount.
Error-path operator workflow
A request adds "model":"unapproved-model" or "n":8. Validation rejects the unexpected field before cost admission and before any provider call. Return a fixed application category such as invalid_generation_request; do not retry the same invalid input or try another model.
Catch validation failures at the application boundary. Avoid logging the complete exception, original JSON, prompt, or unexpected property name in routine cost telemetry: those values can contain user data. Record an opaque request ID, policy revision, fixed rejection category, and whether dispatch occurred.
A failure after dispatch belongs to a different state. A timeout or missing usage does not establish zero consumption. Preserve the attempt and reservation for reconciliation, and require separate admission for any permitted replacement call.
Verify the boundary offline
Use a fake sender that records every received body. Send the accepted and rejected fixtures through the same function the application route calls. For every rejection, verify that the sender’s call count stays unchanged.
| Fixture | Required observation |
|---|---|
| Valid prompt; output allowance omitted | Prepared cap is 256 |
| Valid prompt with integer allowance 32 or 512 | Requested boundary value appears in the provider field |
Allowance "256", true, 256.0, or null | Reject before dispatch |
| Allowance below 32 or above 512 | Reject before dispatch |
| Extra model, candidate, tool, tier, or streaming field | Reject before dispatch |
options or extra_body containing overrides | Reject the wrapper field before dispatch |
| Blank, missing, wrong-type, or overlong prompt | Reject before dispatch |
| Original dictionary changed after preparation | Previously prepared bytes retain the approved values |
A local probe on November 8, 2026 used Python 3.12.3 and Pydantic 2.14.3. Four valid requests passed, including the default and both output-range boundaries. All 28 invalid inputs were rejected with zero calls to the fake dispatcher. They included 14 unexpected-field cases, seven invalid output allowances, and seven invalid prompt or root-object cases. The prepared-body check also confirmed that changing the original dictionary afterward did not alter the already serialized cap.
These observations cover the isolated helper and synthetic dispatch wrapper. Before rollout, repeat the fixtures through the actual HTTP handler, middleware, reservation layer, and transport adapter. Capture the final outbound body in that test and verify that no later merge or SDK default introduces an unreviewed field. Confirm rejected inputs cause neither a reservation nor a network request. Keep routine checks offline; any live staging check needs its own small approved allowance.
Failure modes
Validation runs after fields are discarded. An earlier filter removes the evidence of an unwanted option. Feed the original decoded object into the rejecting schema, and keep an extra-field regression fixture.
Trusted keys win, but new fields survive. Reversing merge order still forwards properties absent from the trusted dictionary. Construct the outbound object from an explicit field list.
A nested options object stays open. Root validation passes a general dictionary to another adapter. Remove that escape hatch or define and authorize every permitted nested field.
Cost is reserved before the request changes. A later model substitution or added context invalidates the estimate. Bind admission to the final body and reauthorize changed attempts.
A prompt instruction is treated as enforcement. Asking for brevity does not prevent the caller from requesting a larger cap through an exposed API field. Enforce the numerical policy before dispatch and assess answer completeness separately.
One bounded call is mistaken for a workload budget. Repeated valid requests can still consume substantial money. Retain account authorization, rate controls, attempt limits, and shared budget admission.
Sources checked
- CometAPI: Create a chat completion — endpoint and request fields, model-specific output controls, reasoning-token inclusion, candidate default, streaming, and response usage. Fetched November 8, 2026 UTC.
- OWASP: Mass Assignment Cheat Sheet — dedicated input objects, permitted-field allowlists, limitations of blocklists, and the continuing need for authorization. Fetched November 8, 2026 UTC.
- Pydantic: Configuration
— ignored extras by default, rejection with
extra="forbid", and model strictness. Fetched at its current canonical URL on November 8, 2026 UTC.
These maintained primary references support an evergreen implementation task. They are not evidence of a new incident. Field ownership, numerical limits, admission ordering, and acceptance checks are application design recommendations derived from those references.
FAQ
Can the client request a shorter answer?
Yes. Expose a bounded application preference and translate it to the reviewed output field. Assess whether the resulting answer completes the task, particularly when reasoning shares the allowance.
Is forbidding unknown fields enough?
It establishes only the declared input boundary. The application must still authorize the caller, construct the request safely, reserve covered cost, and ensure downstream layers preserve the policy.
Should an advanced mode forward arbitrary provider options?
Give it a separately authorized contract with explicit fields, supported routes, and cost bounds. Calling an unrestricted dictionary advanced mode does not make its spending authority reviewable.
Does this guarantee the total bill stays below budget?
No. The helper constrains one request’s permitted shape. A financial bound also needs accurate rates, bounded billable components, complete dispatch coverage, concurrent budget admission, and reconciliation.
Reader next step
Choose one feature that forwards a request body or accepts general options. Write its field-ownership table, replace forwarding with explicit construction, and run the rejection matrix at the real outbound handoff. Enable enforcement after the accepted request stays within policy and every rejected fixture produces zero dispatches.
When the server-controlled route is ready, Start with CometAPI , select the reviewed model configuration, and keep the same input boundary in front of it.