# AI Documents

Upload a file and receive extracted fields and classification when processing completes (via the endpoint response and your callback).

## Run AI on a document

POST `/ai_documents` — Upload a document for AI extraction. Returns immediately with a token; results are sent to your callback URL when processing completes.

Request Parameters

| Parameter | Required | Description |
| --- | --- | --- |
| file | Yes | PDF or TIFF document to process |
| callback_url | Yes | URL to receive results when processing completes |

#### cURL

```bash
export API_BASE="https://api.medsender.com/api/v2"
export API_KEY="sk_test_..."

curl -s -X POST -H "Authorization: Bearer $API_KEY" \
  -F "file=@./sample.pdf" \
  -F "callback_url=https://example.com/webhooks/ai" \
  "$API_BASE/ai_documents"
```

#### Node

```javascript
import { readFile } from 'fs/promises';

const API_BASE = 'https://api.medsender.com/api/v2';
const API_KEY = 'sk_test_...';
const fd = new FormData();
const fileBuffer = await readFile('./sample.pdf');
fd.append('file', new Blob([fileBuffer]), 'sample.pdf');
fd.append('callback_url', 'https://example.com/webhooks/ai');
const res = await fetch(`${API_BASE}/ai_documents`, { method: 'POST', headers: { Authorization: `Bearer ${API_KEY}` }, body: fd });
console.log(await res.json());
```

#### TypeScript

```typescript
const API_BASE: string='https://api.medsender.com/api/v2';
const API_KEY: string='sk_test_...';
const fd = new FormData();
fd.append('file', new Blob([await (await fetch('./sample.pdf')).arrayBuffer()]), 'sample.pdf');
fd.append('callback_url','https://example.com/webhooks/ai');
const res = await fetch(`${API_BASE}/ai_documents`,{ method:'POST', headers:{ Authorization: `Bearer ${API_KEY}` }, body: fd });
console.log(await res.json());
```

#### Python

```python
import requests
API_BASE='https://api.medsender.com/api/v2'
API_KEY='sk_test_...'
files={'file':open('./sample.pdf','rb')}
data={'callback_url':'https://example.com/webhooks/ai'}
r=requests.post(f"{API_BASE}/ai_documents", headers={'Authorization':f'Bearer {API_KEY}'}, files=files, data=data)
print(r.json())
```

#### Ruby

```ruby
require 'net/http'
require 'uri'
uri = URI.parse('https://api.medsender.com/api/v2/ai_documents')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'Bearer sk_test_...'
request.set_form([['callback_url','https://example.com/webhooks/ai']], 'multipart/form-data')
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true){|http| http.request(request)}
puts res.body
```

#### PHP

```php
<?php
$ch = curl_init();
$post = [ 'file' => new CURLFile('sample.pdf','application/pdf','sample.pdf'), 'callback_url' => 'https://example.com/webhooks/ai' ];
curl_setopt_array($ch, [
  CURLOPT_URL => 'https://api.medsender.com/api/v2/ai_documents',
  CURLOPT_POST => true,
  CURLOPT_HTTPHEADER => ['Authorization: Bearer sk_test_...'],
  CURLOPT_POSTFIELDS => $post,
  CURLOPT_RETURNTRANSFER => true
]);
$res = curl_exec($ch);
echo $res;
```

#### Java

```java
import java.net.http.*;
import java.net.URI;
import java.nio.file.*;
import java.util.*;

public class AICreate {
  public static void main(String[] args) throws Exception {
    var boundary = UUID.randomUUID().toString();
    var client = HttpClient.newHttpClient();

    // Build multipart body
    var fileBytes = Files.readAllBytes(Path.of("sample.pdf"));
    var body = new StringBuilder();
    body.append("--").append(boundary).append("\r\n");
    body.append("Content-Disposition: form-data; name=\"file\"; filename=\"sample.pdf\"\r\n");
    body.append("Content-Type: application/pdf\r\n\r\n");
    var prefix = body.toString().getBytes();
    var suffix = ("\r\n--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"callback_url\"\r\n\r\nhttps://example.com/webhooks/ai\r\n--" + boundary + "--\r\n").getBytes();

    var fullBody = new byte[prefix.length + fileBytes.length + suffix.length];
    System.arraycopy(prefix, 0, fullBody, 0, prefix.length);
    System.arraycopy(fileBytes, 0, fullBody, prefix.length, fileBytes.length);
    System.arraycopy(suffix, 0, fullBody, prefix.length + fileBytes.length, suffix.length);

    var req = HttpRequest.newBuilder()
      .uri(URI.create("https://api.medsender.com/api/v2/ai_documents"))
      .header("Authorization", "Bearer sk_test_...")
      .header("Content-Type", "multipart/form-data; boundary=" + boundary)
      .POST(HttpRequest.BodyPublishers.ofByteArray(fullBody))
      .build();
    var res = client.send(req, HttpResponse.BodyHandlers.ofString());
    System.out.println(res.body());
  }
}
```

#### C#

```csharp
using System;
using System.Net.Http;

var api = "https://api.medsender.com/api/v2/ai_documents";
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer sk_test_...");
using var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(System.IO.File.ReadAllBytes("sample.pdf")), "file", "sample.pdf");
form.Add(new StringContent("https://example.com/webhooks/ai"), "callback_url");
var res = await client.PostAsync(api, form);
Console.WriteLine(await res.Content.ReadAsStringAsync());
```

## List AI Documents

GET `/ai_documents`

```bash
curl -s -H "Authorization: Bearer sk_test_..." "https://api.medsender.com/api/v2/ai_documents" | jq
```

## Get AI Document

GET `/ai_documents/:id` where `:id` is the returned token.

```bash
curl -s -H "Authorization: Bearer sk_test_..." "https://api.medsender.com/api/v2/ai_documents/REPLACE_AI_TOKEN" | jq
```

### Response Examples

Create

```json
{
  "message": "AI Document Classification has initiated, callback will be sent upon completion.",
  "ai_token": "c4d5e6f7a8b9"
}
```

Get / List

```json
{
  "ai_result": {
    "ai_token": "d9eabe46-7ba7-40a3-902f-1e383f636140",
    "patient_name": "John Doe",
    "patient_dob": "1990-01-15",
    "patient_phone_number": "+15550100001",
    "patient_gender": "Male",
    "patient_address": "123 Example Street, Anytown, CA 90210",
    "document_classification": "Referral",
    "document_summary": "Cardiology referral for routine evaluation.",
    "insurance_plan_name": "Example Health PPO",
    "insurance_payer": "Example Insurance Co",
    "insurance_group_number": "GRP-000001",
    "insurance_member_id": "MEM000000001",
    "insurance_subscriber_name": "John Doe",
    "insurance_member_names": ["John Doe"],
    "icd_codes_json": [{"code": "R00.0"}, {"code": "I10"}],
    "cpt_codes_json": [{"code": "99213"}, {"code": "93000"}],
    "hcpcs_codes_json": [],
    "completed_at": "2025-01-15T11:00:00.000Z",
    "error_details": null
  }
}
```

### Response Fields

The `ai_result` object contains extracted information:

| Field | Description |
| --- | --- |
| ai_token | Unique identifier for this AI document request |
| document_classification | Document type: "Referral", "Lab Result", "Prior Authorization", "Imaging Result", "Pharmacy Request", "Consult Note", "Discharge Summary", "Medical Records Request", or "Other" |
| document_summary | AI-generated summary of the document contents |
| patient_name | Full patient name extracted from document |
| patient_dob | Patient date of birth (YYYY-MM-DD) |
| patient_phone_number | Patient phone number |
| patient_gender | Patient gender |
| patient_address | Patient address |
| insurance_plan_name | Primary insurance plan name |
| insurance_payer | Primary insurance payer/company |
| insurance_group_number | Insurance group number |
| insurance_member_id | Insurance member ID |
| icd_codes_json | Array of ICD codes: [{"code": "I10"},...] |
| cpt_codes_json | Array of CPT codes: [{"code": "99213"},...] |
| hcpcs_codes_json | Array of HCPCS codes |
| completed_at | When processing completed (ISO 8601) |
| error_details | Error message if processing failed, otherwise null |
