# Cortad > Cortad provides continuous AI assurance and improvement for companies that run AI systems, as an independent third party: it tests, audits and improves them before and after deployment. Its judge model reviews every production session whole, against behavioral questions specific to the business, and before each release an automated audit tests the new version with simulated sessions drawn from real use. Cortad Enterprise adds expert-led audits, a signed attestation for every release, contractual performance guarantees and the $500,000 guarantee: every dollar spent refunded within the first 90 days. The home page as plain text: https://cortad.com/index.md ## Continuous audits of your AI systems - Cortad audits your AI against how people really use it, to assess its performance, reliability and safety, and finds what your engineers, coding agents and existing evals miss. - Automated audits run before a change ships: Cortad learns how your product is meant to be used, from your code and then from real use, and plays simulated sessions through every surface of your running system, calling your tools, each with a language, a tone, an account state and a goal. - Every audit finding comes with the sessions that show it, how often it happens and the file and line it comes from. - Release verification: every fix is replayed on the sessions it failed in and graded on sessions it was never shaped on, and Cortad says whether the behavior moved, with the counts behind it. ## Continuous evaluation of your AI systems - Cortad's judge model reviews every session across your AI systems whole, against behavioral questions specific to your business, with no sampling and no blind spots in coverage. - User personas: Cortad identifies distinct personas from real interactions, their intentions and behavioral patterns. - Performance against your standards: you define behavioral questions that reflect how your AI should perform; the judge model evaluates accuracy, task completion, safety and adherence to your rules. - The impact of your releases: Cortad measures how changes affect performance across personas, identifies regressions and traces them back to the release responsible. - Independence: Cortad writes its own behavioral questions beside yours, so the evaluation is not limited to what the team that built the system thought to test. ## Cortad Enterprise Our engineers work with yours and stand behind the results: we take an active role in improving your AI systems, establish measurable performance standards, and independently verify that those standards are met. - Dedicated engineering team: our engineers work directly in your environment to identify, resolve and prevent performance issues. - Independent attestations: documented verification of AI performance against agreed standards, backed by audit evidence. - Custom judge models: evaluation models calibrated to your business, policies and operational requirements. - Contractual accountability: agreed performance objectives, defined responsibilities and measurable results. ## The $500,000 guarantee You’re protected for your first 90 days. Not completely satisfied? We refund every dollar spent, up to half a million. Available to eligible Enterprise customers. The guarantee and its terms: https://cortad.com/guarantee ([plain text](https://cortad.com/guarantee.md)) ## Customers - Databuddy: How Databuddy improves investigation accuracy for over 3,000 businesses. 3,000+ businesses served, 96% investigation accuracy, 74% reduction in incorrect conclusions. https://cortad.com/customers/databuddy ([plain text](https://cortad.com/customers/databuddy.md)) ## Pricing - Free: 1 automated AI audit per week and continuous analysis of 5,000 messages a month, with all of Cortad. No credit card required. - Basic: $99 a month. Automated audits for one AI system in production. Continuous analysis of 25,000 messages each month, then $4 per 1,000. - All of Cortad, with: - Unlimited automated audits, subject to fair use - 1 automated audit at a time - 90 days of history and session replays - Unlimited teammates - Standard: $499 a month. Automated audits for AI systems at scale. Continuous analysis of 150,000 messages each month, then $4 per 1,000. - All of Cortad, with: - Unlimited automated audits, subject to fair use - 3 concurrent automated audits - 1 year of history and session replays - Direct Slack support - Unlimited teammates - Enterprise: priced on a call with our team, booked at https://cal.com/cortad/30min. For teams that cannot afford an AI failure. - Contractual performance guarantees - Expert-led AI audits - A signed attestation for every release, ready to share with your customers - Real-time failure detection and response - Custom evaluation models - Adversarial testing and release verification - Hands-on engineering and remediation - Dedicated AI reliability engineer - Everything in Standard, plus: - SSO and SAML authentication - Private cloud or on-premise deployment - Bring your own model provider - Custom data retention and DPA - Audit logs and role-based access - Custom usage limits and invoicing - Enterprise support SLA - Access to our Trust Center - Basic and Standard start with a 14-day free trial. A message is one reply your AI sends a real user. Automated audits never count. ## For developers Every Cortad docs page follows in full. The index of the whole site is https://cortad.com/llms.txt. --- # Cortad quickstart: your first automated audit in three steps Connect the AI app on your machine with one prompt, run an automated audit with simulated users, and see how your app behaved and who achieved their goal. You need Node 20 or later on macOS or Linux to run the command, and an AI app you can start on your machine. The app can be written in TypeScript, Python, Go, Java, C#, Ruby, PHP or Rust. ## 1. Get your command Sign up at [cortad.com](https://cortad.com/register) and open **Set up Cortad**. Press your coding agent's name. That copies a prompt with your command in it. Paste it to your agent, and it runs step 2 for you. The code in the command works for fifteen minutes. A coding agent without your prompt asks you for the command. ## 2. Run it in your app's folder The command you copied ends at your code. Add `--` and the command that starts your app, exactly as you type it yourself, such as `npm run dev`, `uvicorn main:app` or `go run .`. Run it in the terminal you start your app from, so your app has its own keys and settings. ```sh npx cortad@2.1.1 -- npm run dev ``` Cortad starts your app with your command and connects it. Nothing in your app's folder is changed. When the terminal says `Cortad is watching your app`, it is connected. Leave the command running. A coding agent starts it in the background and reads its output. If it says `your app is not running`, your start command failed, and the lines above that one are your app's own output. Fix it and save a file: Cortad starts your app again by itself. ## 3. Start the first automated audit Cortad sends each AI feature in your app a test message. In under a minute, **Start audit** is ready on **Set up Cortad**, with its price beside it. Start your app against a staging copy of its database first, then press it: the press is your yes to test conversations using your app as it is, writing where your app writes. The first automated audit plays four simulated users for each AI feature that answered. Your coding agent starts later ones with [`test`](https://cortad.com/docs/tools.md#test). While it plays, the card asks how many of your users' recent messages Cortad should analyze: 500, 1,000 or 2,500. From them Cortad learns your [personas](https://cortad.com/docs/how-it-works.md#personas): who your users are and how each group behaves. The second automated audit plays new simulated users who behave like each persona. When an automated audit ends, ask your coding agent how your app behaved. [Read the behavior](https://cortad.com/docs/fix-a-finding.md) shows what comes back. --- # How Cortad audits your AI How Cortad learns your personas, what an automated audit does with your app, what every reply is asked, and what your coding agent gets back and cannot change. Cortad audits the AI in your app as an independent third party. Before a change ships, an automated audit plays simulated users against your app on your own machine, with its real prompts, tools, retrieval and database. Once your live app is connected, every session is asked the same behavioral questions. Each audit finding shows the conversations behind it and the line of code it comes from, and your coding agent is one way to act on it. ## Personas A persona is what Cortad has learned about a group of your users who come to your app for the same thing. Cortad learns it from your users' messages: the ones you bring in during setup, then each new one from your live app. Each persona carries: - Who its users are, in your app's own terms, such as grade, country and subject for a tutor. - What they want to do, and how they behave: how much they write, and how often they push back or ask for a person. - How well your app serves them, and what goes wrong for them, with the conversations behind it. A persona whose users misuse your app is kept and marked as misuse. ## What it analyzes in your code - Rules: sentences your prompts already state, such as "Never state a refund policy the product does not publish." Each one keeps its file and line. - Journeys: what people use your product to do, such as a billing question or help with homework. - Endpoints: each place your app's AI answers. Before your personas exist, the first automated audit's users are written from these. Your coding agent lists any of them with [`status`](https://cortad.com/docs/tools.md#status). ## What an automated audit does A simulated user written from a persona is a new person who behaves the way that persona's users behave. It is not a replay: each one has a new conversation with your app through your real endpoints, signed in the way a user is. Your app answers with its own model, on its own key. Where the AI in your app is not a chat, an automated audit can instead build a copy of your app's data from its seed, plant problems whose answers Cortad knows, and score what your app finds. Every reply is asked behavioral questions: your app's own rules, its journeys, and a set of engineering standards. Each answer is about what that reply did for that user, and says whether code or a model decided it. A question that only describes behavior is counted, never called failed. ## What comes back For each persona: how many of its simulated users achieved their goal, what your app did well with them, where it gave way, and the conversations that show each. Then your app's habits across personas. Last, where each problem comes from in your code, with the file and line. [Read the behavior](https://cortad.com/docs/fix-a-finding.md#read-how-your-app-behaved) shows one persona and how to read it. ## Your coding agent runs the tests and cannot edit them Your coding agent can start an automated audit and read its findings. Cortad stores the conversations and the questions, out of your coding agent's reach. Some conversations are saved to test a fix. Your coding agent never reads them, and a fix is graded on those too. ## The same questions in production Once your live app is connected, with [the Node SDK](https://cortad.com/docs/production-node.md), [the Python SDK](https://cortad.com/docs/production-python.md) or [one signed request from any language](https://cortad.com/docs/send-conversations.md), and Cortad is analyzing its message text, each user is placed in a persona and their conversations are asked the same questions. That is how a change made here is checked against real users. --- # The tools Cortad gives your coding agent What status, test, behavior, search, verify, connect and tell do, when your coding agent calls each one, and what it learns about how your app behaved. After the [connect command](https://cortad.com/docs/quickstart.md), Claude Code, Codex, Cursor and Copilot have these tools. After an automated audit, a coding agent reads [`behavior`](#behavior). What it can and cannot change is on [How it works](https://cortad.com/docs/how-it-works.md#your-coding-agent-runs-the-tests-and-cannot-edit-them). ## `status` What to know about this app right now. Asked for nothing, it says where things stand: the connection, which AI features answer, an audit playing or just finished, your live app going wrong, and what waits on you. Asked about one thing, it gives that in full: | About | What comes back | | --- | --- | | `repository` | What Cortad found in your code, how each endpoint answered, and your plan | | `run` | Where an audit or a verify stands | | `production` | Your live app in numbers, and what is wrong in it now | | `outcomes` | What your app counts as a good ending, and how often it is reached | | `warehouse` | A question over your live app's own events | | `users` | Who uses your live app and how, before your agent edits what they use: their personas, conversations, the behavioral questions and their answers, visits, and what people did after each answer. Your agent gets ready answers or asks its own question of the same tables. Users are numbers, never names or emails, and no conversation's words are in it | It starts nothing. A coding agent calls it at the start of a session, right after a connect, and before a commit that changes prompts, tools, models or retrieval. ## `test` The one call after a change. Your coding agent says what it built in a sentence. Simulated users then talk to your app on your machine, and every reply is asked its behavioral questions. - `features` names the AI features to test, where your app has more than one, and is kept until another test names a different one. Sent alone, it records the choice and starts nothing. - `conversations` sets the most conversations an audit may play, for a first look that spends less on your model key. - `endpoints` sends one test request to those endpoints and plays no conversations, to try a failed endpoint again. `test` answers at once with what it started; [`status`](#status) about `run` follows it. Some endpoints need a signed-in user. Cortad can make one test account through your app's own sign-up, only with your yes. Once you give it, your coding agent records it in a shell: ```sh npx cortad@2.1.1 test --account make ``` ## `behavior` How your app behaved with its users. Asked for nothing, it reads the latest finished audit, top down: 1. How many simulated users, of how many personas, achieved their goal. 2. Each persona, largest first: who its users are, how they behave, what your app did well with them and where it gave way, each with how often and the conversations that show it. 3. Your app's habits across personas: what it does well, where it gives way, and the habit behind it. 4. Last, where each problem comes from in your code, with the id `verify` takes. | Ask with | What comes back | | --- | --- | | `at` | Another point: an audit's id, a commit an audit played on, or `production` | | `persona` | One persona in full, with its conversations | | `against` | What got better, worse, new or gone for each persona, compared with `previous`, `production`, an audit's id or a commit. Compared with production, it also says where simulated users behave unlike your real ones | | `history` | Every audit by commit and every day of production, newest first, with what changed since the one before | [Read the behavior](https://cortad.com/docs/fix-a-finding.md) shows one persona as it prints. ## `search` Finds conversations by what they mean, across audits and production: who asked, what, how it ended and what your app said, with how many of all conversations are about it. `where` keeps it to `simulation`, `production` or one audit's id, `persona` to one persona, and `limit` sets how many come back. ## `verify` Whether a behavior moved after a fix. It takes a problem's id from `behavior`, such as `finding:1`. [Read the behavior](https://cortad.com/docs/fix-a-finding.md#replay-the-conversations) walks through it. ## `connect` Sets up your live app one step at a time, the same as `npx -y cortad@2.1.1 intelligence` in a terminal. It brings in the recent messages you chose on **Set up Cortad**, so Cortad can learn your personas from them, and writes both keys into your git-ignored env file. Then it prints the change for your coding agent to make: the SDK for Node or Python, or one signed request for any other language, and the page tag. It edits no code, and asks before it adds the key to your production host. ## `tell` One of five things in a call: - A note to the Cortad team about Cortad itself: a result that read wrong, something no tool gave, or what worked. - That a problem's question misjudges your app, with the problem's id, the reason and, if your agent has one, a better wording. The problem and its rate stay as they are, and the note goes to the account owner. - What your app counts as a good ending, found in its code, such as a sign-up route or a checkout. You approve it in the browser before it counts. - Behavioral questions your live app's answers should be asked, where conversations went badly with no question failing. You say yes or no to each on **Behavioral questions**. - An address of yours that should receive each incident in your live app, as signed JSON. Nothing about an audit or its questions changes. --- # Read how your app behaved, then change it How to read an automated audit persona by persona, choose one change from what its users ran into, and replay their conversations to see if the behavior moved. Your coding agent reports first, and edits nothing until you say so. ## Read how your app behaved When an automated audit ends, your coding agent calls [`behavior`](https://cortad.com/docs/tools.md#behavior) and tells you how your app behaved with its users: who they were, what they wanted, who achieved their goal and why the others did not. Then what it would change, and why that follows. This is one persona, and the line in the code its problem comes from, as `behavior` prints them: ```text 2. Asks where their order is: 4 simulated users, 31 conversations. Who they are: signed in 75%, guest 25%. They send 2 messages a conversation, with a first message of about 9 words. They achieved their goal in 19 of 31 conversations. - Those signed in achieved their goal in 11 of 23 conversations; guests in 8 of 8. Shown in 41c2e0b7, 5d19a3f0, 9e07c2b1. What the app did well with them: - The reply gives the order's status once it has the order: in 19 of 19 conversations, 100% (83% to 100%). Where it gave way: - The reply asks for an order number the account already has: in 12 of 23 conversations, 52% (33% to 71%). (finding:1) Shown in 41c2e0b7, 5d19a3f0, 9e07c2b1 and 9 more. In 41c2e0b7: The user: "Where's my order?" Reply 1: "Happy to help! What's your order number?" Where each problem comes from in the code: - src/prompts/support.ts:42 The reply asks for an order number the account already has: 12 conversations of "Asks where their order is". Verify with findingId "finding:1" replays them after a fix. ``` - The first line is the persona: what its users want, and how many simulated users played it. - `Who they are` is in your app's own terms. A split such as signed in and guest shows which users miss their goal. - `52% (33% to 71%)` is the rate, and its likely range. Every rate carries both. - `Shown in` names the conversations behind a line, and one of them is quoted. - `finding:1` is the id `verify` takes, and the line in the code is where the change belongs. ## Compare with before `behavior` with `against` says what got better, worse, new or gone for each persona since another point: `previous`, a commit, or `production`. Compared with production, it also says where simulated users behave unlike your real ones. A rate counts as moved only where the range of the difference leaves out zero. With `history`, it lists every automated audit by commit and every day of production, newest first. ## Make one change Choose what to change first. On your go, your coding agent makes one change, near the line in the code `behavior` names. ## Replay the conversations Your coding agent calls [`verify`](https://cortad.com/docs/tools.md#verify) with the problem's id, the `finding:1` beside it. ```sh npx cortad@2.1.1 verify finding:1 ``` Cortad restarts your app when its code changed, then replays the conversations the problem happened in, word for word, against the saved edit. It also plays the [conversations saved to test a fix](https://cortad.com/docs/how-it-works.md#your-coding-agent-runs-the-tests-and-cannot-edit-them), once, and reports them separately. ## Read the answer | The verify says | What to do | | --- | --- | | Worse on the saved conversations | Undo the change, whatever its own conversations did, and aim the next one at the behavior the question asks about. | | Gone | Keep the change. | | Less often, or stayed | Read the replayed conversations beside what they said before the change, and decide what to change next. | | Not decided yet | It says how many more clean replays would decide. Keep the change, and call `verify` again. | Replies your app refused or failed on the replay come first, because a change that broke the endpoint shows there. Then run [`test`](https://cortad.com/docs/tools.md#test) again, and read `behavior` against `previous` to see how every persona moved. ## When a question misjudges your app A question can measure something your app was not built to do. Your coding agent records that with [`tell`](https://cortad.com/docs/tools.md#tell). --- # Cortad commands and flags The Cortad commands you type in a shell, the flags that change how your app connects, and the two commands that make it part of your repository. The commands below run in a shell, in your app's folder. `status` prints what the [`status`](https://cortad.com/docs/tools.md#status) tool gives when asked about `repository`. ## Connect your app ```sh npx cortad@2.1.1 -- npm run dev ``` `` is the code in the prompt you copy on **Set up Cortad**. A folder that connected before reconnects without one. After `--` goes the command that starts your app in any language, such as `python app.py`, `go run .` or `dotnet run`. | Flag | What it does | | --- | --- | | `-- ` | How your app starts. Everything after `--` is run as you typed it. | | `--start ""` | The same, as one quoted flag. | | `--port 3000` | Uses an app that is already running, as it is. Cortad sees its replies and not the calls it makes to its model. | | `--port 3000 -- ` | Starts an app in a container and watches the port it publishes. The model setting to give the container is printed. | | `--verbose` | Prints your app's own output. | | `--explain` | Lists every file a connect would send and why each was picked. It connects to nothing and writes nothing. | | `--samples` | Opens your app's search and vector stores for samples of their content, so simulated users ask about it. Without it, none is opened. | | `--agent-picks` | Sends no file by itself. Your coding agent picks the files and sends them with `send`, below. | ## Choose the files yourself ```sh npx cortad@2.1.1 --agent-picks -- npm run dev npx cortad@2.1.1 send src/agent.ts src/prompts/system.ts npx cortad@2.1.1 send --yes src/agent.ts src/prompts/system.ts ``` `send` shows the files that would go and which of Cortad's needs each one covers: prompts, model calls, the routes that reach them, tools and evals. `send --yes` sends them, and a later `send` adds to the set. Env files, keys, files git ignores and data files are refused. ## Run and read from a shell ```sh npx cortad@2.1.1 status npx cortad@2.1.1 test "" npx cortad@2.1.1 behavior npx cortad@2.1.1 verify npx cortad@2.1.1 wait ``` - `status rules`, `status journeys` and `status endpoints` list in full the rules, journeys and endpoints Cortad found in your code. - `test --conversations 10 ""` starts an automated audit capped at ten conversations. `test --features "POST /api/chat"` records which AI features to test and starts nothing. - `behavior` prints how your app behaved in the latest automated audit, persona by persona. `behavior ` reads another one, and `--persona ""`, `--against previous` and `--history` do what the [`behavior`](https://cortad.com/docs/tools.md#behavior) tool's `persona`, `against` and `history` do. - `verify` takes the id `behavior` names, such as `finding:1`. - `wait` returns when the next automated audit or verify ends, with what it found. A coding agent starts it in the background so the end of an automated audit wakes it. An automated audit needs your app up. If nothing on your machine is running it, the command starts it with the start command it kept, and stops it ten minutes after the last automated audit. ## Make Cortad part of your repository This step is optional. ```sh npx cortad@2.1.1 stick npx cortad@2.1.1 unstick ``` `stick` adds one line to `AGENTS.md`, `CLAUDE.md`, the Cursor rules and `.github/copilot-instructions.md`, and two hooks for Claude Code and Codex. The first hook names the prompt and tool files you changed since the last automated audit, and both tell your coding agent what is new since its last call, such as an automated audit that ended. `unstick` takes them out. Both commands print every file they change. Neither touches git. --- # Connect a live Node app to Cortad Add @cortad/sdk to a Node app with one line, choose whether message text is sent, and see every production conversation as it happens. One line where your app starts connects it to Cortad. Each user is placed in one of your personas, and their conversations are [asked the same questions as your automated audits](https://cortad.com/docs/how-it-works.md#the-same-questions-in-production). ## Get your key Copy the setup from **Your users** into your coding agent, or run `npx -y cortad@2.1.1 intelligence` in your app's folder. It writes `CORTAD_INGEST_KEY` into your git-ignored env file and asks before it adds the key to your production host. Where it cannot, put `CORTAD_INGEST_KEY` in your production environment the way you add any secret. ## Install The SDK needs Node 20.16 or later, and works with `require`, `import` and TypeScript. ```sh npm i @cortad/sdk ``` Add one line where your app starts: ```js import { cortad } from "@cortad/sdk"; cortad({ key: process.env.CORTAD_INGEST_KEY, captureContent: true }).install(); ``` That is the install. Every call your process makes through `fetch` to OpenAI, Anthropic, Fireworks, Groq, OpenRouter or Google is observed, streamed replies included. A conversation is recognised by the system prompt and first user message it keeps resending, so nothing has to be wrapped. ## Choose whether message text leaves Message text stays in your process unless you pass `captureContent: true`. ## Say which conversation a call belongs to When your app keeps its own conversation id, wrap each conversation in `run` with that id, and say what the reply was built from. Use this in place of the install line, so the client that observes the calls is the one that wraps them: ```js const cortadClient = cortad({ key: process.env.CORTAD_INGEST_KEY, captureContent: true }); cortadClient.install(); await cortadClient.run({ id: conversationId, user: customerId }, async () => { const docs = await retriever.invoke(question); cortadClient.context({ passages: docs.map((d) => ({ id: d.id, text: d.pageContent, score: d.score })) }); const reply = await model.invoke(question); cortadClient.outcome("resolved"); }); ``` ## Sent as each conversation ends When the work inside `run` ends, its conversation is sent before `run` returns, waiting at most two seconds, because a serverless host freezes the process as soon as the response is out. If a send has taken longer than two seconds, later conversations go on without waiting until one gets through. ```js export async function POST(request) { const { id, messages } = await request.json(); return cortadClient.run({ id }, async () => Response.json(await openai.chat.completions.create({ model: "gpt-4o", messages }))); } ``` ## Hand over a reply the SDK cannot see Inside `run`, a chat request to any address is captured, so Azure, Vertex, a gateway or a model on your own machine need nothing more. A reply that never goes through `fetch` or `node:http`, such as one over gRPC or a stream you finish in a callback, you hand over yourself, inside `run`. `messages` is what the model was given, as `{ role, content }`, and `answer` is what it said; the rest is optional. ```js await cortadClient.run({ id: conversationId }, async () => { const text = await callModelOverGrpc(messages); cortadClient.reply({ messages, answer: text, model: "claude-sonnet-4", tokens: { in: 120, out: 40 }, ms: 812 }); }); ``` ## When only some calls answer a person Your app may also make model calls that are not replies to a person: choosing a route, rewriting a query, naming a chat. Pass `onlyRun: true` and wrap the answering call alone. Only calls inside `run` are then observed. ## Next.js The line goes in `instrumentation.ts`, behind `process.env.NEXT_RUNTIME === "nodejs"`. On the edge runtime the SDK switches itself off and your app keeps running. ## See it arrive Open **Your users** in the Cortad app. They appear there as their conversations arrive. For what people did around each answer, add [the page tag](https://cortad.com/docs/page-tag.md). For a Python app, see [the Python SDK](https://cortad.com/docs/production-python.md). An app in any other language sends [one signed request](https://cortad.com/docs/send-conversations.md) after each reply. --- # Connect a live Python app to Cortad Add the cortad package from PyPI to a Python app with one line where it starts, and choose whether message text is sent to Cortad. The Python SDK is one file that uses only the standard library. ## Install Your key comes from the same setup as for Node: `npx -y cortad@2.1.1 intelligence` in your app's folder, or your coding agent's [`connect`](https://cortad.com/docs/tools.md#connect) tool. The SDK needs Python 3.10 or later. ```sh pip install cortad ``` Add one line where your app starts: ```python import os from cortad import cortad cortad(key=os.environ["CORTAD_INGEST_KEY"], capture_content=True).install() ``` Every call your process makes through httpx or requests to the providers [the Node SDK names](https://cortad.com/docs/production-node.md#install) is observed. ## Choose whether message text leaves Message text stays in your process unless you pass `capture_content=True`. ## Say which conversation a call belongs to When your app keeps its own conversation id, wrap each conversation in `run` with that id. Use this in place of the install line, so each call is observed once: ```python cortad_client = cortad(key=os.environ["CORTAD_INGEST_KEY"], capture_content=True) cortad_client.install() with cortad_client.run(conversation_id, user=customer_id): answer = client.chat.completions.create(...) cortad_client.outcome("resolved") ``` The SDK sends in batches every five seconds and when your process exits. `cortad_client.flush()` sends at once. ## Sent as each conversation ends Leaving `run` sends its conversation, waiting at most two seconds, because a serverless host freezes the process as soon as the response is out. In async code use `async with`, which waits without holding the event loop. If a send has taken longer than two seconds, later conversations go on without waiting until one gets through. ```python async def chat(conversation_id, messages): async with cortad_client.run(conversation_id): return await client.chat.completions.create(model="gpt-4o", messages=messages) ``` ## Hand over a reply the SDK cannot see Inside `run`, a chat request to any address is captured, so Azure, Vertex, a gateway or a model on your own machine need nothing more. A reply that never goes through httpx or requests, such as Bedrock through boto3 or a stream you finish in a callback, you hand over yourself, inside `run`. `messages` is what the model was given, as `{role, content}`, and `answer` is what it said; the rest is optional. ```python with cortad_client.run(conversation_id): text = call_bedrock(messages) cortad_client.reply(messages=messages, answer=text, model="claude-sonnet-4", tokens={"in": 120, "out": 40}, ms=812) ``` ## When only some calls answer a person Your app may also make model calls that are not replies to a person: choosing a route, rewriting a query, naming a chat. Pass `only_run=True` and wrap the answering call alone. Only calls inside `run` are then observed. An app in another language sends [one signed request](https://cortad.com/docs/send-conversations.md) after each reply. --- # Add the Cortad page tag to your site Add one script tag to your pages to see what people did around each answer your AI gave, with a recording of what they saw. ## Add the tag Put it once in the page every person uses. ```html ``` The value is `CORTAD_PUBLIC_KEY`, which the setup on **Your users** writes into your env file beside your SDK key and prints in the tag line for your page. The key is public and carries no secret. Name the addresses your site answers on in Settings, under **Where your pages send from**, so a page on any other address is refused. If your app's backend answers on another host than the page, name it on the tag with `data-backends="api.example.com"`, or under **Backend hosts** in Settings. ## What you get - What the person did around each request to your app, such as clicking the same spot three times within a second, or clicking something that did nothing. - A recording of what they saw. ## Keep something out Recording is on from the moment the tag is in. | To do this | What happens | | --- | --- | | Add the class `cortad-no-capture` | The element is an empty box of its size in a recording. | | Add the class `cortad-mask` | The element's text is masked in a recording. | | Add the class `cortad-sensitive` | A click on the element sends none of its words, labels or address. A click on an element inside it sends that element's own words, so the class goes on the element that carries them. | | Turn on **Mask all text** in Settings | Every word on the page becomes stars in the recording. The layout stays. | | Turn off **Record what people see** in Settings | Nothing is recorded. | ## Say who the person is Once your page knows who is signed in, say so: ```js window.cortad.identify("your own id for them"); ``` The visit they are on, and every later visit from that browser, is then theirs. On sign-out, for a machine more than one person uses: ```js window.cortad.forget(); ``` A page your server renders for a signed-in person can name them on the tag instead, with `data-who`. ## Show who they are **Your users** shows each user as a number, User 37, in the order they first came. To see who they are instead, pass a label as you identify them: `window.cortad.identify(user.id, { label: user.email })`, or on the server `cortadClient.run({ id, user: customerId, label: customer.email }, ...)` (`label=` in Python). The label can be an email, a name or your own id for them. Only people on your Cortad account see it; your coding agent sees the number. ## Ask for consent first A page that must ask first adds `data-opt-out-by-default` to the tag, and calls one of these when the person answers: ```js window.cortad.optIn(); window.cortad.optOut(); ``` Until a yes, the tag sends nothing the person does and records nothing. Recording starts on the first page loaded after the yes. With `data-respect-dnt`, the tag does nothing in a browser that has Do Not Track or Global Privacy Control on. ## Mark a good ending When the person reaches what your product is for, such as a checkout or a booking, say so: ```js window.cortad.outcome("checkout"); ``` --- # Send conversations from any language Send each conversation to Cortad over HTTPS after every reply, signed with your key, from Go, Ruby, PHP, Java, C#, Rust, curl or an edge function. Send your app's conversations to Cortad with one HTTPS request after each reply. This is how an app in Go, Java, C#, Ruby, PHP, Rust or any other language without an SDK connects, and your coding agent writes it into your app during setup. It also fits an app on an edge runtime, or one that answers people through a relay such as a WhatsApp, Slack or voice webhook. A Node or Python app can use [the Node SDK](https://cortad.com/docs/production-node.md) or [the Python SDK](https://cortad.com/docs/production-python.md) instead. ## Get your key Your key, `CORTAD_INGEST_KEY`, comes from the same setup as the SDKs: see [Get your key](https://cortad.com/docs/production-node.md#get-your-key). It starts with `ct_ing_`. Every request is signed with it, so keep it on your server: never in a browser, and never inside a mobile app. ## Send after each reply After each reply your app sends, POST the whole conversation so far, oldest message first, to `https://cortad.com/api/v1/conversations`. A copy with as many messages as one you already sent adds nothing, so a retry is safe. A copy with more adds its newest reply. Each conversation sent here is shown on **Conversations** as a real person's, so send from production only. ## The body ```json { "id": "conv_8f2c", "user": "20668f17abcff6a999719c346b4fa97b4071069522ceac09fef6978accadbaf2", "country": "SA", "channel": "whatsapp", "messages": [ { "role": "user", "text": "Where is my order?", "at": "2026-11-08T14:02:11Z" }, { "role": "assistant", "text": "It ships Monday.", "at": "2026-11-08T14:02:13Z" } ] } ``` | Field | What it is | | --- | --- | | `id` | Your own id for the conversation, 1 to 200 characters. Send the same id every time. | | `user` | Optional. The person, as the SHA-256 of `:user:` in lowercase hex. The SDKs hash a user the same way, so a person sent both ways is one person. | | `country` | Optional. Where the person is, as a two-letter ISO 3166 code in capitals, such as `SA`. | | `channel` | Optional. How they reached your app: `web`, `whatsapp`, `slack`, `discord`, `telegram`, `voice`, `email`, `sms` or `other`. | | `messages` | 1 to 200 messages, oldest first. Each has a `role` of `user` or `assistant`, a `text` of 1 to 8,000 characters, and `at`: when it was sent, with its zone. A time later than now is refused. | Any other field is refused, and a body is at most 1 MiB. ## Sign the request The key itself never travels. Each request carries its first 15 characters and a signature made with it: 1. Serialize the body once. Those exact bytes are what you hash and what you send. 2. `secret` is the SHA-256 of your whole key, as lowercase hex. That hex text is the HMAC key. 3. `timestamp` is the time now in milliseconds since 1970, as digits. It must be within five minutes of Cortad's clock. 4. `nonce` is 16 random bytes as lowercase hex. Make a new one for every request, a retry included. 5. `signature` is the HMAC-SHA-256 of `v1...`, keyed with `secret`, as lowercase hex. Send these headers with the body: | Header | Value | | --- | --- | | `content-type` | `application/json` | | `x-cortad-key` | The first 15 characters of your key | | `x-cortad-timestamp` | `timestamp` | | `x-cortad-nonce` | `nonce` | | `x-cortad-signature` | `v1=` followed by `signature` | ## What comes back | Status | What it means | | --- | --- | | `202` | Accepted: `{"added": true}`, or `{"added": false}` when a copy with this many messages was already sent. | | `400` | The body broke a rule above. `error` says which rule and where. | | `401` | The key id, the timestamp or the signature is wrong. Most often the timestamp is in seconds, or the body was serialized again after it was signed. | | `409` | This nonce was already used. Sign again with a new one. | | `413` | The body is over 1 MiB. | | `429` | Too many requests from your address. Wait the seconds in `Retry-After`, then sign again and send. | ## The same send in each language Each example sends the conversation above, without `user`, `country` and `channel`, and prints what came back. ### curl and openssl ```bash KEY="$CORTAD_INGEST_KEY" BODY='{"id":"conv_8f2c","messages":[{"role":"user","text":"Where is my order?","at":"2026-11-08T14:02:11Z"},{"role":"assistant","text":"It ships Monday.","at":"2026-11-08T14:02:13Z"}]}' SECRET=$(printf %s "$KEY" | openssl dgst -sha256 -r | cut -d' ' -f1) TIMESTAMP=$(( $(date +%s) * 1000 )) NONCE=$(openssl rand -hex 16) BODY_HASH=$(printf %s "$BODY" | openssl dgst -sha256 -r | cut -d' ' -f1) SIGNATURE=$(printf %s "v1.$TIMESTAMP.$NONCE.$BODY_HASH" | openssl dgst -sha256 -hmac "$SECRET" -r | cut -d' ' -f1) curl -sS https://cortad.com/api/v1/conversations \ -H 'content-type: application/json' \ -H "x-cortad-key: ${KEY:0:15}" \ -H "x-cortad-timestamp: $TIMESTAMP" \ -H "x-cortad-nonce: $NONCE" \ -H "x-cortad-signature: v1=$SIGNATURE" \ --data-binary "$BODY" \ --write-out ' %{http_code}\n' ``` ### Go ```go package main import ( "bytes" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "os" "strconv" "time" ) type Message struct { Role string `json:"role"` Text string `json:"text"` At string `json:"at"` } func sha256Hex(b []byte) string { sum := sha256.Sum256(b) return hex.EncodeToString(sum[:]) } func main() { key := os.Getenv("CORTAD_INGEST_KEY") body, err := json.Marshal(map[string]any{ "id": "conv_8f2c", "messages": []Message{ {Role: "user", Text: "Where is my order?", At: "2026-11-08T14:02:11Z"}, {Role: "assistant", Text: "It ships Monday.", At: "2026-11-08T14:02:13Z"}, }, }) if err != nil { panic(err) } random := make([]byte, 16) if _, err := rand.Read(random); err != nil { panic(err) } nonce := hex.EncodeToString(random) timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10) mac := hmac.New(sha256.New, []byte(sha256Hex([]byte(key)))) mac.Write([]byte("v1." + timestamp + "." + nonce + "." + sha256Hex(body))) req, err := http.NewRequest("POST", "https://cortad.com/api/v1/conversations", bytes.NewReader(body)) if err != nil { panic(err) } req.Header.Set("content-type", "application/json") req.Header.Set("x-cortad-key", key[:15]) req.Header.Set("x-cortad-timestamp", timestamp) req.Header.Set("x-cortad-nonce", nonce) req.Header.Set("x-cortad-signature", "v1="+hex.EncodeToString(mac.Sum(nil))) res, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer res.Body.Close() answer, _ := io.ReadAll(res.Body) fmt.Println(res.StatusCode, string(answer)) } ``` ### Ruby ```ruby require "json" require "net/http" require "openssl" require "securerandom" key = ENV.fetch("CORTAD_INGEST_KEY") body = JSON.generate( id: "conv_8f2c", messages: [ { role: "user", text: "Where is my order?", at: "2026-11-08T14:02:11Z" }, { role: "assistant", text: "It ships Monday.", at: "2026-11-08T14:02:13Z" } ] ) secret = OpenSSL::Digest::SHA256.hexdigest(key) timestamp = (Time.now.to_f * 1000).to_i.to_s nonce = SecureRandom.hex(16) signature = OpenSSL::HMAC.hexdigest("SHA256", secret, "v1.#{timestamp}.#{nonce}.#{OpenSSL::Digest::SHA256.hexdigest(body)}") response = Net::HTTP.post( URI("https://cortad.com/api/v1/conversations"), body, "content-type" => "application/json", "x-cortad-key" => key[0, 15], "x-cortad-timestamp" => timestamp, "x-cortad-nonce" => nonce, "x-cortad-signature" => "v1=#{signature}" ) puts "#{response.code} #{response.body}" ``` ### PHP ```php 'conv_8f2c', 'messages' => [ ['role' => 'user', 'text' => 'Where is my order?', 'at' => '2026-11-08T14:02:11Z'], ['role' => 'assistant', 'text' => 'It ships Monday.', 'at' => '2026-11-08T14:02:13Z'], ], ]); $timestamp = (string) (int) (microtime(true) * 1000); $nonce = bin2hex(random_bytes(16)); $signature = hash_hmac('sha256', "v1.$timestamp.$nonce." . hash('sha256', $body), hash('sha256', $key)); $request = curl_init('https://cortad.com/api/v1/conversations'); curl_setopt_array($request, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'content-type: application/json', 'x-cortad-key: ' . substr($key, 0, 15), "x-cortad-timestamp: $timestamp", "x-cortad-nonce: $nonce", "x-cortad-signature: v1=$signature", ], ]); $answer = curl_exec($request); echo curl_getinfo($request, CURLINFO_RESPONSE_CODE), ' ', $answer, "\n"; ``` ### Java Java 17 or later. The standard library has no JSON writer, so the body is written out here; in your app, write it with your JSON library. ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.HexFormat; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class SendConversation { static String sha256Hex(byte[] bytes) throws Exception { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } public static void main(String[] args) throws Exception { String key = System.getenv("CORTAD_INGEST_KEY"); byte[] body = """ {"id":"conv_8f2c","messages":[ {"role":"user","text":"Where is my order?","at":"2026-11-08T14:02:11Z"}, {"role":"assistant","text":"It ships Monday.","at":"2026-11-08T14:02:13Z"}]} """.getBytes(StandardCharsets.UTF_8); String timestamp = Long.toString(System.currentTimeMillis()); byte[] random = new byte[16]; new SecureRandom().nextBytes(random); String nonce = HexFormat.of().formatHex(random); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(sha256Hex(key.getBytes(StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8), "HmacSHA256")); String signed = "v1." + timestamp + "." + nonce + "." + sha256Hex(body); String signature = HexFormat.of().formatHex(mac.doFinal(signed.getBytes(StandardCharsets.UTF_8))); HttpRequest request = HttpRequest.newBuilder(URI.create("https://cortad.com/api/v1/conversations")) .header("content-type", "application/json") .header("x-cortad-key", key.substring(0, 15)) .header("x-cortad-timestamp", timestamp) .header("x-cortad-nonce", nonce) .header("x-cortad-signature", "v1=" + signature) .POST(HttpRequest.BodyPublishers.ofByteArray(body)) .build(); HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` ### C# A .NET 8 console app. ```csharp using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Text.Json; static string Hex(byte[] bytes) => Convert.ToHexString(bytes).ToLowerInvariant(); var key = Environment.GetEnvironmentVariable("CORTAD_INGEST_KEY")!; var body = JsonSerializer.SerializeToUtf8Bytes(new { id = "conv_8f2c", messages = new[] { new { role = "user", text = "Where is my order?", at = "2026-11-08T14:02:11Z" }, new { role = "assistant", text = "It ships Monday.", at = "2026-11-08T14:02:13Z" }, }, }); var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(); var nonce = Hex(RandomNumberGenerator.GetBytes(16)); var secret = Hex(SHA256.HashData(Encoding.UTF8.GetBytes(key))); var signature = Hex(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes($"v1.{timestamp}.{nonce}.{Hex(SHA256.HashData(body))}"))); using var request = new HttpRequestMessage(HttpMethod.Post, "https://cortad.com/api/v1/conversations") { Content = new ByteArrayContent(body) }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); request.Headers.Add("x-cortad-key", key[..15]); request.Headers.Add("x-cortad-timestamp", timestamp); request.Headers.Add("x-cortad-nonce", nonce); request.Headers.Add("x-cortad-signature", $"v1={signature}"); using var client = new HttpClient(); using var response = await client.SendAsync(request); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` ### Rust The standard library has no SHA-256 or HTTP client, so this uses these crates in `Cargo.toml`: ```toml [dependencies] hex = "0.4" hmac = "0.12" rand = "0.8" reqwest = { version = "0.12", features = ["blocking"] } serde_json = "1" sha2 = "0.10" ``` ```rust use hmac::{Hmac, Mac}; use sha2::{Digest, Sha256}; use std::time::{SystemTime, UNIX_EPOCH}; fn main() -> Result<(), Box> { let key = std::env::var("CORTAD_INGEST_KEY")?; let body = serde_json::json!({ "id": "conv_8f2c", "messages": [ { "role": "user", "text": "Where is my order?", "at": "2026-11-08T14:02:11Z" }, { "role": "assistant", "text": "It ships Monday.", "at": "2026-11-08T14:02:13Z" } ] }) .to_string(); let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis().to_string(); let nonce = hex::encode(rand::random::<[u8; 16]>()); let secret = hex::encode(Sha256::digest(key.as_bytes())); let mut mac = Hmac::::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length"); mac.update(format!("v1.{timestamp}.{nonce}.{}", hex::encode(Sha256::digest(body.as_bytes()))).as_bytes()); let signature = hex::encode(mac.finalize().into_bytes()); let response = reqwest::blocking::Client::new() .post("https://cortad.com/api/v1/conversations") .header("content-type", "application/json") .header("x-cortad-key", &key[..15]) .header("x-cortad-timestamp", ×tamp) .header("x-cortad-nonce", &nonce) .header("x-cortad-signature", format!("v1={signature}")) .body(body) .send()?; let status = response.status(); println!("{status} {}", response.text()?); Ok(()) } ``` ### Edge runtimes Web Crypto and `fetch` are all it takes on Cloudflare Workers, Vercel Edge Functions and Supabase Edge Functions. Call it from your handler through the platform's `waitUntil`, so the reply never waits on it: `ctx.waitUntil` on Cloudflare, `waitUntil` from `@vercel/functions` on Vercel, `EdgeRuntime.waitUntil` on Supabase. ```js const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join(""); const sha256Hex = async (text) => hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))); export async function sendConversation(key, conversation) { const body = JSON.stringify(conversation); const timestamp = String(Date.now()); const nonce = hex(crypto.getRandomValues(new Uint8Array(16))); const secret = await crypto.subtle.importKey("raw", new TextEncoder().encode(await sha256Hex(key)), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const signature = hex(await crypto.subtle.sign("HMAC", secret, new TextEncoder().encode(`v1.${timestamp}.${nonce}.${await sha256Hex(body)}`))); return fetch("https://cortad.com/api/v1/conversations", { method: "POST", headers: { "content-type": "application/json", "x-cortad-key": key.slice(0, 15), "x-cortad-timestamp": timestamp, "x-cortad-nonce": nonce, "x-cortad-signature": `v1=${signature}`, }, body, }); } ``` On Cloudflare Workers: ```js export default { async fetch(request, env, ctx) { const messages = [ { role: "user", text: "Where is my order?", at: "2026-11-08T14:02:11Z" }, { role: "assistant", text: "It ships Monday.", at: "2026-11-08T14:02:13Z" }, ]; ctx.waitUntil(sendConversation(env.CORTAD_INGEST_KEY, { id: "conv_8f2c", messages })); return new Response(messages.at(-1).text); }, }; ```