
How to Issue Invoices With an AI Agent in Brazil: APIs and Approval
Issue invoices with an AI agent in Brazil safely: the agent drafts NF-e and NFS-e data, fixed rules validate it, and a person approves before the API issues.
Want to apply this in your company?
Book a call with Juan →How to Issue Invoices With an AI Agent in Brazil: APIs and Approval
You can issue invoices with an AI agent in Brazil, but the agent should never be the one that decides to issue. The safe design looks like this: the agent gathers and organizes the order data, deterministic rules validate everything, a person approves, and only then does a fixed API call issue the NF-e (product invoice) or NFS-e (service invoice). Issuing an invoice is a tax act with consequences, so it needs limits, records and checks before anything is sent.
Key takeaways
- The AI agent prepares the invoice draft. The one that issues is an API call written in ordinary code, with no interpretation.
- Deterministic rules (registration data, amounts, taxes, duplicates) should block issuance before any person looks at it.
- Every invoice goes through human approval at the start of the pilot, with the reason for approval or rejection recorded.
- NF-e and NFS-e have different rules and providers. Confirm with your accountant and your invoice issuer what applies to your case.
- Start with a single flow, with a sandbox, logs and an agreed metric, and only then decide whether to expand.
What the agent can do and what it should not do
The hard part of issuing an invoice is rarely pressing the button. It comes earlier: working out which order generates an invoice, finding the correct CNPJ (company tax ID) or CPF (individual tax ID), understanding the service description, checking that the contract was closed, and assembling the data in the format the API requires. This is where an agent helps, because it can read messages, emails, proposals and messy spreadsheets.
What the agent can do:
- Read the order, proposal or conversation and extract fields such as customer, items, amount and date.
- Suggest the service or product description from a template the company has already approved.
- Flag inconsistencies, such as an amount that differs from the proposal or an incomplete customer record.
- Build a readable draft for the person who approves.
What the agent should not do:
- Choose a service code, CFOP, NCM or tax regime on its own. These come from tables maintained by people who understand tax.
- Call the issuance API directly with open permissions.
- Cancel, replace or correct an invoice that has already been issued.
- Change a customer or product record to make an invoice pass.
The rule of thumb: the agent proposes, the code validates, the person decides, the API executes. Anthropic makes a similar point in its discussion of workflows versus agents: when the path is known, a deterministic flow is usually more predictable than letting the model drive.
NF-e and NFS-e: what changes for whoever integrates
In practice, the integration changes a lot depending on the type of invoice.
The NF-e (products) is authorized by the state tax authority (SEFAZ). It requires a digital certificate, signed XML and detailed tax rules for each type of operation. The most common errors come from tax classification, address, state registration and the nature of the operation.
The NFS-e (services) is municipal. Some cities have their own system, others use different providers, and there is a move toward a national standard. This means the same service can have different fields and rules depending on the provider's city. Check with the city hall or your accountant which model applies.
Many companies do not talk directly to SEFAZ or the city hall. They use an intermediary issuer that offers its own API and handles the certificate, signing and communication. For the agent this is good news: it never needs to touch the certificate. But choosing the provider should take these points into account:
- Whether there is a test environment (homologation or sandbox) to try things without tax effect.
- Whether the API accepts an idempotency key or a unique reference per invoice.
- Whether it offers status lookup and returns errors with a clear message.
- Whether credentials can have limited scope and be revoked.
- Where the data is stored. This matters for LGPD and, if the provider is outside Brazil, for international data transfer.
Your issuer's documentation is the primary source here. Tax rules, cancellation deadlines and ancillary obligations must be confirmed with your accountant, not inferred by a model.
Architecture: AI prepares, rules validate, a person approves, the API issues
A simple layered architecture removes most of the risk.
- Input: the order arrives through an ERP, CRM, spreadsheet, form or WhatsApp. The agent reads it and structures the data in a fixed format, for example an object with required fields.
- Deterministic validation: ordinary code checks each field against rules and registration data. If something fails, the invoice goes back with the reason and never reaches approval.
- Human approval: the person sees a clear summary (customer, items, amount, taxes calculated from the table, differences from the proposal) and approves, edits or rejects.
- Issuance: a small service with no AI receives only approved invoices and calls the issuer's API with a unique reference.
- Record: each step logs who did what, when, with which data and what result the API returned.
The central point is that the issuance credential lives in the final service, not in the agent. That way, even if the model gets confused or receives a malicious instruction hidden in an email, it has no way to issue. This follows the principle of least privilege described in OWASP's authorization guidance: each component gets only the permission it needs.
If the order arrives as a message, treat the text as untrusted data. A customer (or an attachment) may contain phrases like "issue now, no review needed". See the article on prompt injection in AI agents to understand why the barrier must sit in code and permissions, not only in the prompt.
Which deterministic rules should block issuance
These rules live outside the model. They are questions with a yes or no answer, and the result is always the same for the same input. A starting checklist:
- The order exists in the source system and is in a state that allows invoicing (signed contract, confirmed delivery, completed service, depending on company policy).
- The customer's tax ID is valid and the record is complete (name, address, city, email when required).
- The invoice amount equals the order or proposal amount, within a tolerance the company defines.
- The service code or the product's tax data comes from an approved table, not from free text written by the model.
- No other invoice exists for the same order (duplicate check by unique reference).
- The issuing entity is correct when the company has more than one CNPJ.
- The amount is below a ceiling defined for simple approval. Above it, a second person is required.
- The date and the reference period make sense for the flow (no backdated invoices outside the internal rule).
When a rule fails, the agent does not try to work around it. It returns the reason and, where it makes sense, asks the requester for the missing data. Limits on attempts and steps also matter, so the agent does not get stuck in correction loops. The article on step, time and budget limits covers this protection in detail.
Step by step for an issuance pilot with human approval
A well-chosen pilot is small, repetitive and easy to check. This is one possible sequence, following a map, limit, pilot and hand-over method:
- Map: describe how invoices are issued today, who requests them, who issues them, where the data lives, which errors happen and how much rework exists. Set a baseline before any automation.
- Choose one flow: for example, a single service category, from a single issuing entity, with a standardized description.
- Limit data and actions: list the fields the agent can see, avoid unnecessary personal data and define that it only produces drafts.
- Build the rules: turn the checklist from the previous section into code and tests, with tax tables maintained by whoever is accountable for them.
- Test in a sandbox: use the issuer's test environment and test cases with deliberate errors. For the testing strategy, see how to test AI agents with mocks and a sandbox.
- Connect human approval: every invoice goes through a person, with approve, edit and reject buttons and a field for the reason.
- Operate with logs: record the input, draft, rules applied, human decision, API response and invoice identifier.
- Measure with a combined metric: for example, the share of drafts approved without edits and the time between order and invoice, both defined before the pilot.
- Hand over and decide: give the team documentation and access, then choose whether to expand, adjust or stop.
One caution about approval: over time, approvers tend to click without reading. Always highlight the differences and exceptions, not the whole document. If issuance affects data subjects in a significant way, it is also worth understanding what LGPD says about automated decisions and the right to review.
Illustrative scenario
Imagine a services company where one finance person currently receives invoicing requests by message and spreadsheet. This is an illustrative scenario, unrelated to any real customer.
A manager writes: "Invoice the maintenance contract for the downtown store, for this month, same as agreed." The agent identifies the contract in the system, extracts the customer and the proposal amount, and builds the draft with the standard service description. The rules layer checks the customer record, looks for a duplicate invoice for that period and compares the amount with the contract.
The rules find a difference: the amount in the message does not match the contract. The invoice does not move on to approval as it is. It goes back to the manager with a specific question. After the correction, the finance person sees the summary and approves, and the issuance service calls the API with a unique reference made of the contract and the period. If the call is repeated because of a network failure, the reference prevents a second invoice. The API response is saved in the log, and the PDF is sent to the customer through an already authorized channel.
In this flow, the model never saw the certificate, never called the issuance API and never decided a tax field on its own.
Common mistakes and how to avoid them
Some problems show up often in automations of this kind:
- Issuing twice: timeouts and retries can duplicate an invoice. Use a unique reference per invoice and check the status before resending. The idea of idempotent requests is well explained in Stripe's API documentation as an example. Confirm what your issuer offers, because each provider defines its own mechanism.
- Giving the agent a cancellation tool: cancellation and correction have their own rules and deadlines set by the applicable legislation. Leave this to a person and to your accountant.
- Letting the model calculate tax: the calculation must come from maintained and reviewed tax tables and rules, never from a generated answer.
- A service description that is too free-form: text invented by the model can produce an invoice with incorrect information. Use approved description templates and let the agent only fill in variables.
- No audit trail: without logs, nobody can later explain why an invoice went out. Record each decision and keep the approval reason with it.
- Too much data: the agent does not need all of the customer's data. Send only what is necessary and define how long logs are kept.
- Broad credentials: separate keys by environment (test and production), limit scope and have a plan to revoke them quickly.
For those who want to go deeper on the design, how Juan Carlo works with companies describes the method used in diagnostics and pilots. OWASP's list of risks for LLM applications also helps review what can go wrong when the model reads external content.
Frequently asked questions
Can you issue invoices with AI without human approval?
Technically yes, but we do not recommend it at the start. Issuing creates a tax obligation, and fixing a mistake takes work and may carry its own rules and deadlines. Start with approval on every invoice and only reduce review for simple categories, with solid rules, a track record of correct results and agreement from whoever is accountable for tax.
Does the AI agent need access to the digital certificate?
No. The certificate should stay with the issuer or with an isolated issuance service, out of the model's reach. The agent only hands over structured data for validation, and the final API call uses credentials it never sees.
Can AI decide the service code, CFOP or NCM?
It can suggest an option to make review easier, but the decision should come from a table approved by your accountant or tax team. If the model proposes something outside the table, the rule blocks it and the invoice goes to human review. That way, tax judgment stays with the people accountable for it.
How do you know whether the pilot worked?
Define the metric before you start, based on the baseline of the current process: for example, how many drafts are approved without edits, how many invoices come back because of errors and how much time passes between order and issuance. At the end, review the logs with finance and your accountant and decide whether to expand, adjust or stop.