Portfolio Services Company Contacts Blog Get a Quote
uaruen
Themis checks a gold token against a cobalt glass schema frame, with a human-review tray and a locked record beside her.
Artificial Intelligence

How to Get Correct JSON from AI for CRM and ERP

Ivan Deineka
Ivan Deineka
CEO at BotLabs
· Updated 12 min read
Key takeaway: The short answer: a CRM or ERP integration needs two separate things. First, schema-constrained structured output so the model returns data in a known format with the required fields and types. Second, your…

The short answer: a CRM or ERP integration needs two separate things. First, schema-constrained structured output so the model returns data in a known format with the required fields and types. Second, your own business-value checks in the integration code before any write. Valid JSON does not mean the amount is correct, the product exists, the customer was found, or the model was authorized to change a deal.

The key requirement is that the model proposes data while your code decides whether to write it, according to the process rules. After reading this article, you will be able to describe the data contract for your use case, the checks required before a CRM write, how to handle incomplete and refused responses, and the acceptance examples an integration must pass before launch.

Three levels of correctness

When a developer says “the model returns invalid JSON,” they may mean three different problems. These should be separated because each has a different solution.

Level 1. Syntax. The response is valid JSON at all: braces are closed, strings are quoted, and no explanatory text appears before or after the object. JSON mode in many APIs solves this problem, and no more.

Level 2. Schema compliance. The object has all required fields with the right types, enum values come only from the allowed list, and there are no extra fields. Schema-constrained structured output, supported by some models and APIs, targets this level. The difference from JSON mode matters: any object can be valid JSON, while schema compliance means the model will not omit a required key or invent a value outside an enum.

Level 3. Semantic correctness. Values match reality and the process rules. The customer ID exists in the CRM. The amount matches what the customer wrote. The date is not in the past. The status is allowed for the deal’s current stage. The user on whose behalf the integration acts has permission for the operation.

Provider documentation explicitly allows for third-level errors even when the structure is perfect: the model can fill a field with the wrong value, refuse to answer, or return an incomplete response. The schema handles form; your validation handles content.

The data contract

The data contract describes exactly what the integration expects from the model and what it will do with each field. Write it before the prompt, together with the owner of the CRM process.

For each field, define:

  • Whether it is required. Is a write impossible without it, or can it be empty?
  • Type and format. Number or string, integer or decimal, date format (for example, ISO 8601 with a time zone), and decimal precision.
  • Allowed values. Use enums for statuses, currencies, and request types. The model must not invent a status such as “almost closed” if the CRM has none.
  • Rule for missing data. If the text contains no amount, the field should be null, not 0 or an average. It is safer to always include the field and mark missing data explicitly as null; then the integration can distinguish “the model forgot the field” from “the data is genuinely absent.” Check how your API describes optional values.
  • Source of the value. Does it come from the customer’s text, a reference table, or a calculation? Mark an amount “calculated” by the model separately from one the customer explicitly wrote.
  • Currency and units. An amount without a currency is incomplete. So is a quantity without a unit of measure.

A separate status field in the object helps the model signal uncertainty. For example, needs_review means “I filled the fields, but something needs a person’s review.” This is a useful contract, but it does not prove correctness: the model may say ok even when it is wrong. Treat model status as a routing hint, not a substitute for validation.

Another practical tip is to give fields clear names and short descriptions. amount_uah_from_text is less ambiguous than sum. A schema description also acts as an instruction: “the amount explicitly stated by the customer in the email; null if no amount is given” leaves less room for guessing than “amount.”

Keep the contract as a separate document next to the code and change it only with the process owner. When a new CRM status is added or the currency list changes, update the schema, prompt, and checks together, then rerun the acceptance examples.

Incomplete responses and refusals

Structured output does not mean every response will be complete. Provider documentation describes at least two separate cases the integration must handle explicitly.

Refusal. The model may refuse a request, for example for safety reasons. In these APIs, the refusal comes as a separate field or marker, not as an object matching the schema. If the integration does not check for it, it may fail to parse a missing object or, worse, write empty values.

Truncated response. If the response reaches the token limit, the JSON may be incomplete. APIs usually report the reason for completion, such as a length-limit marker. Do not write even a partial result.

Handling rules:

  • Check the completion reason before parsing. Only a normally completed response proceeds.
  • Handle refusals as a separate result. Log the refusal and route the request to a person. An automatic retry of the same request makes sense only when the cause is understood and a retry could produce a different result.
  • Do not write streamed output before completion. If the response arrives in chunks, send data to the CRM only after it has fully arrived and passed all checks.
  • Do not guess missing values. If a required field is absent or null, mark the record incomplete and request the data instead of inserting a default.

Checks before the CRM

After JSON parsing and schema validation, the data goes through business validation. This layer is implemented in code and does not depend on the model.

Describe the full path from model response to CRM write as a sequence in which each step can stop processing:

  1. Check the completion reason and whether the response is a refusal.
  2. Parse the JSON and validate it against the schema with your own validator, even if the API promises structured output. This protects against model or configuration changes.
  3. Run the business checks below.
  4. Check the idempotency key.
  5. Decide whether the action requires human approval.
  6. Write to the CRM and log the input event, model response, validation results, and ID of the created record.

The final log is not just for reporting. When a manager sees a strange deal, it helps identify whether the model, validation, or CRM caused the problem.

Typical checks include:

  • Entity existence. The customer, product, manager, or branch with those IDs exists in the CRM or ERP. Otherwise, do not create the record.
  • Allowed values. The currency is on the allowed list, the status is valid for the current stage, and the quantity is within a reasonable range for the product.
  • Arithmetic. Line items add up to the total; unit price multiplied by quantity equals the line amount. Code:not the model:performs the calculations.
  • Source match. A value the model claims to have extracted is actually present in the text. For critical fields (amount, date, contract number), it is useful to retain the original text passage from which they were extracted.
  • Permissions. The integration acts as a specific user or service account with only the required permissions. The CRM or a separate service checks authorization; the model does not. If the model proposes changing a deal status and the user lacks permission, reject the action.
  • Record version. When updating an existing record, check that it has not changed since it was read. Otherwise, you could overwrite changes a manager just entered manually.

Also separate actions by risk. Creating a draft customer note and changing a deal amount or sending an invoice have different error costs. For high-cost actions, require human approval even when all technical checks pass.

Retries and idempotency

Integrations retry requests after timeouts, webhook redelivery, or a workflow restart. If every retry creates a new record, the CRM will accumulate duplicate deals, tasks, and contacts.

Idempotency means that processing the same input event again does not change the result after the first successful run. It requires:

  • A stable event ID. An email, message, webhook, or form-row ID. Some automation platforms use it to avoid running a workflow twice for one record. But that protects only the trigger, not the later CRM write.
  • An operation key. Build a key for each action, such as “event ID + action type.” Before writing, check whether that operation has already been completed.
  • A lookup for an existing record. Before creating a contact or deal, check for a record with the same external ID.
  • Care after a timeout. A timeout does not mean the write failed. The CRM may have created the deal while its response never arrived. Check whether the record exists before retrying.

Remember that the model may return slightly different values when called again. Build the idempotency key from the input event, not the model response.

An acceptance test set

Do not enable the integration on real data until it passes a fixed set of examples, including failure cases. The example below is illustrative; the data is fictional and does not come from a real CRM.

The model returned:

{"customer_id":"C-17","amount":1200,"currency":"UAH","status":"needs_review"}

Here is a compact illustrative schema for this object. The values UAH and needs_review are examples; replace them with the actual allowed values in your CRM. All four fields are required, but an unknown amount may be null. Supported JSON Schema subsets vary by provider and API mode, so check support for your model before using it. The schema does not check whether the customer exists, whether the amount is supported by the source, or whether the caller may write the record; integration code performs those checks.

{
  "type": "object",
  "properties": {
    "customer_id": {
      "type": "string"
    },
    "amount": {
      "type": [
        "number",
        "null"
      ]
    },
    "currency": {
      "type": "string",
      "enum": [
        "UAH"
      ]
    },
    "status": {
      "type": "string",
      "enum": [
        "needs_review"
      ]
    }
  },
  "required": [
    "customer_id",
    "amount",
    "currency",
    "status"
  ],
  "additionalProperties": false
}

The schema accepts the object: all fields are present, types are correct, and currency and status are in the allowed lists. Business checks run next.

Illustrative validation table

CheckWhat the code doesResult for the exampleWhat happens if it fails
Customer existsLooks up C-17 in the CRMFoundNo record is created; route the request to a person
Amount is nonnegative and supported by the textCompares 1200 with a passage from the customer’s emailPassage contains “1,200 UAH”Mark “amount unverified” and require manual review
Currency is allowedChecks UAH against the process currency listAllowedReject
Status is allowedneeds_review is valid for new requestsValidReject
Permission for the actionThe service account may create draft dealsYesReject and log
RetryThe operation key has not been usedNewA repeated event does not create a second deal

Now consider the same object with "customer_id":"C-99", which does not exist in the CRM. The JSON is valid and the schema is satisfied, but the write is unacceptable. This shows why format does not replace validation.

The minimum acceptance set for this kind of integration is:

  1. Valid request. All data is in the text and a record is created.
  2. Unknown product or customer. The model returns an ID that does not exist. No record is created.
  3. Missing amount. The text contains no amount. The field is null and the record is marked incomplete.
  4. Prohibited action. The text requests a change the integration is not authorized to make. Reject it.
  5. Duplicate event. The same event arrives twice. Only one record is created.
  6. Refusal or truncated response. Nothing is written and the request is routed to a person.

Conclusion

A schema makes the form of a model response predictable. The integration code ensures data correctness and safe writes through business checks, permission controls, refusal handling, and idempotency.

What you can do in your process:

  1. Define the data contract for one use case: fields, types, enums, rules for missing values, and the source of each value.
  2. Enable schema-constrained structured output if your model supports it, and check completion reasons and refusals before parsing.
  3. Implement business checks for entity existence, allowed values, arithmetic, text matching, permissions, and record versions.
  4. Define an idempotency key from the input event and check for an existing record after every timeout.
  5. Assemble the six acceptance examples above and run them before each launch and after prompt or schema changes.
  6. Separate actions by risk and decide which require human approval.

If you plan to send AI-generated data to a CRM or ERP, the BotLabs team can review your use case in a 15-minute consultation. We will discuss the fields your process needs, the required checks, and which actions should wait for human approval. The next step will be to choose the acceptance examples to test first.

Frequently asked questions

For normally completed responses, JSON mode ensures syntactically valid JSON, not schema compliance; handle refusals and incomplete outputs separately. Schema-constrained structured output, where supported, also limits the fields, their types, and allowed values. Neither option checks whether the values themselves are correct.

Not automatically. First handle the refusal as a separate result: log it and route the request to a person. A retry makes sense only when the cause is understood and another attempt could produce a different, acceptable result. Blind retries waste resources and do not solve the problem.

Because a correctly structured object can still contain a wrong price, date, or ID. An object with a nonexistent customer fully matches the schema, but writing it would corrupt CRM data. The integration code separately validates values, permissions, and retries.

Request a consultation

15 min · specialist consultation

Consultation on AI and CRM integration

In 15 minutes with an automation specialist, discuss one CRM or ERP operation, its required fields and human approval. Identify the first data validation check and acceptance example to prepare.

15 minutes with a specialist.

A BUSINESS CONSULTATION
AI DATA → FIELD CHECKS → NEXT STEP

AI data
Field checks

15 minutes with a specialist to discuss fields and write rules and identify the first integration check.

Automation consultation15 min · specialist consultation
… click to support
Ivan Deineka
Ivan Deineka
CEO at BotLabs
Ivan Deyneka is an entrepreneur and founder of BotLabs Agency, with over 8 years of experience launching and scaling digital products in the field of business automation.
← Back to Blog

Recommended articles

AI and your CRM15 minutes with a specialist.Request a consultation