> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gately.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Document AI Processing

> Processing documents with Gately AI AI models

<Frame>
  <img src="https://mintcdn.com/taamai-c8c27d6c/7tpU7wOp-rlopJuB/images/AI_ocr.jpg?fit=max&auto=format&n=7tpU7wOp-rlopJuB&q=85&s=c592762e6ca087e99bd63e4503190861" alt="Document Processing" width="1200" height="600" data-path="images/AI_ocr.jpg" />
</Frame>

# Document Processing with AI

This guide demonstrates how to extract content from documents and process it with Gately AI's AI models.

## Step 1: Upload and Extract Document Content

First, upload your document to extract its content:

```bash theme={null}
curl -X POST \
  'https://uploud.taam.cloud/upload' \
  -F 'file=@/path/to/document.pdf'
```

The API will return the extracted content:

```json theme={null}
{
  "status": true,
  "content": "Document content extracted...",
  "type": "pdf",
  "error": ""
}
```

## Step 2: Process with AI Models

Use the extracted content with Gately AI's AI models:

<CodeGroup>
  ```python Python theme={null}
  import os
  import requests

  # Step 1: Upload and extract document
  upload_url = 'https://uploud.taam.cloud/upload'
  file_path = '/path/to/document.pdf'

  with open(file_path, 'rb') as file:
      files = {'file': file}
      upload_response = requests.post(upload_url, files=files)

  document_content = upload_response.json()['content']

  # Step 2: Process with AI
  ai_url = 'https://api.gately.ai/v1/chat/completions'
  headers = {
      'Authorization': f'Bearer {os.environ.get("TAAM_API_KEY")}',
      'Content-Type': 'application/json'
  }

  ai_payload = {
      'model': 'gpt-4o',
      'messages': [
          {'role': 'system', 'content': 'You are a document analysis assistant.'},
          {'role': 'user', 'content': f'Summarize this document: {document_content}'}
      ]
  }

  ai_response = requests.post(ai_url, json=ai_payload, headers=headers)
  summary = ai_response.json()['choices'][0]['message']['content']
  print(summary)
  ```

  ```javascript JavaScript theme={null}
  const axios = require('axios');
  const fs = require('fs');
  const FormData = require('form-data');

  async function processDocument() {
    // Step 1: Upload and extract document
    const formData = new FormData();
    formData.append('file', fs.createReadStream('/path/to/document.pdf'));
    
    const uploadResponse = await axios.post('https://uploud.taam.cloud/upload', formData, {
      headers: formData.getHeaders()
    });
    
    const documentContent = uploadResponse.data.content;
    
    // Step 2: Process with AI
    const aiResponse = await axios.post('https://api.gately.ai/v1/chat/completions', {
      model: 'gpt-4o',
      messages: [
        { role: 'system', content: 'You are a document analysis assistant.' },
        { role: 'user', content: `Summarize this document: ${documentContent}` }
      ]
    }, {
      headers: {
        'Authorization': `Bearer ${process.env.TAAM_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });
    
    const summary = aiResponse.data.choices[0].message.content;
    console.log(summary);
  }

  processDocument().catch(console.error);
  ```
</CodeGroup>

## Working with Large Documents

For large documents, use the embeddings extraction mode:

```bash theme={null}
curl -X POST \
  'https://uploud.taam.cloud/upload' \
  -F 'file=@/path/to/large_document.pdf' \
  -F 'extract_mode=embeddings'
```

This returns the document split into chunks:

```json theme={null}
{
  "id": "scrape-aec35e29-703d-4eaf-b1c4-5cda9fd66951",
  "object": "chunks",
  "data": {
    "success": true,
    "data": {
      "chunks": [
        {
          "content": "Chapter 1: Introduction...",
          "total_tokens": 150,
          "from_page": 1
        },
        // Additional chunks...
      ]
    }
  }
}
```

Process the chunks sequentially or use a RAG pattern:

<CodeGroup>
  ```python Python theme={null}
  # Process chunks with AI
  chunks = response.json()['data']['data']['chunks']
  summaries = []

  for idx, chunk in enumerate(chunks):
      ai_payload = {
          'model': 'gpt-4o',
          'messages': [
              {'role': 'system', 'content': 'Summarize the following document section.'},
              {'role': 'user', 'content': chunk['content']}
          ]
      }
      
      chunk_summary = requests.post(ai_url, json=ai_payload, headers=headers)
      summaries.append(f"Section {idx+1}: " + chunk_summary.json()['choices'][0]['message']['content'])

  # Combine summaries
  final_summary = "\n\n".join(summaries)
  ```

  ```javascript JavaScript theme={null}
  // Process chunks with AI
  const chunks = response.data.data.data.chunks;
  const summaries = [];

  for (let i = 0; i < chunks.length; i++) {
    const aiResponse = await axios.post('https://api.gately.ai/v1/chat/completions', {
      model: 'gpt-4o',
      messages: [
        { role: 'system', content: 'Summarize the following document section.' },
        { role: 'user', content: chunks[i].content }
      ]
    }, {
      headers: {
        'Authorization': `Bearer ${process.env.TAAM_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });
    
    summaries.push(`Section ${i+1}: ${aiResponse.data.choices[0].message.content}`);
  }

  // Combine summaries
  const finalSummary = summaries.join('\n\n');
  ```
</CodeGroup>

## Using Document Processing Options

### Extract Images from Document

```bash theme={null}
curl -X POST \
  'https://uploud.taam.cloud/upload' \
  -F 'file=@/path/to/document.pdf' \
  -F 'images_only=true'
```

### OCR Processing for Scanned Documents

```bash theme={null}
curl -X POST \
  'https://uploud.taam.cloud/upload' \
  -F 'file=@/path/to/scanned_document.pdf' \
  -F 'enable_ocr=true'
```

### Page-Based Processing

```bash theme={null}
curl -X POST \
  'https://uploud.taam.cloud/upload' \
  -F 'file=@/path/to/document.pdf' \
  -F 'page_based=true'
```

## Best Practices

<CardGroup cols={2}>
  <Card title="File Size" icon="weight-scale">
    For files approaching the size limit (50MB), compress them before uploading
  </Card>

  <Card title="Image Quality" icon="image">
    For OCR, ensure images are at least 300 DPI for optimal text extraction
  </Card>

  <Card title="Chunking" icon="puzzle-piece">
    Use embeddings mode for large documents to get proper chunking
  </Card>

  <Card title="Headers & Footers" icon="heading">
    Use remove\_headers=true to clean repeated elements from each page
  </Card>
</CardGroup>

## Handling Specific Document Types

### PDFs with Forms

```bash theme={null}
curl -X POST \
  'https://uploud.taam.cloud/upload' \
  -F 'file=@/path/to/form.pdf'
```

The API will extract form fields and their values.

### Presentations

```bash theme={null}
curl -X POST \
  'https://uploud.taam.cloud/upload' \
  -F 'file=@/path/to/slides.pptx'
```

The API preserves slide structure in the extracted content.

### Audio Files (Transcription)

```bash theme={null}
curl -X POST \
  'https://uploud.taam.cloud/upload' \
  -F 'file=@/path/to/recording.mp3'
```

Returns the transcribed text from the audio file.
