惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
罗磊的独立博客
H
Help Net Security
I
Intezer
G
Google Developers Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Troy Hunt's Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
News and Events Feed by Topic
J
Java Code Geeks
S
Security Affairs
T
The Blog of Author Tim Ferriss
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
D
Docker
The GitHub Blog
The GitHub Blog
F
Full Disclosure
N
News and Events Feed by Topic
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
腾讯CDC
人人都是产品经理
人人都是产品经理
M
MIT News - Artificial intelligence
Blog — PlanetScale
Blog — PlanetScale
T
Threatpost
D
DataBreaches.Net
Recent Announcements
Recent Announcements
博客园 - 三生石上(FineUI控件)
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
L
LINUX DO - 最新话题
Google Online Security Blog
Google Online Security Blog
S
Schneier on Security
S
Securelist
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Help Net Security
Help Net Security
P
Proofpoint News Feed
Project Zero
Project Zero
S
SegmentFault 最新的问题
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MyScale Blog
MyScale Blog
Google DeepMind News
Google DeepMind News
宝玉的分享
宝玉的分享
Y
Y Combinator Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 叶小钗

MarkTechPost

A Coding Implementation of End-to-End Brain Decoding from MEG Signals Using NeuralSet and Deep Learning for Predicting Linguistic Features Meta Introduces Autodata: An Agentic Framework That Turns AI Models into Autonomous Data Scientists for High-Quality Training Data Creation Qwen AI Releases Qwen-Scope: An Open-Source Sparse AutoEncoders (SAE) Suite That Turns LLM Internal Features into Practical Development Tools A Coding Deep Dive into Agentic UI, Generative UI, State Synchronization, and Interrupt-Driven Approval Flows Moonshot AI Open-Sources FlashKDA: CUTLASS Kernels for Kimi Delta Attention with Variable-Length Batching and H20 Benchmarks Microsoft Research’s World-R1 Uses Flow-GRPO and 3D-Aware Rewards to Inject Geometric Consistency Into Wan 2.1 Without Architectural Changes A Coding Implementation on Pyright Type Checking Covering Generics, Protocols, Strict Mode, Type Narrowing, and Modern Python Typing IBM Releases Two Granite Speech 4.1 2B Models: Autoregressive ASR with Translation and Non-Autoregressive Editing for Fast Inference Top 10 KV Cache Compression Techniques for LLM Inference: Reducing Memory Overhead Across Eviction, Quantization, and Low-Rank Methods Qwen Team Releases FlashQLA: a High-Performance Linear Attention Kernel Library That Achieves Up to 3× Speedup on NVIDIA Hopper GPUs Step by Step Guide to Build a Complete PII Detection and Redaction Pipeline with OpenAI Privacy Filter Meta FAIR Releases NeuralSet: A Python Package for Neuro-AI That Supports fMRI, M/EEG, Spikes, and HuggingFace Embeddings smol-audio: A Colab-Friendly Notebook Collection for Fine-Tuning Whisper, Parakeet, Voxtral, Granite Speech, and Audio Flamingo 3 A Coding Implementation on Document Parsing Benchmarking with LlamaIndex ParseBench Using Python, Hugging Face, and Evaluation Metrics Poolside AI Introduces Laguna XS.2 and M.1: Agentic Coding Models Reaching 68.2% and 72.5% on SWE-bench Verified How to Build Traceable and Evaluated LLM Workflows Using Promptflow, Prompty, and OpenAI OpenAI Releases Privacy Filter: A 1.5B-Parameter Open-Source PII Redaction Model with 50M Active Parameters Top 10 Physical AI Models Powering Real-World Robots in 2026 How to Build a Lightweight Vision-Language-Action-Inspired Embodied Agent with Latent World Modeling and Model Predictive Control Meet Talkie-1930: A 13B Open-Weight LLM Trained on Pre-1931 English Text for Historical Reasoning and Generalization Research Build a Reinforcement Learning Powered Agent that Learns to Retrieve Relevant Long-Term Memories for Accurate LLM Question Answering OpenMOSS Releases MOSS-Audio: An Open-Source Foundation Model for Speech, Sound, Music, and Time-Aware Audio Reasoning Meta AI Releases Sapiens2: A High-Resolution Human-Centric Vision Model for Pose, Segmentation, Normals, Pointmap, and Albedo The LoRA Assumption That Breaks in Production How to Build a Fully Searchable AI Knowledge Base with OpenKB, OpenRouter, and Llama How to Build Smarter Multilingual Text Wrapping with BudouX Through Parsing, HTML Rendering, Model Introspection, and Toy Training Top 7 Benchmarks That Actually Matter for Agentic Reasoning in Large Language Models RAG Without Vectors: How PageIndex Retrieves by Reasoning A Coding Tutorial on Datashader on Rendering Massive Datasets with High-Performance Python Visual Analytics xAI Launches grok-voice-think-fast-1.0: Topping τ-voice Bench at 67.3%, Outperforming Gemini, GPT Realtime, and More A Coding Implementation on kvcached for Elastic KV Cache Memory, Bursty LLM Serving, and Multi-Model GPU Sharing Google DeepMind Introduces Vision Banana: An Instruction-Tuned Image Generator That Beats SAM 3 on Segmentation and Depth Anything V3 on Metric Depth Estimation Meet GitNexus: An Open-Source MCP-Native Knowledge Graph Engine That Gives Claude Code and Cursor Full Codebase Structural Awareness A Coding Implementation on Deepgram Python SDK for Transcription, Text-to-Speech, Async Audio Processing, and Text Intelligence A Coding Implementation on Microsoft’s OpenMementos with Trace Structure Analysis, Context Compression, and Fine-Tuning Data Preparation DeepSeek AI Releases DeepSeek-V4: Compressed Sparse Attention and Heavily Compressed Attention Enable One-Million-Token Contexts Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Training Architecture Achieving 88% Goodput Under High Hardware Failure Rates Mend Releases AI Security Governance Framework: Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model Mend.io Releases AI Security Governance Framework Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model OpenAI Releases GPT-5.5, a Fully Retrained Agentic Model That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval A Coding Tutorial on OpenMythos on Recurrent-Depth Transformers with Depth Extrapolation, Adaptive Computation, and Mixture-of-Experts Routing Google Cloud AI Research Introduces ReasoningBank: A Memory Framework that Distills Reasoning Strategies from Agent Successes and Failures Xiaomi Releases MiMo-V2.5-Pro and MiMo-V2.5: Matching Frontier Model Benchmarks at Significantly Lower Token Cost How to Design a Production-Grade CAMEL Multi-Agent System with Planning, Tool Use, Self-Consistency, and Critique-Driven Refinement Alibaba Qwen Team Releases Qwen3.6-27B: A Dense Open-Weight Model Outperforming 397B MoE on Agentic Coding Benchmarks A Detailed Implementation on Equinox with JAX Native Modules, Filtered Transforms, Stateful Layers, and End-to-End Training Workflows Next Leap to Harness Engineering: JiuwenClaw Pioneers ‘Coordination Engineering’ Photon Releases Spectrum: An Open-Source TypeScript Framework that Deploys AI Agents Directly to iMessage, WhatsApp, and Telegram OpenAI Open-Sources Euphony: A Browser-Based Visualization Tool for Harmony Chat Data and Codex Session Logs Hugging Face Releases ml-intern: An Open-Source AI Agent that Automates the LLM Post-Training Workflow A Coding Implementation to Build a Conditional Bayesian Hyperparameter Optimization Pipeline with Hyperopt, TPE, and Early Stopping Google Introduces Simula: A Reasoning-First Framework for Generating Controllable, Scalable Synthetic Datasets Across Specialized AI Domains A Coding Implementation on Qwen 3.6-35B-A3B Covering Multimodal Inference, Thinking Control, Tool Calling, MoE Routing, RAG, and Session Persistence Moonshot AI Releases Kimi K2.6 with Long-Horizon Coding, Agent Swarm Scaling to 300 Sub-Agents and 4,000 Coordinated Steps A Coding Implementation on Microsoft’s Phi-4-Mini for Quantized Inference Reasoning Tool Use RAG and LoRA Fine-Tuning OpenAI Scales Trusted Access for Cyber Defense With GPT-5.4-Cyber: a Fine-Tuned Model Built for Verified Security Defenders Moonshot AI and Tsinghua Researchers Propose PrfaaS: A Cross-Datacenter KVCache Architecture that Rethinks How LLMs are Served at Scale Meet OpenMythos: An Open-Source PyTorch Reconstruction of Claude Mythos Where 770M Parameters Match a 1.3B Transformer How TabPFN Leverages In-Context Learning to Achieve Superior Accuracy on Tabular Datasets Compared to Random Forest and CatBoost A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI NVIDIA Releases Ising: the First Open Quantum AI Model Family for Hybrid Quantum-Classical Systems xAI Launches Standalone Grok Speech-to-Text and Text-to-Speech APIs, Targeting Enterprise Voice Developers A Coding Tutorial for Running PrismML Bonsai 1-Bit LLM on CUDA with GGUF, Benchmarking, Chat, JSON, and RAG A Coding Guide for Property-Based Testing Using Hypothesis with Stateful, Differential, and Metamorphic Test Design Anthropic Releases Claude Opus 4.7: A Major Upgrade for Agentic Coding, High-Resolution Vision, and Long-Horizon Autonomous Tasks Google AI Releases Auto-Diagnose: An Large Language Model LLM-Based System to Diagnose Integration Test Failures at Scale A End-to-End Coding Guide to Running OpenAI GPT-OSS Open-Weight Models with Advanced Inference Workflows Top 19 AI Red Teaming Tools (2026): Secure Your ML Models A Coding Guide to Build a Production-Grade Background Task Processing System Using Huey with SQLite, Scheduling, Retries, Pipelines, and Concurrency Control Qwen Team Open-Sources Qwen3.6-35B-A3B: A Sparse MoE Vision-Language Model with 3B Active Parameters and Agentic Coding Capabilities OpenAI Launches GPT-Rosalind: Its First Life Sciences AI Model Built to Accelerate Drug Discovery and Genomics Research Building Transformer-Based NQS for Frustrated Spin Systems with NetKet UCSD and Together AI Research Introduces Parcae: A Stable Architecture for Looped Language Models That Achieves the Quality of a Transformer Twice the Size How to Build a Universal Long-Term Memory Layer for AI Agents Using Mem0 and OpenAI A Coding Implementation to Build Multi-Agent AI Systems with SmolAgents Using Code Execution, Tool Calling, and Dynamic Orchestration A Technical Deep Dive into the Essential Stages of Modern Large Language Model Training, Alignment, and Deployment Google AI Launches Gemini 3.1 Flash TTS: A New Benchmark in Expressive and Controllable AI Voice Google DeepMind Releases Gemini Robotics-ER 1.6: Bringing Enhanced Embodied Reasoning and Instrument Reading to Physical AI Google Launches ‘Skills’ in Chrome: Turning Reusable AI Prompts into One-Click Browser Workflows A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction TinyFish AI Releases Full Web Infrastructure Platform for AI Agents: Search, Fetch, Browser, and Agent Under One API Key NVIDIA and the University of Maryland Researchers Released Audio Flamingo Next (AF-Next): A Super Powerful and Open Large Audio-Language Model A Hands-On Coding Tutorial for Microsoft VibeVoice Covering Speaker-Aware ASR, Real-Time TTS, and Speech-to-Speech Pipelines Meta AI and KAUST Researchers Propose Neural Computers That Fold Computation, Memory, and I/O Into One Learned Model A Coding Implementation of MolmoAct for Depth-Aware Spatial Reasoning, Visual Trajectory Tracing, and Robotic Action Prediction MiniMax Just Open Sourced MiniMax M2.7: A Self-Evolving Agent Model that Scores 56.22% on SWE-Pro and 57.0% on Terminal Bench 2 Liquid AI Releases LFM2.5-VL-450M: a 450M-Parameter Vision-Language Model with Bounding Box Prediction, Multilingual Support, and Sub-250ms Edge Inference Researchers from MIT, NVIDIA, and Zhejiang University Propose TriAttention: A KV Cache Compression Method That Matches Full Attention at 2.5× Higher Throughput How to Build a Secure Local-First Agent Runtime with OpenClaw Gateway, Skills, and Controlled Tool Execution How Knowledge Distillation Compresses Ensemble Intelligence into a Single Deployable AI Model Alibaba’s Tongyi Lab Releases VimRAG: a Multimodal RAG Framework that Uses a Memory Graph to Navigate Massive Visual Contexts A Coding Guide to Markerless 3D Human Kinematics with Pose2Sim, RTMPose, and OpenSim NVIDIA Releases AITune: An Open-Source Inference Toolkit That Automatically Finds the Fastest Inference Backend for Any PyTorch Model Five AI Compute Architectures Every Engineer Should Know: CPUs, GPUs, TPUs, NPUs, and LPUs Compared An End-to-End Coding Guide to NVIDIA KVPress for Long-Context LLM Inference, KV Cache Compression, and Memory-Efficient Generation Meta Superintelligence Lab Releases Muse Spark: A Multimodal Reasoning Model With Thought Compression and Parallel Agents Sigmoid vs ReLU Activation Functions: The Inference Cost of Losing Geometric Context A Coding Guide to Build Advanced Document Intelligence Pipelines with Google LangExtract, OpenAI Models, Structured Extraction, and Interactive Visualization Google AI Research Introduces PaperOrchestra: A Multi-Agent Framework for Automated AI Research Paper Writing A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export
GLM-5.2 OpenAI-Compatible API: A Hands-On Guide to Reasoning Effort, Function Calling, and Long-Context Retrieval
Sana Hassan · 2026-06-23 · via MarkTechPost

In this tutorial, we work with GLM-5.2 and use its hosted, OpenAI-compatible API instead of running the full model locally. We begin by setting up multiple provider options, securely loading the API key, and creating a reusable chat wrapper that supports normal chat, thinking mode, streaming, tool calling, and token tracking. Then we move beyond a simple chatbot example and test the model in more practical situations, including reasoning-effort control, streamed reasoning and answers, function calling, a small tool-using agent, structured JSON output, long-context retrieval, and cost estimation. 

Setting Up the GLM-5.2 OpenAI-Compatible Client and Reusable Chat Wrapper

import sys, subprocess
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-U", "openai"], check=False)
import os, re, json, time, getpass
from openai import OpenAI
PROVIDERS = {
   "zai":         {"base_url": "https://api.z.ai/api/paas/v4/",   "model": "glm-5.2",        "env": "ZAI_API_KEY"},
   "openrouter":  {"base_url": "https://openrouter.ai/api/v1",    "model": "z-ai/glm-5.2",   "env": "OPENROUTER_API_KEY"},
   "together":    {"base_url": "https://api.together.xyz/v1",     "model": "zai-org/GLM-5.2","env": "TOGETHER_API_KEY"},
   "requesty":    {"base_url": "https://router.requesty.ai/v1",   "model": "zai/glm-5.2",    "env": "REQUESTY_API_KEY"},
   "huggingface": {"base_url": "https://router.huggingface.co/v1","model": "zai-org/GLM-5.2","env": "HF_TOKEN"},
}
PROVIDER = "zai"
CFG   = PROVIDERS[PROVIDER]
MODEL = CFG["model"]
def load_api_key(env_name):
   try:
       from google.colab import userdata
       v = userdata.get(env_name)
       if v: return v
   except Exception:
       pass
   if os.environ.get(env_name):
       return os.environ[env_name]
   return getpass.getpass(f"Enter your {env_name}: ")
client = OpenAI(api_key=load_api_key(CFG["env"]), base_url=CFG["base_url"])
PRICE_IN_PER_M, PRICE_OUT_PER_M = 1.40, 4.40
_USAGE = {"in": 0, "out": 0, "calls": 0}
def _track(usage):
   if usage:
       _USAGE["in"]    += getattr(usage, "prompt_tokens", 0) or 0
       _USAGE["out"]   += getattr(usage, "completion_tokens", 0) or 0
       _USAGE["calls"] += 1
def get_reasoning(obj):
   """Pull GLM's hidden reasoning trace from a message/delta (a provider-extra field)."""
   val = getattr(obj, "reasoning_content", None)
   if val: return val
   extra = getattr(obj, "model_extra", None) or {}
   if extra.get("reasoning_content"): return extra["reasoning_content"]
   try:    return obj.to_dict().get("reasoning_content")
   except Exception: return None
def chat(messages, effort=None, thinking=True, tools=None, tool_choice="auto",
        stream=False, max_tokens=2048, temperature=1.0, tool_stream=False):
   """
   effort:   None | "high" | "max"   (GLM-5.2 thinking-effort level; max is the model default)
   thinking: True -> deep thinking on; False -> off (fast, cheap, low-latency)
   GLM-specific params go through extra_body so any OpenAI client works.
   """
   extra = {"thinking": {"type": "enabled" if thinking else "disabled"}}
   if effort and thinking: extra["reasoning_effort"] = effort
   if tool_stream:         extra["tool_stream"] = True
   kwargs = dict(model=MODEL, messages=messages, max_tokens=max_tokens,
                 temperature=temperature, stream=stream, extra_body=extra)
   if tools:
       kwargs.update(tools=tools, tool_choice=tool_choice)
   if stream:
       kwargs["stream_options"] = {"include_usage": True}
   return client.chat.completions.create(**kwargs)

We set up the complete foundation for using GLM-5.2 through an OpenAI-compatible API. We define multiple provider options, load the API key securely, create the OpenAI client, and set up token-cost tracking for the entire notebook. We also build a reusable chat wrapper so that every subsequent demo can use thinking mode, reasoning effort, streaming, tool calling, and provider-specific parameters cleanly.

Basic Chat, Thinking-Effort Control, and Streamed Reasoning with GLM-5.2

def demo_basic():
   print("\n=== 1. BASIC CHAT / SANITY CHECK =========================")
   resp = chat([{"role": "system", "content": "You are a concise technical assistant."},
                {"role": "user",   "content": "In one sentence, what is GLM-5.2 best at?"}],
               thinking=False, max_tokens=200)
   _track(resp.usage)
   print(resp.choices[0].message.content.strip())
def demo_effort():
   print("\n=== 2. THINKING-EFFORT CONTROL (off / high / max) ========")
   problem = ("Train A leaves city A at 9:00 going 60 km/h toward city B. "
              "Train B leaves B (420 km away) at 9:30 going 90 km/h toward A. "
              "At what clock time do they meet? Show the key steps briefly.")
   for label, kw in [("thinking OFF", dict(thinking=False)),
                     ("effort=high",  dict(thinking=True, effort="high")),
                     ("effort=max",   dict(thinking=True, effort="max"))]:
       t0 = time.time()
       resp = chat([{"role": "user", "content": problem}], max_tokens=2000, **kw)
       dt = time.time() - t0
       _track(resp.usage)
       msg, u = resp.choices[0].message, resp.usage
       print(f"\n--- {label} | {dt:0.1f}s | out_tokens={getattr(u,'completion_tokens',0)} ---")
       r = get_reasoning(msg)
       if r:
           print("  [reasoning, first 220 chars]: " + " ".join(r.split())[:220] + " ...")
       print("  : " + " ".join((msg.content or '').split())[:350])
def demo_streaming():
   print("\n=== 3. STREAMING: reasoning channel vs answer channel ====")
   stream = chat([{"role": "user", "content":
                   "Explain why the sky is blue, then give a one-line TL;DR."}],
                 thinking=True, effort="high", stream=True, max_tokens=1200)
   saw_r = saw_a = False
   usage = None
   for chunk in stream:
       if getattr(chunk, "usage", None): usage = chunk.usage
       if not chunk.choices: continue
       delta = chunk.choices[0].delta
       r = get_reasoning(delta)
       if r:
           if not saw_r: print("\n[thinking] ", end="", flush=True); saw_r = True
           print(r, end="", flush=True)
       if getattr(delta, "content", None):
           if not saw_a: print("\n\n ", end="", flush=True); saw_a = True
           print(delta.content, end="", flush=True)
   print()
   _track(usage)

We start testing GLM-5.2 with basic chat, reasoning-effort control, and streaming output. We first run a simple sanity check, then compare the same problem across thinking-off, high-effort, and max-effort modes to observe changes in latency and output tokens. We also stream the model response so we can view the reasoning channel and the final answer separately as the response is being generated.

Function Calling and a Multi-Step Tool-Using GLM-5.2 Agent

def tool_calculator(expression: str):
   if not re.fullmatch(r"[0-9+\-*/(). %]+", expression or ""):
       return {"error": "unsupported characters"}
   try:    return {"result": eval(expression, {"__builtins__": {}}, {})}
   except Exception as e: return {"error": str(e)}
_CITY_POP = {"tokyo": 37_400_068, "delhi": 32_900_000, "shanghai": 28_500_000,
            "sao paulo": 22_400_000, "mexico city": 21_800_000}
def tool_city_population(city: str):
   return {"city": city, "population": _CITY_POP.get((city or "").strip().lower())}
TOOLS = [
   {"type": "function", "function": {
       "name": "calculator", "description": "Evaluate basic arithmetic like '37400068/21800000'.",
       "parameters": {"type": "object", "properties": {"expression": {"type": "string"}},
                      "required": ["expression"]}}},
   {"type": "function", "function": {
       "name": "city_population", "description": "Look up the metro population of a city.",
       "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
                      "required": ["city"]}}},
]
TOOL_IMPLS = {"calculator": tool_calculator, "city_population": tool_city_population}
def run_tool_loop(messages, max_rounds=6, effort="max"):
   """Full loop: model -> tool_calls -> execute -> feed results back -> repeat."""
   for _ in range(max_rounds):
       resp = chat(messages, tools=TOOLS, thinking=True, effort=effort,
                   max_tokens=1500, temperature=0.3)
       _track(resp.usage)
       m = resp.choices[0].message
       if not getattr(m, "tool_calls", None):
           return m.content
       messages.append({
           "role": "assistant", "content": m.content or "",
           "tool_calls": [{"id": tc.id, "type": "function",
                           "function": {"name": tc.function.name,
                                        "arguments": tc.function.arguments}}
                          for tc in m.tool_calls]})
       for tc in m.tool_calls:
           try:    args = json.loads(tc.function.arguments or "{}")
           except json.JSONDecodeError: args = {}
           result = TOOL_IMPLS.get(tc.function.name, lambda **k: {"error": "unknown"})(**args)
           print(f"   ↳ {tc.function.name}({args}) -> {result}")
           messages.append({"role": "tool", "tool_call_id": tc.id,
                            "content": json.dumps(result)})
   return "(stopped: max tool rounds reached)"
def demo_tools():
   print("\n=== 4. FUNCTION / TOOL CALLING ===========================")
   q = ("How many times larger is Tokyo's metro population than Mexico City's? "
        "Use the tools, then answer with the ratio to one decimal place.")
   print("Final:", " ".join((run_tool_loop([{"role": "user", "content": q}]) or "").split()))
def demo_agent():
   print("\n=== 5. MINI MULTI-STEP AGENT (tools + max effort) ========")
   task = ("Rank Tokyo, Delhi, and Shanghai by metro population (largest first), "
           "then compute the combined population of the top two and report it. "
           "Use the tools for every lookup and sum; never guess numbers.")
   ans = run_tool_loop([{"role": "system", "content": "You are a careful analyst."},
                        {"role": "user",   "content": task}])
   print("Final:", " ".join((ans or "").split()))

We connect GLM-5.2 to external tools and build a small tool-using workflow. We define a calculator and a city-population lookup tool, register them in an OpenAI-style tool schema, and create a loop in which the model requests tool calls and receives tool results. We then use this setup for a direct function-calling task and a small multi-step agent that looks up populations, ranks cities, and performs calculations without guessing.

Structured JSON Output and Long-Context Retrieval with GLM-5.2

def tool_calculator(expression: str):
   if not re.fullmatch(r"[0-9+\-*/(). %]+", expression or ""):
       return {"error": "unsupported characters"}
   try:    return {"result": eval(expression, {"__builtins__": {}}, {})}
   except Exception as e: return {"error": str(e)}
_CITY_POP = {"tokyo": 37_400_068, "delhi": 32_900_000, "shanghai": 28_500_000,
            "sao paulo": 22_400_000, "mexico city": 21_800_000}
def tool_city_population(city: str):
   return {"city": city, "population": _CITY_POP.get((city or "").strip().lower())}
TOOLS = [
   {"type": "function", "function": {
       "name": "calculator", "description": "Evaluate basic arithmetic like '37400068/21800000'.",
       "parameters": {"type": "object", "properties": {"expression": {"type": "string"}},
                      "required": ["expression"]}}},
   {"type": "function", "function": {
       "name": "city_population", "description": "Look up the metro population of a city.",
       "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
                      "required": ["city"]}}},
]
TOOL_IMPLS = {"calculator": tool_calculator, "city_population": tool_city_population}
def run_tool_loop(messages, max_rounds=6, effort="max"):
   """Full loop: model -> tool_calls -> execute -> feed results back -> repeat."""
   for _ in range(max_rounds):
       resp = chat(messages, tools=TOOLS, thinking=True, effort=effort,
                   max_tokens=1500, temperature=0.3)
       _track(resp.usage)
       m = resp.choices[0].message
       if not getattr(m, "tool_calls", None):
           return m.content
       messages.append({
           "role": "assistant", "content": m.content or "",
           "tool_calls": [{"id": tc.id, "type": "function",
                           "function": {"name": tc.function.name,
                                        "arguments": tc.function.arguments}}
                          for tc in m.tool_calls]})
       for tc in m.tool_calls:
           try:    args = json.loads(tc.function.arguments or "{}")
           except json.JSONDecodeError: args = {}
           result = TOOL_IMPLS.get(tc.function.name, lambda **k: {"error": "unknown"})(**args)
           print(f"   ↳ {tc.function.name}({args}) -> {result}")
           messages.append({"role": "tool", "tool_call_id": tc.id,
                            "content": json.dumps(result)})
   return "(stopped: max tool rounds reached)"
def demo_tools():
   print("\n=== 4. FUNCTION / TOOL CALLING ===========================")
   q = ("How many times larger is Tokyo's metro population than Mexico City's? "
        "Use the tools, then answer with the ratio to one decimal place.")
   print("Final:", " ".join((run_tool_loop([{"role": "user", "content": q}]) or "").split()))
def demo_agent():
   print("\n=== 5. MINI MULTI-STEP AGENT (tools + max effort) ========")
   task = ("Rank Tokyo, Delhi, and Shanghai by metro population (largest first), "
           "then compute the combined population of the top two and report it. "
           "Use the tools for every lookup and sum; never guess numbers.")
   ans = run_tool_loop([{"role": "system", "content": "You are a careful analyst."},
                        {"role": "user",   "content": task}])
   print("Final:", " ".join((ans or "").split()))

We focus on reliable, structured output and long-context retrieval. We create a JSON extraction helper, ask the model to return a strict JSON object, and retry once if the first response is not valid JSON. We also build a synthetic long document with a hidden “needle” and send it to GLM-5.2 to check whether the model retrieves the exact launch code from the provided context.

Running All Demos with GLM-5.2 Token and Cost Accounting

def cost_summary():
   print("\n=== 8. TOKEN + COST ACCOUNTING ===========================")
   cost = _USAGE["in"]/1e6*PRICE_IN_PER_M + _USAGE["out"]/1e6*PRICE_OUT_PER_M
   print(f"  calls: {_USAGE['calls']} | input: {_USAGE['in']:,} tok | output: {_USAGE['out']:,} tok")
   print(f"  estimated spend @ ${PRICE_IN_PER_M}/{PRICE_OUT_PER_M} per 1M: ${cost:0.4f}")
DEMOS = [demo_basic, demo_effort, demo_streaming, demo_tools,
        demo_agent, demo_structured, demo_long_context]
print(f"Provider={PROVIDER}   model={MODEL}")
for fn in DEMOS:
   try:    fn()
   except Exception as e:
       print(f"  [skipped {fn.__name__}: {type(e).__name__}: {e}]")
cost_summary()
print("\nDone. Tweak PROVIDER / effort / max_tokens and re-run any demo function.")

We finish the tutorial by collecting usage information and running all demos from top to bottom. We calculate the estimated cost from total input and output tokens, then print a compact summary of calls, token counts, and spend. We also use a driver loop so that a single failed demo does not halt the entire notebook, making the tutorial easier to run, debug, and reuse.

Conclusion

In conclusion, we have a practical and reusable workflow for using GLM-5.2 in Python applications. We learned how to control its reasoning behavior, compare different thinking modes, connect it with tools, validate structured outputs, test long-context inputs, and monitor token usage with estimated cost. It provides us a strong starting point for building more advanced systems such as research assistants, document analysis tools, coding agents, long-context retrieval workflows, or API-based reasoning pipelines. We finished with a setup that is lightweight enough for Colab but still close to how we would build with GLM-5.2 in a real project.


Check out the Full Codes hereAlso, feel free to follow us on Twitter and don’t forget to join our 150k+ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us

Sana Hassan

Sana Hassan, a consulting intern at Marktechpost and dual-degree student at IIT Madras, is passionate about applying technology and AI to address real-world challenges. With a keen interest in solving practical problems, he brings a fresh perspective to the intersection of AI and real-life solutions.