Skip to content

Documents

You can send documents and other media files directly to the chat completions endpoint. Voidon extends the standard OpenAI message format to support a wide range of file types by embedding them as Base64 encoded data within your request.

There is no separate upload endpoint. All files must be included in the messages array of your call to /v1/chat/completions.

How it Works

To send a file, you must:

  1. Read the file from your local disk into memory.
  2. Encode the file's binary content into a Base64 string.
  3. Determine the file's MIME type (e.g., image/jpeg, application/pdf).
  4. Construct a data URI in the format data:[MIME_TYPE];base64,[BASE64_ENCODED_STRING].
  5. Modify the message payload so that the content field is an array containing both the text and the file objects.

Payload Structure

The content of a user message becomes an array of parts. Each part can be text or a file.

JSON
{
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Please describe this image and summarize the attached document."
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUg..."
          }
        },
        {
          "type": "file",
          "file": {
            "url": "data:application/pdf;base64,JVBERi0xLjcKJeLjz9M..."
          }
        }
      ]
    }
  ]
}

The type field can be image_url, audio_url, video_url, or a generic file.

Note

In the examples below, you must replace your-voidon-api-key with your actual API key. You will also need to have local files named example.jpg, example.mp3, example.mp4, and example.pdf for the code to run correctly.


Code Examples

The following examples demonstrate how to send a text prompt along with an image and a PDF file. The same pattern applies to audio and video files.

Bash
# Helper command to encode files into Base64
# For macOS:
IMAGE_B64=$(base64 -i example.jpg)
PDF_B64=$(base64 -i example.pdf)
# For Linux:
# IMAGE_B64=$(base64 -w 0 example.jpg)
# PDF_B64=$(base64 -w 0 example.pdf)

curl -X POST https://api.voidon.astramind.ai/v1/chat/completions \
  -H "Authorization: Bearer your-voidon-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "Describe the image and summarize the PDF."
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "data:image/jpeg;base64,'"$IMAGE_B64"'"
            }
          },
          {
            "type": "file",
            "file": {
              "url": "data:application/pdf;base64,'"$PDF_B64"'"
            }
          }
        ]
      }
    ]
  }'
Python
import openai
import base64
import mimetypes

# Function to encode a local file into a data URI
def encode_file_to_data_uri(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if mime_type is None:
        raise ValueError("Could not determine MIME type for file")

    with open(file_path, "rb") as file:
        encoded_string = base64.b64encode(file.read()).decode("utf-8")

    return f"data:{mime_type};base64,{encoded_string}"

client = openai.OpenAI(
    api_key="your-voidon-api-key",
    base_url="https://api.voidon.astramind.ai/v1"
)

# Prepare the data URIs
image_uri = encode_file_to_data_uri("example.jpg")
pdf_uri = encode_file_to_data_uri("example.pdf")

response = client.chat.completions.create(
    model="auto",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Describe the image and summarize the PDF."},
                {"type": "image_url", "image_url": {"url": image_uri}},
                {"type": "file", "file": {"url": pdf_uri}}
            ]
        }
    ]
)

print(response.choices[0].message.content)
Python
import requests
import json
import base64
import mimetypes

API_KEY = "your-voidon-api-key"
API_URL = "https://api.voidon.astramind.ai/v1/chat/completions"

# Function to encode a local file into a data URI
def encode_file_to_data_uri(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if mime_type is None:
        raise ValueError("Could not determine MIME type for file")

    with open(file_path, "rb") as file:
        encoded_string = base64.b64encode(file.read()).decode("utf-8")

    return f"data:{mime_type};base64,{encoded_string}"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

image_uri = encode_file_to_data_uri("example.jpg")
pdf_uri = encode_file_to_data_uri("example.pdf")

payload = {
    "model": "auto",
    "messages": [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Describe the image and summarize the PDF."},
                {"type": "image_url", "image_url": {"url": image_uri}},
                {"type": "file", "file": {"url": pdf_uri}}
            ]
        }
    ]
}

response = requests.post(API_URL, headers=headers, data=json.dumps(payload))

if response.status_code == 200:
    print(response.json()['choices'][0]['message']['content'])
else:
    print(f"Error: {response.status_code} - {response.text}")
JavaScript
// Requires Node.js environment
import OpenAI from 'openai';
import fs from 'fs';
import path from 'path';
import mime from 'mime-types'; // npm install mime-types

const encodeFileToDataUri = (filePath) => {
    const mimeType = mime.lookup(filePath);
    if (!mimeType) {
        throw new Error("Could not determine MIME type");
    }
    const fileBuffer = fs.readFileSync(filePath);
    const base64Encoded = fileBuffer.toString('base64');
    return `data:${mimeType};base64,${base64Encoded}`;
};

const openai = new OpenAI({
    apiKey: 'your-voidon-api-key',
    baseURL: 'https://api.voidon.astramind.ai/v1'
});

async function main() {
    const imageUri = encodeFileToDataUri('example.jpg');
    const pdfUri = encodeFileToDataUri('example.pdf');

    const response = await openai.chat.completions.create({
        model: 'auto',
        messages: [
            {
                role: 'user',
                content: [
                    { type: 'text', text: 'Describe the image and summarize the PDF.' },
                    { type: 'image_url', image_url: { url: imageUri } },
                    { type: 'file', file: { url: pdfUri } }
                ],
            }
        ],
    });
    console.log(response.choices[0].message.content);
}

main();
JavaScript
// Requires Node.js environment
import fs from 'fs';
import mime from 'mime-types'; // npm install mime-types
import fetch from 'node-fetch'; // npm install node-fetch

const apiKey = 'your-voidon-api-key';
const apiUrl = 'https://api.voidon.astramind.ai/v1/chat/completions';

const encodeFileToDataUri = (filePath) => {
    const mimeType = mime.lookup(filePath);
    if (!mimeType) {
        throw new Error("Could not determine MIME type");
    }
    const fileBuffer = fs.readFileSync(filePath);
    const base64Encoded = fileBuffer.toString('base64');
    return `data:${mimeType};base64,${base64Encoded}`;
};

const imageUri = encodeFileToDataUri('example.jpg');
const pdfUri = encodeFileToDataUri('example.pdf');

const payload = {
    model: 'auto',
    messages: [
        {
            role: 'user',
            content: [
                { type: 'text', text: 'Describe the image and summarize the PDF.' },
                { type: 'image_url', image_url: { url: imageUri } },
                { type: 'file', file: { url: pdfUri } }
            ],
        }
    ],
};

fetch(apiUrl, {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(payload)
})
.then(res => res.json())
.then(data => {
    console.log(data.choices[0].message.content);
})
.catch(error => console.error('Error:', error));
Go
package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "github.com/sashabaranov/go-openai"
    "log"
    "mime"
    "os"
    "path/filepath"
)

func encodeFileToDataURI(filePath string) (string, error) {
    fileBytes, err := os.ReadFile(filePath)
    if err != nil {
        return "", err
    }
    encodedString := base64.StdEncoding.EncodeToString(fileBytes)
    mimeType := mime.TypeByExtension(filepath.Ext(filePath))
    if mimeType == "" {
        mimeType = "application/octet-stream"
    }
    return fmt.Sprintf("data:%s;base64,%s", mimeType, encodedString), nil
}

func main() {
    config := openai.DefaultConfig("your-voidon-api-key")
    config.BaseURL = "https://api.voidon.astramind.ai/v1"
    client := openai.NewClientWithConfig(config)

    imageURI, err := encodeFileToDataURI("example.jpg")
    if err != nil {
        log.Fatalf("Failed to encode image: %v", err)
    }

    pdfURI, err := encodeFileToDataURI("example.pdf")
    if err != nil {
        log.Fatalf("Failed to encode PDF: %v", err)
    }

    resp, err := client.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
            Model: "auto",
            Messages: []openai.ChatCompletionMessage{
                {
                    Role: openai.ChatMessageRoleUser,
                    MultiContent: []openai.ChatMessagePart{
                        {
                            Type: openai.ChatMessagePartTypeText,
                            Text: "Describe the image and summarize the PDF.",
                        },
                        {
                            Type: openai.ChatMessagePartTypeImageURL,
                            ImageURL: &openai.ChatMessageImageURL{
                                URL: imageURI,
                            },
                        },
                        // Note: The go-openai library doesn't have a native 'file' type.
                        // You might need to send this as a generic ImageURL or use an HTTP client.
                        // This example assumes the API can interpret an ImageURL part as a generic file.
                        {
                            Type: openai.ChatMessagePartTypeImageURL,
                            ImageURL: &openai.ChatMessageImageURL{
                                URL: pdfURI,
                            },
                        },
                    },
                },
            },
        },
    )
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    fmt.Println(resp.Choices[0].Message.Content)
}
Go
package main

import (
    "bytes"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io"
    "log"
    "mime"
    "net/http"
    "os"
    "path/filepath"
)

func encodeFileToDataURI(filePath string) (string, error) {
    fileBytes, err := os.ReadFile(filePath)
    if err != nil {
        return "", err
    }
    encodedString := base64.StdEncoding.EncodeToString(fileBytes)
    mimeType := mime.TypeByExtension(filepath.Ext(filePath))
    if mimeType == "" {
        mimeType = "application/octet-stream"
    }
    return fmt.Sprintf("data:%s;base64,%s", mimeType, encodedString), nil
}

// Define structs for the JSON payload
type MessagePart struct {
    Type      string     `json:"type"`
    Text      string     `json:"text,omitempty"`
    ImageURL  *URLDetail `json:"image_url,omitempty"`
    FileURL   *URLDetail `json:"file,omitempty"`
}
type URLDetail struct {
    URL string `json:"url"`
}
type Message struct {
    Role    string        `json:"role"`
    Content []MessagePart `json:"content"`
}
type RequestPayload struct {
    Model    string    `json:"model"`
    Messages []Message `json:"messages"`
}

func main() {
    apiKey := "your-voidon-api-key"
    url := "https://api.voidon.astramind.ai/v1/chat/completions"

    imageURI, err := encodeFileToDataURI("example.jpg")
    if err != nil {
        log.Fatalf("Failed to encode image: %v", err)
    }
    pdfURI, err := encodeFileToDataURI("example.pdf")
    if err != nil {
        log.Fatalf("Failed to encode PDF: %v", err)
    }

    payload := RequestPayload{
        Model: "auto",
        Messages: []Message{
            {
                Role: "user",
                Content: []MessagePart{
                    {Type: "text", Text: "Describe the image and summarize the PDF."},
                    {Type: "image_url", ImageURL: &URLDetail{URL: imageURI}},
                    {Type: "file", FileURL: &URLDetail{URL: pdfURI}},
                },
            },
        },
    }

    requestBody, _ := json.Marshal(payload)
    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}