Skip to content

GLM-OCR Image Recognition

glm-ocr is an OCR and layout parsing model provided by Zhipu. It supports structured recognition of text, tables, formulas, and other content in images. This document demonstrates how to call this model through the Agentsflare gateway.

Basic Configuration

Before using the API, please make sure you have obtained an API Key. If not, please refer to Create API Key.

Basic Information

  • API Base URL: https://api.agentsflare.com/zhipu/v4/layout_parsing
  • Authentication: Bearer Token
  • Content Type: application/json
  • Request Method: POST

Image Transmission Methods

glm-ocr supports the following two image transmission methods:

MethodField FormatDescription
Image URL"file": "https://example.com/image.png"Use a directly accessible image link.
Base64 Encoding"file": "data:image/png;base64,iVBORw0KGgo..."Convert the image file to base64 and pass it as a data URL.

The examples below demonstrate both methods. Choose according to your actual needs.

Request Examples

Call via Image URL

bash
curl -X POST "https://api.agentsflare.com/zhipu/v4/layout_parsing" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "glm-ocr",
    "file": "https://cdn.bigmodel.cn/static/logo/introduction.png"
  }'
python
import requests

API_KEY = "YOUR_API_KEY"
URL = "https://api.agentsflare.com/zhipu/v4/layout_parsing"

payload = {
    "model": "glm-ocr",
    "file": "https://cdn.bigmodel.cn/static/logo/introduction.png",
}

resp = requests.post(
    URL,
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    },
    json=payload,
)

print(resp.status_code)
print(resp.json())
javascript
const resp = await fetch("https://api.agentsflare.com/zhipu/v4/layout_parsing", {
  method: "POST",
  headers: {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "glm-ocr",
    file: "https://cdn.bigmodel.cn/static/logo/introduction.png",
  }),
});

const data = await resp.json();
console.log(data);
javascript
const https = require("https");

const payload = JSON.stringify({
  model: "glm-ocr",
  file: "https://cdn.bigmodel.cn/static/logo/introduction.png",
});

const req = https.request(
  "https://api.agentsflare.com/zhipu/v4/layout_parsing",
  {
    method: "POST",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json",
      "Content-Length": Buffer.byteLength(payload),
    },
  },
  (res) => {
    let body = "";
    res.on("data", (chunk) => (body += chunk));
    res.on("end", () => console.log(body));
  }
);

req.write(payload);
req.end();
go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func main() {
	apiKey := "YOUR_API_KEY"
	url := "https://api.agentsflare.com/zhipu/v4/layout_parsing"

	payload := map[string]any{
		"model": "glm-ocr",
		"file":  "https://cdn.bigmodel.cn/static/logo/introduction.png",
	}

	bodyBytes, _ := json.Marshal(payload)
	req, err := http.NewRequest("POST", url, bytes.NewReader(bodyBytes))
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

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

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

Call via Base64

bash
# 1) Convert image to base64 (Linux/macOS example)
BASE64=$(base64 -i /path/to/image.png | tr -d '\n')

# 2) Send request
curl -X POST "https://api.agentsflare.com/zhipu/v4/layout_parsing" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"model\": \"glm-ocr\",
    \"file\": \"data:image/png;base64,${BASE64}\"
  }"
python
import base64
import mimetypes
import os
import sys

import requests

API_KEY = "YOUR_API_KEY"
URL = "https://api.agentsflare.com/zhipu/v4/layout_parsing"


def file_to_data_url(path: str) -> str:
    if not os.path.isfile(path):
        raise FileNotFoundError(f"File not found: {path}")

    mime, _ = mimetypes.guess_type(path)
    if mime is None:
        mime = "image/jpeg"

    with open(path, "rb") as f:
        b64 = base64.b64encode(f.read()).decode("utf-8")

    return f"data:{mime};base64,{b64}"


def main():
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} /path/to/image.png")
        sys.exit(1)

    image_path = sys.argv[1]
    data_url = file_to_data_url(image_path)

    payload = {
        "model": "glm-ocr",
        "file": data_url,
    }

    resp = requests.post(
        URL,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json=payload,
    )

    print(resp.status_code)
    print(resp.json())


if __name__ == "__main__":
    main()
javascript
import fs from "fs";
import path from "path";

const API_KEY = "YOUR_API_KEY";
const URL = "https://api.agentsflare.com/zhipu/v4/layout_parsing";

function fileToDataUrl(filePath) {
  if (!fs.existsSync(filePath)) {
    throw new Error(`File not found: ${filePath}`);
  }

  const ext = path.extname(filePath).toLowerCase();
  let mime = "image/jpeg";
  if (ext === ".png") mime = "image/png";
  else if (ext === ".webp") mime = "image/webp";
  else if (ext === ".gif") mime = "image/gif";

  const b64 = fs.readFileSync(filePath).toString("base64");
  return `data:${mime};base64,${b64}`;
}

async function main() {
  const imagePath = process.argv[2];
  if (!imagePath) {
    console.error("Usage: node script.js /path/to/image.png");
    process.exit(1);
  }

  const dataUrl = fileToDataUrl(imagePath);

  const resp = await fetch(URL, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "glm-ocr",
      file: dataUrl,
    }),
  });

  const data = await resp.json();
  console.log(data);
}

main().catch(console.error);
javascript
const fs = require("fs");
const path = require("path");
const https = require("https");

const API_KEY = "YOUR_API_KEY";
const URL = "https://api.agentsflare.com/zhipu/v4/layout_parsing";

function fileToDataUrl(filePath) {
  if (!fs.existsSync(filePath)) {
    throw new Error(`File not found: ${filePath}`);
  }

  const ext = path.extname(filePath).toLowerCase();
  let mime = "image/jpeg";
  if (ext === ".png") mime = "image/png";
  else if (ext === ".webp") mime = "image/webp";
  else if (ext === ".gif") mime = "image/gif";

  const b64 = fs.readFileSync(filePath).toString("base64");
  return `data:${mime};base64,${b64}`;
}

function main() {
  const imagePath = process.argv[2];
  if (!imagePath) {
    console.error("Usage: node script.js /path/to/image.png");
    process.exit(1);
  }

  const dataUrl = fileToDataUrl(imagePath);
  const payload = JSON.stringify({
    model: "glm-ocr",
    file: dataUrl,
  });

  const req = https.request(
    URL,
    {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${API_KEY}`,
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(payload),
      },
    },
    (res) => {
      let body = "";
      res.on("data", (chunk) => (body += chunk));
      res.on("end", () => console.log(body));
    }
  );

  req.write(payload);
  req.end();
}

main();
go
package main

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

func main() {
	apiKey := "YOUR_API_KEY"
	url := "https://api.agentsflare.com/zhipu/v4/layout_parsing"

	if len(os.Args) < 2 {
		fmt.Printf("Usage: %s /path/to/image.png\n", os.Args[0])
		os.Exit(1)
	}
	imagePath := os.Args[1]

	info, err := os.Stat(imagePath)
	if err != nil || info.IsDir() {
		fmt.Printf("File not found: %s\n", imagePath)
		os.Exit(1)
	}

	ext := filepath.Ext(imagePath)
	mediaType := mime.TypeByExtension(ext)
	if mediaType == "" {
		mediaType = "image/jpeg"
	}

	b, err := os.ReadFile(imagePath)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	dataUrl := fmt.Sprintf("data:%s;base64,%s", mediaType, base64.StdEncoding.EncodeToString(b))

	payload := map[string]any{
		"model": "glm-ocr",
		"file":  dataUrl,
	}

	bodyBytes, _ := json.Marshal(payload)
	req, err := http.NewRequest("POST", url, bytes.NewReader(bodyBytes))
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

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

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

Supported Models

  • glm-ocr

💡 Tip

glm-ocr focuses on OCR and layout parsing, making it suitable for structured text recognition scenarios such as invoices, contracts, papers, and tables.

This documentation is licensed under CC BY-SA 4.0.