Vision Models
TOKENGRID_BASE_URL environment variables. The base URL includes /v1. See the quick start.Send images to vision-capable models using a supported chat interface.
Chat Completions API
Combine text with an image URL in message content. Choose a vision-capable Model ID and verify the interface supports the input format.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["TOKENGRID_API_KEY"],
base_url=os.environ["TOKENGRID_BASE_URL"]
)
response = client.chat.completions.create(
model="YOUR_VISION_MODEL_ID",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image."},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg"
}
}
]
}
]
)
print(response.choices[0].message.content)import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.TOKENGRID_API_KEY,
baseURL: process.env.TOKENGRID_BASE_URL,
});
const response = await client.chat.completions.create({
model: "YOUR_VISION_MODEL_ID",
messages: [
{
role: "user",
content: [
{ type: "text", text: "Describe this image." },
{
type: "image_url",
image_url: { url: "https://example.com/image.jpg" }
}
]
}
]
});
console.log(response.choices[0].message.content);curl "$TOKENGRID_BASE_URL/chat/completions" \
-H "request-id: $REQUEST_ID" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKENGRID_API_KEY" \
-d '{
"model": "YOUR_VISION_MODEL_ID",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image."},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
]
}]
}'Using Base64 images
You can encode a local image as a Base64 data URL and include it in the request where supported. The examples use Python and JavaScript.
import os
import base64
from openai import OpenAI
client = OpenAI(
api_key=os.environ["TOKENGRID_API_KEY"],
base_url=os.environ["TOKENGRID_BASE_URL"]
)
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
image_base64 = encode_image("your_image.jpg")
response = client.chat.completions.create(
model="YOUR_VISION_MODEL_ID",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image."},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{image_base64}"
}
}
]
}]
)
print(response.choices[0].message.content)import OpenAI from "openai";
import fs from "fs";
const client = new OpenAI({
apiKey: process.env.TOKENGRID_API_KEY,
baseURL: process.env.TOKENGRID_BASE_URL,
});
const imageBase64 = fs.readFileSync("your_image.jpg").toString("base64");
const response = await client.chat.completions.create({
model: "YOUR_VISION_MODEL_ID",
messages: [{
role: "user",
content: [
{ type: "text", text: "Describe this image." },
{
type: "image_url",
image_url: { url: `data:image/jpeg;base64,${imageBase64}` }
}
]
}]
});
console.log(response.choices[0].message.content);Working with images
Image URL accessibility, expiration, size and format affect whether a model can read it.
Images requiring authentication
Fetch a private image in your application using appropriate authorization, then send an accepted representation. Do not expose private credentials in a URL.
Processing PDF and Word documents
If the interface does not directly accept a PDF or DOCX, preprocess it in your application. Convert PDF pages to images; for DOCX, extract text and optionally supported images. Process long documents in batches. The examples cover Python and JavaScript:
import os
import io
import base64
import pypdfium2 as pdfium
from openai import OpenAI
client = OpenAI(api_key=os.environ["TOKENGRID_API_KEY"],
base_url=os.environ["TOKENGRID_BASE_URL"])
def pdf_to_images(path):
document = pdfium.PdfDocument(path)
parts = []
try:
for page in document:
output = io.BytesIO()
page.render(scale=2).to_pil().save(output, format="PNG")
encoded = base64.b64encode(output.getvalue()).decode("utf-8")
parts.append({"type": "image_url", "image_url": {
"url": f"data:image/png;base64,{encoded}"}})
finally:
document.close()
return parts
response = client.chat.completions.create(
model="YOUR_VISION_MODEL_ID",
messages=[{"role": "user", "content": [
{"type": "text", "text": "Summarize this PDF."},
*pdf_to_images("document.pdf")
]}]
)
print(response.choices[0].message.content)import os
import base64
from docx import Document
from openai import OpenAI
client = OpenAI(api_key=os.environ["TOKENGRID_API_KEY"],
base_url=os.environ["TOKENGRID_BASE_URL"])
def docx_to_content(path):
document = Document(path)
text = "\n".join(p.text for p in document.paragraphs if p.text.strip())
parts = [{"type": "text", "text": "Summarize this document:\n" + text}]
for relation in document.part.rels.values():
if relation.reltype.endswith("/image"):
image = relation.target_part
if image.content_type not in ("image/png", "image/jpeg"):
continue
encoded = base64.b64encode(image.blob).decode("utf-8")
parts.append({"type": "image_url", "image_url": {
"url": f"data:{image.content_type};base64,{encoded}"}})
return parts
response = client.chat.completions.create(
model="YOUR_VISION_MODEL_ID",
messages=[{"role": "user", "content": docx_to_content("document.docx")}]
)
print(response.choices[0].message.content)import fs from "node:fs";
import OpenAI from "openai";
import { pdf } from "pdf-to-img";
const client = new OpenAI({
apiKey: process.env.TOKENGRID_API_KEY,
baseURL: process.env.TOKENGRID_BASE_URL
});
async function pdfToImages(path) {
const parts = [];
for await (const page of await pdf(path, { scale: 2 })) {
parts.push({type: "image_url", image_url: {
url: `data:image/png;base64,${Buffer.from(page).toString("base64")}`
}});
}
return parts;
}
const response = await client.chat.completions.create({
model: "YOUR_VISION_MODEL_ID",
messages: [{role: "user", content: [
{type: "text", text: "Summarize this PDF."},
...(await pdfToImages("document.pdf"))
]}]
});
console.log(response.choices[0].message.content);import OpenAI from "openai";
import mammoth from "mammoth";
const client = new OpenAI({
apiKey: process.env.TOKENGRID_API_KEY,
baseURL: process.env.TOKENGRID_BASE_URL
});
async function docxToContent(path) {
const {value: text} = await mammoth.extractRawText({path});
const parts = [{type: "text", text: `Summarize this document:\n${text}`}];
await mammoth.convertToHtml({path}, {convertImage:
mammoth.images.imgElement(async image => {
if (["image/png", "image/jpeg"].includes(image.contentType)) {
const encoded = await image.readAsBase64String();
parts.push({type: "image_url", image_url: {
url: `data:${image.contentType};base64,${encoded}`
}});
}
return {src: ""};
})
});
return parts;
}
const response = await client.chat.completions.create({
model: "YOUR_VISION_MODEL_ID",
messages: [{role: "user", content: await docxToContent("document.docx")}]
});
console.log(response.choices[0].message.content);Input limits
Check the selected model's image count, format and size limits, URL accessibility, download requirements and ordering of text and images. Limits vary by model and interface.