Skip to content

GLM-OCR 图片识别

glm-ocr 是智谱提供的 OCR 及版面解析模型,支持对图片中的文字、表格、公式等内容进行结构化识别。本文档演示如何通过 Agentsflare 网关调用该模型。

基础配置

在开始使用 API 之前,请确保您已经获取了 API Key。如果还没有,请参考创建 API Key

基础信息

  • API Base URL: https://api.agentsflare.com/zhipu/v4/layout_parsing
  • 认证方式: Bearer Token
  • 内容类型: application/json
  • 请求方法: POST

图片传输方式

glm-ocr 支持以下两种图片传输方式:

方式字段格式说明
图片 URL"file": "https://example.com/image.png"直接使用可访问的图片链接。
base64 编码"file": "data:image/png;base64,iVBORw0KGgo..."将图片文件转为 base64 后,以 data URL 形式传入。

下方示例同时演示两种用法,你可按实际需求选择。

请求示例

通过图片 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))
}

通过 base64 调用

bash
# 1) 将图片转为 base64(以 Linux/macOS 为例)
BASE64=$(base64 -i /path/to/image.png | tr -d '\n')

# 2) 发送请求
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"找不到文件:{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"用法:{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(`找不到文件:${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("用法: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(`找不到文件:${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("用法: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("用法:%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("找不到文件:%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))
}

支持的模型

  • glm-ocr

💡 提示

glm-ocr 专注于 OCR 与版面解析,适合票据、合同、论文、表格等结构化文字识别场景。

本文档遵循 CC BY-SA 4.0 协议。