Skip to main content





Tutorial: Evaluating Z.AI GLM 4.5 Using W&B Inference and Weave
Running and evaluating Z.AI GLM 4.5 with W&B Inference and Weave.
Last updated: March 2, 2026
In this tutorial, we'll explore how to run and evaluate the Z.AI GLM 4.5 model, one of the most powerful open source language models available today, using Weights & Biases Inference. We'll walk through deploying GLM 4.5 on W&B Inference and leveraging W&B Weave to trace every request, inspect model outputs, and build a systematic evaluation pipeline.
Whether you're building autonomous agents, exploring GLM 4.5's exceptional multilingual capabilities, or benchmarking its reasoning performance against closed source competitors, this guide will help you create a transparent, observable workflow from experimentation to production.
Table of contents
What is Z.AI GLM 4.5?W&B InferenceW&B WeaveTutorial: Running inference with Z.AI GLM 4.5 using W&B inferencePrerequisitesStep 1: Install dependencies & importsStep 2: ConfigurationStep 3: Initialize weave & clientStep 4: Define benchmark datasetsStep 5: Create weave model classStep 6: Define scorersStep 7: Evaluation runnerStep 8: Save results & runInspecting the "Thinking" process in Weave⭐ Best practices📈 Monitor quality, cost, and latency together🤖 Leverage dual mode reasoning🎯 Use the recommended temperature🚦 Know when GLM 4.5 excels🧪 Evaluate on realistic, task-specific data📊 Monitor everything🚀 What's next?
What is Z.AI GLM 4.5?
Z.AI GLM 4.5 is Zhipu AI's flagship open source large language model, designed specifically for agentic AI applications. Released in July 2025, GLM 4.5 represents a breakthrough in combining massive scale with practical usability through its innovative Mixture of Experts (MoE) architecture. Built with 355 billion total parameters and 32 billion active parameters per inference, GLM 4.5 delivers exceptional performance while maintaining computational efficiency. Some of its key features include:
- Dual mode reasoning: "Thinking" mode for complex reasoning and tool use, "non-thinking" mode for instant responses
- Native tool calling capabilities for building autonomous agents
- 90.6% tool use success rate in coding tasks, outperforming Claude 4 Sonnet and Kimi K2
- Multilingual proficiency across 24+ languages with exceptional English Chinese bilingual capabilities
- MIT open source license for commercial and noncommercial use
Among today's most capable open weight language models, Z.AI GLM 4.5 firmly earns its place as a top choice for agentic AI applications and complex reasoning tasks.
W&B Inference
W&B Inference is a managed inference service that lets you run, test, and deploy large language models without hosting the infrastructure yourself. It provides an OpenAI compatible API, so you can call models using familiar SDKs while W&B handles scaling, routing, and performance behind the scenes.

Weights & Biases Inference provides access to a wide range of popular language models, including Meta’s Llama, OpenAI’s GPT models, DeepSeek, Moonshot (Kimi), and many others. You can explore the full list of available models and their configurations directly through the W&B Inference model catalog using the provided link.
In short, W&B Inference removes the operational overhead of serving LLMs while giving you deep visibility into how they behave, making it ideal for benchmarking, evaluation, and real world LLM applications.
W&B Weave

W&B Weave is a powerful LLM observability and debugging platform by Weights & Biases that helps developers track, evaluate, and improve AI applications built with large language models. It enables end to end visibility into prompts, model outputs, traces, and evaluations, making it easier to understand how LLMs behave in real world workflows.
With Weave, teams can debug failures, compare model versions, monitor performance, and iterate faster, all through an intuitive interface. It's especially useful for building reliable, production ready AI systems, turning experimentation into confidence and insight.
Tutorial: Running inference with Z.AI GLM 4.5 using W&B inference
For the practical section, we’ll run Z.AI GLM 4.5 in a Kaggle notebook.
The same code works seamlessly in other Python environments, such as Jupyter notebooks or any standard local or cloud based Python setup.
💡
Prerequisites
Some required and optional requirements for this tutorial include:
Account requirements
- A Weights & Biases account
- W&B API key from https://wandb.ai/authorize
Technical requirements
- Python 3.9 or higher
- Basic familiarity with Python
- Kaggle/Jupyter Notebook or any Python environment
Helpful background (optional)
- Familiarity with the OpenAI SDK (W&B Inference uses an OpenAI compatible API)
- Basic understanding of LLM concepts (prompts, tokens, temperature)
- Experience with chat completions APIs
Step 1: Install dependencies & imports
Install and import the required libraries. We use OpenAI for the API client (W&B Inference uses OpenAI compatible endpoints), weave for tracing and evaluation, and wandb for experiment tracking.
! pip install openai weave requests wandbimport osimport jsonimport timeimport reimport openaiimport weaveimport wandb
Step 2: Configuration
Moving on, set up your W&B API key, project name, and model ID. The project follows the format team-name/project-name, and the model ID references GLM 4.5 from the W&B Inference model registry.
WANDB_API_KEY = os.getenv("WANDB_API_KEY", "your-api-key-here")TEAM_PROJECT = "your-team/your-project"MODEL_ID = "zai-org/GLM-4.5"wandb.login(key=WANDB_API_KEY, relogin=True)
Step 3: Initialize weave & client
We will be relying heavily on Weave for automatic tracing and creating an OpenAI-compatible client pointing to the W&B Inference endpoint. All API calls will be logged to your Weave dashboard.
weave.init(TEAM_PROJECT)print(f"✓ Weave initialized for project: {TEAM_PROJECT}")client = openai.OpenAI(base_url="https://api.inference.wandb.ai/v1",api_key=WANDB_API_KEY,project=TEAM_PROJECT,)print(f"✓ Client ready for model: {MODEL_ID}")
Step 4: Define benchmark datasets
For a comprehensive evaluation, we will be defining 43 benchmark questions across 7 categories: math reasoning, logic reasoning, code generation, instruction following, multilingual, debugging, and data extraction. Each question includes difficulty level, expected answer, and validation criteria.
4.1 Math reasoning
MATH_REASONING_DATASET = [{"id": "math_01_medium", "level": "medium", "question": "A store sells apples at $3 per kg. If you buy more than 5 kg, you get 10% off the entire purchase. How much do you pay for 8 kg? Answer with just the number (no $ sign).", "expected": "21.6", "category": "math_reasoning"},{"id": "math_02_hard", "level": "hard", "question": "A car travels from A to B at 60 km/h and returns at 40 km/h. What is the average speed for the entire round trip in km/h? Answer with just the number.", "expected": "48", "category": "math_reasoning"},{"id": "math_03_very_hard", "level": "very_hard", "question": "In a class, 60% of students passed math, 70% passed English, and 40% passed both. What percentage of students failed both subjects? Answer with just the number.", "expected": "10", "category": "math_reasoning"},{"id": "math_04_expert", "level": "expert", "question": "A merchant marks up goods by 50% above cost, then offers two successive discounts of 20% and 10%. What is the final profit or loss percentage? Answer as a positive number for profit or negative for loss.", "expected": "8", "category": "math_reasoning"},{"id": "math_05_expert", "level": "expert", "question": "A can complete a job in 12 days. B can complete it in 18 days. They work together for 4 days, then A leaves. How many more days does B need to finish alone? Answer with just the number.", "expected": "8", "category": "math_reasoning"},{"id": "math_06_extreme", "level": "extreme", "question": "A sum doubles in 5 years at compound interest. In how many years will it become 8 times itself? Answer with just the number.", "expected": "15", "category": "math_reasoning"},{"id": "math_07_extreme", "level": "extreme", "question": "A bag has 5 red and 3 blue balls. You draw 3 balls without replacement. What is the probability of getting exactly 2 red balls? Express as a simplified fraction in format 'a/b'.", "expected": "15/28", "category": "math_reasoning"},{"id": "math_08_extreme", "level": "extreme", "question": "What is the remainder when 2^100 is divided by 7? Answer with just the number.", "expected": "2", "category": "math_reasoning"},]
4.2 Logic reasoning
LOGIC_REASONING_DATASET = [{"id": "logic_01_medium", "level": "medium", "question": "If all birds can fly, and penguins are birds, then penguins can fly. Is this argument logically VALID (ignoring real world facts)? Answer only 'valid' or 'invalid'.", "expected": "valid", "category": "logic_reasoning"},{"id": "logic_02_hard", "level": "hard", "question": "Statement: 'If it's a dog, it's a mammal.' We observe: 'It's a mammal.' Can we conclude: 'It's a dog'? Answer 'yes' or 'no'.", "expected": "no", "category": "logic_reasoning"},{"id": "logic_03_very_hard", "level": "very_hard", "question": "Given: 'All successful people work hard.' Which statement MUST be true?\nA) All hard workers are successful\nB) Some non-hard workers are not successful\nC) No unsuccessful person works hard\nD) Some unsuccessful people don't work hard\nAnswer with just the letter.", "expected": "B", "category": "logic_reasoning"},{"id": "logic_04_expert", "level": "expert", "question": "On an island, Knights always tell truth, Knaves always lie. A says: 'B is a Knight.' B says: 'A and I are different types.' What is A? Answer 'knight' or 'knave'.", "expected": "knave", "category": "logic_reasoning"},{"id": "logic_05_expert", "level": "expert", "question": "Five people (A,B,C,D,E) sit in a row. B is not at either end. C is immediately right of A. E is not adjacent to B. D is at the left end. Who sits at the right end? Answer with one letter.", "expected": "E", "category": "logic_reasoning"},{"id": "logic_06_extreme", "level": "extreme", "question": "In a village, the barber shaves all and only those who do not shave themselves. Does the barber shave himself? Answer 'yes', 'no', or 'paradox'.", "expected": "paradox", "category": "logic_reasoning"},{"id": "logic_07_extreme", "level": "extreme", "question": "Given these rules for a game:\n1. If you have a RED card, you must have a BLUE card.\n2. If you have a GREEN card, you cannot have a RED card.\n3. Everyone has at least one of: RED, GREEN.\nCan someone have only a GREEN card? Answer 'yes' or 'no'.", "expected": "yes", "category": "logic_reasoning"},{"id": "logic_08_extreme", "level": "extreme", "question": "Three suspects: A, B, C. Facts:\n- The crime happened at 3 PM\n- A was with B from 2-4 PM\n- C was alone from 1-5 PM\n- The criminal acted alone\n- At least one of them is guilty\nWho committed the crime? Answer with one letter, or 'impossible' if contradictory.", "expected": "C", "category": "logic_reasoning"},]
4.3 Code generation
CODE_GENERATION_DATASET = [{"id": "code_01_hard", "level": "hard", "question": """Write a Python function `merge_intervals(intervals)` that:- Takes a list of intervals as [start, end] pairs- Returns merged overlapping intervals, sorted by start time- Example: merge_intervals([[1,3],[2,6],[8,10],[15,18]]) → [[1,6],[8,10],[15,18]]Provide only the function code, no explanations.""", "expected": "def merge_intervals", "test_cases": [("merge_intervals([[1,3],[2,6],[8,10],[15,18]])", [[1,6],[8,10],[15,18]]), ("merge_intervals([[1,4],[4,5]])", [[1,5]]), ("merge_intervals([[1,4],[0,4]])", [[0,4]]), ("merge_intervals([[1,4],[2,3]])", [[1,4]]), ("merge_intervals([])", [])], "category": "code_generation"},{"id": "code_02_hard", "level": "hard", "question": """Write a Python function `find_anagrams(s, p)` that:- Finds all start indices of p's anagrams in s- Returns a list of starting indices- Example: find_anagrams("cbaebabacd", "abc") → [0, 6]Use O(n) time complexity. Provide only the function code.""", "expected": "def find_anagrams", "test_cases": [('find_anagrams("cbaebabacd", "abc")', [0, 6]), ('find_anagrams("abab", "ab")', [0, 1, 2]), ('find_anagrams("hello", "xyz")', [])], "category": "code_generation"},{"id": "code_03_extreme", "level": "extreme", "question": """Write a Python class LRUCache(capacity) with methods:- get(key): returns the value if key exists, otherwise returns -1- put(key, value): inserts or updates the key-value pairRequirements:- Both operations must be O(1) time complexity- When capacity is exceeded, evict the least recently used itemProvide only the complete Python code, no explanations.""", "expected": "class LRUCache", "test_cases": [("cache = LRUCache(2)", None), ("cache.put(1, 1)", None), ("cache.put(2, 2)", None), ("cache.get(1)", 1), ("cache.put(3, 3)", None), ("cache.get(2)", -1), ("cache.get(3)", 3)], "category": "code_generation"},{"id": "code_04_extreme", "level": "extreme", "question": """Write a Python function `min_window(s, t)` that:- Finds the minimum window substring of s that contains all characters in t- Returns "" if no such window exists- Example: min_window("ADOBECODEBANC", "ABC") → "BANC"Must be O(n) time complexity. Provide only the function code.""", "expected": "def min_window", "test_cases": [('min_window("ADOBECODEBANC", "ABC")', "BANC"), ('min_window("a", "a")', "a"), ('min_window("a", "aa")', "")], "category": "code_generation"},{"id": "code_05_extreme", "level": "extreme", "question": """Write a Python function `calculate(s)` that:- Evaluates a basic calculator expression string- Supports +, -, *, / and parentheses ()- Follows standard operator precedence- Example: calculate("3+2*2") → 7Handle spaces in input. Provide only the function code.""", "expected": "def calculate", "test_cases": [('calculate("3+2*2")', 7), ('calculate("1+1")', 2), ('calculate(" 2-1 + 2 ")', 3)], "category": "code_generation"},]
4.4 Instruction following
INSTRUCTION_FOLLOWING_DATASET = [{"id": "instruction_01_medium", "level": "medium", "question": """Write a haiku about programming. Requirements:- Line 1: exactly 5 syllables- Line 2: exactly 7 syllables- Line 3: exactly 5 syllables- Must mention "code" or "bug" somewhere- NO title, just the three lines""", "expected": None, "constraints": {"line_count": 3, "must_contain_any": ["code", "bug"], "no_title": True}, "category": "instruction_following"},{"id": "instruction_02_hard", "level": "hard", "question": """Generate a JSON object with EXACTLY this structure:{"users": [exactly 3 users],each user has: "id" (number 1-100), "name" (string, 4-8 chars), "active" (boolean)}Rules:- At least one user must have active=false- All names must start with uppercase letter- IDs must be unique and in ascending order- Output ONLY valid JSON, no explanation""", "expected": None, "constraints": {"valid_json": True, "has_users_array": True, "user_count": 3}, "category": "instruction_following"},{"id": "instruction_03_hard", "level": "hard", "question": """Write exactly 5 sentences about climate change following ALL these rules:1. Sentence 1 must be a question2. Sentence 2 must contain exactly 2 numbers3. Sentence 3 must start with "However"4. Sentence 4 must be under 10 words5. Sentence 5 must end with an exclamation mark6. Total response must be 50-80 words7. Do NOT use the words: "global", "warming", "crisis"Output only the 5 sentences.""", "expected": None, "constraints": {"sentence_count": 5, "s1_is_question": True, "s3_starts_with_however": True, "s5_ends_exclamation": True, "word_count_min": 50, "word_count_max": 80, "forbidden_words": ["global", "warming", "crisis"]}, "category": "instruction_following"},{"id": "instruction_04_extreme", "level": "extreme", "question": """Create a 4x4 grid representing a maze:- Use # for walls, . for paths, S for start, E for end- S must be in top-left corner- E must be in bottom-right corner- There must be exactly ONE valid path from S to E- Surround the entire maze with # walls (making it 6x6 total)Output ONLY the maze, nothing else.""", "expected": None, "constraints": {"has_S": True, "has_E": True, "has_walls": True, "has_path": True}, "category": "instruction_following"},{"id": "instruction_05_extreme", "level": "extreme", "question": """Write a Python function with these EXACT constraints:1. Function name must be "process_data"2. Must have exactly 3 parameters: lst, threshold, flag3. Must contain exactly 2 for loops (not while, not comprehensions)4. Must contain exactly 1 if statement and 1 else clause5. Must have exactly 3 comments (lines starting with #)6. Must return a list7. Do not include any code outside the functionOutput ONLY the function.""", "expected": None, "constraints": {"function_name": "process_data", "has_if": True, "has_else": True, "has_comments": True, "returns_list": True}, "category": "instruction_following"},{"id": "instruction_06_extreme", "level": "extreme", "question": """Generate a fictional person profile following ALL rules:FORMAT (use exactly this structure):NAME: [first] [last]AGE: [number]JOB: [occupation]HOBBIES: [hobby1], [hobby2], [hobby3]BIO: [one sentence bio]RULES:- First name: exactly 4 letters, starts with J- Last name: exactly 6 letters, ends with "son"- Age: prime number between 20-40- Job: compound word (two words joined, like "firefighter")- Hobbies: all must start with different letters- Bio: exactly 12 words, must mention their jobOutput ONLY the profile in the exact format above.""", "expected": None, "constraints": {"has_name_line": True, "has_age_line": True, "has_job_line": True, "has_hobbies_line": True, "has_bio_line": True}, "category": "instruction_following"},]
4.5 Long context
def generate_long_context_dataset(difficulty: str = "expert") -> dict:filler_topics = ["artificial intelligence", "quantum computing", "blockchain", "cybersecurity", "cloud architecture", "machine learning", "data engineering", "DevOps practices", "microservices", "API design", "database optimization", "network protocols"]filler_template = """The field of {topic} continues to evolve rapidly. Industry experts have noted significantadvancements in recent years, with major technology companies investing heavily in researchand development. Best practices in {topic} emphasize scalability, maintainability, andsecurity. Teams working in this area often collaborate across multiple time zones, usingmodern tools for version control and continuous integration. Documentation remains crucialfor knowledge transfer, and regular code reviews help maintain quality standards."""distractors = ["CRITICAL: The primary encryption key is ALPHA-7749-BETA (24 chars)","AUTH_TOKEN: GAMMA-8832-DELTA - master token for system access","IMPORTANT: Secret passphrase is 'BlueHorse42Running'","System password: EPSILON-9921-ZETA - required for admin access","API_KEY: THETA-1156-IOTA - for external integrations","Recovery code: KAPPA-2267-LAMBDA - store securely","Master credential: SIGMA-4478-OMEGA - highest priority",]needles = {"expert": [("The actual database password is: NEPTUNE-3847-MARS", "NEPTUNE-3847-MARS", "35%")],"extreme": [("First fragment of the launch code: APOLLO", "APOLLO", "25%"), ("Second fragment of the launch code: ELEVEN", "ELEVEN", "55%"), ("Third fragment of the launch code: LUNAR", "LUNAR", "85%")],"nightmare": [("Agent codename for Operation Sunrise: FALCON", "FALCON", "15%"), ("The meeting point coordinates encoded as: 47N-122W", "47N-122W", "40%"), ("Extraction time in military format: 0347", "0347", "65%"), ("The safe combination sequence is: 27-14-33", "27-14-33", "90%")],}target_words = {"expert": 15000, "extreme": 30000, "nightmare": 50000}[difficulty]paragraphs_needed = target_words // 100document_parts = []needle_list = needles[difficulty]distractor_positions = [int(paragraphs_needed * p) for p in [0.1, 0.2, 0.3, 0.45, 0.5, 0.6, 0.75]]needle_positions = [int(paragraphs_needed * float(n[2].strip('%'))/100) for n in needle_list]for i in range(paragraphs_needed):document_parts.append(filler_template.format(topic=filler_topics[i % len(filler_topics)]))if i in distractor_positions:document_parts.append(f"\n[SYSTEM NOTICE: {distractors[distractor_positions.index(i) % len(distractors)]}]\n")for j, (needle_text, _, _) in enumerate(needle_list):if i == needle_positions[j]:document_parts.append(f"\n[CONFIDENTIAL: {needle_text}]\n")full_document = "\n\n".join(document_parts)questions = {"expert": ("What is the actual database password mentioned in the document? Provide ONLY the password, nothing else.", ["NEPTUNE-3847-MARS"]),"extreme": ("Find all three fragments of the launch code in the document. List them in order separated by hyphens. Format: WORD-WORD-WORD", ["APOLLO-ELEVEN-LUNAR"]),"nightmare": ("Find ALL four pieces of intelligence: 1) Agent codename 2) Coordinates 3) Extraction time 4) Safe combination. Format: CODENAME / COORDINATES / TIME / COMBINATION", ["FALCON / 47N-122W / 0347 / 27-14-33", "FALCON/47N-122W/0347/27-14-33"]),}return {"id": f"long_context_{difficulty}", "level": difficulty, "document": full_document,"question": questions[difficulty][0], "expected": questions[difficulty][1],"needle_count": len(needle_list), "distractor_count": len(distractors),"word_count": len(full_document.split()), "category": "long_context"}LONG_CONTEXT_DATASET = [generate_long_context_dataset("expert"), generate_long_context_dataset("extreme"), generate_long_context_dataset("nightmare")]
4.6 Multilingual
MULTILINGUAL_DATASET = [{"id": "multilingual_01_spanish", "level": "hard", "question": """Explica en español cómo funciona el algoritmo de búsqueda binaria. Incluye: 1. Complejidad temporal (Big O notation) 2. Requisito principal de los datos 3. Un caso donde NO funcionaría. Responde completamente en español.""", "requirements": {"language": "Spanish", "must_mention": ["O(log n)", "ordenado"], "min_sentences": 5}, "category": "multilingual"},{"id": "multilingual_02_french", "level": "hard", "question": """En français, résolvez ce problème: Un train part de Paris à 9h00 à 120 km/h. Un autre train part de Lyon (465 km de Paris) à 10h00 à 150 km/h vers Paris. À quelle heure se croiseront-ils? Montrez les calculs, réponse en format HH:MM.""", "requirements": {"language": "French", "must_show_calculation": True, "expected_answer": "12:30"}, "category": "multilingual"},{"id": "multilingual_03_german", "level": "extreme", "question": """Auf Deutsch, erkläre den Unterschied zwischen: 1. Stack und Heap Speicher 2. Pass by Value und Pass by Reference 3. Kompilierte und interpretierte Sprachen. Gib für jeden Punkt ein Beispiel. Antworte vollständig auf Deutsch.""", "requirements": {"language": "German", "sections": 3, "must_have_examples": True}, "category": "multilingual"},{"id": "multilingual_04_thai", "level": "extreme", "question": """อธิบายความแตกต่างระหว่าง LSTM และ GRU ในบริบทของ recurrent neural networks โดยครอบคลุม: 1) สมการทางคณิตศาสตร์ของแต่ละ gate 2) ความซับซ้อนในการคำนวณ 3) กรณีการใช้งานที่เหมาะสม ตอบเป็นภาษาไทย""", "requirements": {"language": "Thai", "must_mention": ["LSTM", "GRU", "gate"], "min_sentences": 5}, "category": "multilingual"},{"id": "multilingual_05_mixed", "level": "extreme", "question": """Translate into THREE languages (Spanish, French, German). Preserve technical terms in English."The API uses REST architecture with JSON payloads. Authentication is handled via OAuth 2.0 tokens with a 3600-second expiry."Format:[ES]: (Spanish)[FR]: (French)[DE]: (German)""", "requirements": {"has_spanish": True, "has_french": True, "has_german": True}, "category": "multilingual"},]
4.7 Debugging
DEBUGGING_DATASET = [{"id": "debug_01_python", "level": "hard", "question": """Find ALL bugs in this Python code. There are exactly 4 bugs.```pythondef find_duplicates(lst):seen = set()duplicates = []for item in lst:if item in seen:duplicates.add(item)else:seen.add(item)return sorted(duplicates, reverse=true)result = find_duplicates([1, 2, 2, 3, 3, 3])print(f"Found: {results}")```Format: Line X: problem → fix""", "expected_bugs": [{"line": 5, "issue": "duplicates.add on list"}, {"line": 8, "issue": "true not True"}, {"line": 11, "issue": "results undefined"}], "bug_count": 4, "category": "debugging"},{"id": "debug_02_javascript", "level": "hard", "question": """Find ALL bugs in this JavaScript code. There are exactly 5 bugs.```javascriptconst fetchUserData = async (userId) => {const response = await fetch(`/api/users/${userId}`)const data = response.json()if (response.status = 200) {return { success: true, user: data }} else {return { success: false, error: response.statusText }}}```Format: Line X: problem → fix""", "expected_bugs": [{"line": 3, "issue": "missing await"}, {"line": 5, "issue": "assignment not comparison"}, {"line": 2, "issue": "missing error handling"}], "bug_count": 5, "category": "debugging"},{"id": "debug_03_race_condition", "level": "extreme", "question": """This Python code has a race condition. Find ALL issues.```pythonimport threadingcounter = 0lock = threading.Lock()def increment():global counterfor _ in range(100000):temp = countercounter = temp + 1threads = []for i in range(4):t = threading.Thread(target=increment())threads.append(t)t.start()```Format: Line X: problem → fix""", "expected_bugs": [{"line": 9, "issue": "no lock used"}, {"line": 13, "issue": "increment() called immediately"}], "bug_count": 3, "category": "debugging"},{"id": "debug_04_sql_injection", "level": "extreme", "question": """This code has security vulnerabilities. Find ALL issues.```pythonimport sqlite3def get_user(username, password):conn = sqlite3.connect('users.db')cursor = conn.cursor()query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"cursor.execute(query)user = cursor.fetchone()return user```Format: Line X: problem → fix""", "expected_bugs": [{"line": 7, "issue": "SQL injection"}, {"line": 7, "issue": "password plain text"}, {"line": 10, "issue": "connection not closed"}], "bug_count": 6, "category": "debugging"},{"id": "debug_05_memory_leak", "level": "extreme", "question": """This JavaScript has memory leaks. Find ALL bugs.```javascriptclass DataProcessor {constructor() {this.data = []this.listeners = []window.addEventListener('resize', this.handleResize)}handleResize() {console.log('Resizing, data:', this.data.length)}addListener(callback) {this.listeners.push(callback)setInterval(() => callback(this.data), 1000)}destroy() {this.data = []this.listeners = []}}```Format: Description → fix""", "expected_bugs": [{"line": 5, "issue": "event listener not removed"}, {"line": 5, "issue": "handleResize this binding"}, {"line": 13, "issue": "intervals never cleared"}], "bug_count": 4, "category": "debugging"},{"id": "debug_06_async", "level": "extreme", "question": """This async Python code has multiple bugs. Find ALL of them.```pythonimport asyncioasync def fetch_data(url):await asyncio.sleep(1)return f"Data from {url}"async def process_urls(urls):results = []for url in urls:result = fetch_data(url)results.append(result)return resultsasync def main():urls = ["http://api.com/1", "http://api.com/2"]results = process_urls(urls)for r in results:print(r)asyncio.run(main())```Format: Line X: problem → fix""", "expected_bugs": [{"line": 10, "issue": "missing await on fetch_data"}, {"line": 16, "issue": "missing await on process_urls"}], "bug_count": 4, "category": "debugging"},]
4.8 Data extraction
DATA_EXTRACTION_DATASET = [{"id": "extraction_01_nested_json", "level": "hard", "question": """Extract all email addresses from this nested JSON. Return as a flat JSON array of unique emails, sorted alphabetically.```json{"company": {"departments": [{"name": "Engineering", "lead": {"email": "[email protected]"}, "members": [{"email": "[email protected]"}, {"email": "[email protected]"}]}, {"name": "Sales", "lead": {"email": "[email protected]"}, "members": [{"email": "[email protected]"}, {"email": "[email protected]"}]}], "contact": "[email protected]"}}```Output ONLY the JSON array.""", "expected": '["alice@company.com", "bob@company.com", "charlie@company.com", "diana@company.com", "eve@company.com", "info@company.com"]', "expected_count": 6, "category": "data_extraction"},{"id": "extraction_02_log_parsing", "level": "hard", "question": """Parse these logs and output JSON with error counts by type.```2024-01-15 10:23:45 ERROR DatabaseError: Connection timeout2024-01-15 10:24:12 WARN MemoryWarning: High usage2024-01-15 10:25:33 ERROR ValidationError: Invalid input2024-01-15 10:26:01 ERROR DatabaseError: Query failed2024-01-15 10:28:44 ERROR NetworkError: Host unreachable2024-01-15 10:29:02 ERROR ValidationError: Missing field```Output: {"ErrorType": count, ...} for ERROR entries only. Output ONLY the JSON.""", "expected": '{"DatabaseError": 2, "ValidationError": 2, "NetworkError": 1}', "category": "data_extraction"},{"id": "extraction_03_xml_to_json", "level": "extreme", "question": """Convert this XML to JSON with proper types.```xml<library><book id="1" available="true"><title>The Great Gatsby</title><author>F. Scott Fitzgerald</author><year>1925</year><price currency="USD">12.99</price></book><book id="2" available="false"><title>1984</title><author>George Orwell</author><year>1949</year><price currency="GBP">9.99</price></book></library>```Requirements: id/year as integers, available as boolean, price as {amount, currency}. Output ONLY valid JSON.""", "expected_structure": {"library": [{"id": 1, "available": True, "title": "The Great Gatsby"}]}, "category": "data_extraction"},{"id": "extraction_04_markdown_table", "level": "extreme", "question": """Parse this markdown table and output as JSON with calculated fields.| Product | Q1 Sales | Q2 Sales | Q3 Sales | Q4 Sales ||---------|----------|----------|----------|----------|| Widget A | $1,234 | $2,345 | $1,890 | $3,210 || Widget B | $890 | $1,200 | $1,500 | $2,100 |Output JSON with each product as object, sales as numbers (no $ or ,), calculated "total" and "average" fields. Output ONLY JSON array.""", "expected_structure": [{"product": "Widget A", "total": 8679}], "category": "data_extraction"},{"id": "extraction_05_regex_transform", "level": "extreme", "question": """Extract function signatures from this code into JSON.```pythondef calculate_total(items: list[dict], tax_rate: float = 0.08) -> float:passasync def fetch_user(user_id: int, include_profile: bool = True) -> dict[str, any]:pass```Output JSON array with: name, async (boolean), parameters (array of {name, type, default}), return_type. Output ONLY JSON.""", "expected_structure": [{"name": "calculate_total", "async": False}], "category": "data_extraction"},]
Step 5: Create weave model class
Wrap the model in a Weave Model class with @weave.op() decorated methods. This automatically traces all predictions, logging inputs, outputs, and latency to your Weave project.
class GLM45Model(weave.Model):model_name: str = MODEL_IDsystem_prompt: str = "You are GLM 4.5, an intelligent assistant created by Zhipu AI. Be precise and concise."temperature: float = 0.3@weave.op()def predict(self, question: str, max_tokens: int = 2000) -> str:response = client.chat.completions.create(model=self.model_name,messages=[{"role": "system", "content": self.system_prompt}, {"role": "user", "content": question}],temperature=self.temperature,max_tokens=max_tokens,)return response.choices[0].message.content@weave.op()def predict_long_context(self, document: str, question: str) -> str:prompt = f"Read the following document carefully and answer the question.\n\nDOCUMENT:\n{document}\n\nQUESTION: {question}\n\nAnswer precisely based only on information found in the document."response = client.chat.completions.create(model=self.model_name,messages=[{"role": "system", "content": "You are a careful document analyst. Find and report specific information accurately."}, {"role": "user", "content": prompt}],temperature=0.1,max_tokens=500,)return response.choices[0].message.content
Step 6: Define scorers
We will then create 8 category specific scoring functions that extract answers from model outputs and compare against expected values. Each scorer handles different validation logic (exact match, code execution, constraint checking, etc.).
@weave.op()def math_scorer(output: str, expected: str) -> dict:output_clean = output.strip().lower().replace("$", "").replace(",", "").replace(" ", "")expected_clean = expected.strip().lower()numbers = re.findall(r'-?[\d.]+(?:/\d+)?', output_clean)if "/" in expected_clean:exact_match = expected_clean in output_cleanif not exact_match:try:num, den = map(int, expected_clean.split("/"))expected_decimal = num / denfor n in numbers:if "/" in n:n_num, n_den = map(int, n.split("/"))if abs(n_num/n_den - expected_decimal) < 0.001:exact_match = Truebreakexcept: passelse:try:expected_val = float(expected_clean)exact_match = any(abs(float(n) - expected_val) < 0.01 for n in numbers if n.replace('.','').replace('-','').isdigit())except:exact_match = expected_clean in output_cleanreturn {"exact_match": exact_match, "expected": expected, "score": 1.0 if exact_match else 0.0}@weave.op()def logic_scorer(output: str, expected: str) -> dict:output_clean = output.strip().lower()expected_clean = expected.strip().lower()first_line = output_clean.split('\n')[0].strip()first_words = first_line.split()[:5]if expected_clean in ["yes", "no", "valid", "invalid", "paradox"]:if expected_clean == "yes": match = "yes" in first_words and "no" not in first_words[:3]elif expected_clean == "no": match = "no" in first_words or "cannot" in first_wordselif expected_clean == "valid": match = "valid" in output_clean and "invalid" not in output_cleanelif expected_clean == "invalid": match = "invalid" in output_cleanelif expected_clean == "paradox": match = "paradox" in output_cleanelse: match = expected_clean in output_cleanelif len(expected_clean) == 1:patterns = [rf'^{expected_clean}[^a-z]', rf'answer[:\s]+{expected_clean}', rf'\({expected_clean}\)']match = any(re.search(p, output_clean) for p in patterns) or output_clean.strip().startswith(expected_clean)else: match = expected_clean in output_cleanreturn {"match": match, "expected": expected_clean, "score": 1.0 if match else 0.0}@weave.op()def code_scorer(output: str, test_cases: list) -> dict:results = {"syntax_valid": False, "tests_passed": 0, "total_tests": len([t for t in test_cases if t[1] is not None]) if test_cases else 0}code_block = outputif "```python" in output:match = re.search(r'```python\s*(.*?)\s*```', output, re.DOTALL)if match: code_block = match.group(1)elif "```" in output:match = re.search(r'```\s*(.*?)\s*```', output, re.DOTALL)if match: code_block = match.group(1)try:compile(code_block, '<string>', 'exec')results["syntax_valid"] = Trueexcept SyntaxError as e:results["syntax_error"] = str(e)results["score"] = 0.0return resultsif results["syntax_valid"] and test_cases:try:exec_globals = {}exec(code_block, exec_globals)for test_expr, expected in test_cases:if expected is None: exec(test_expr, exec_globals); continuetry:actual = eval(test_expr, exec_globals)if actual == expected: results["tests_passed"] += 1except: passexcept: passresults["score"] = results["tests_passed"] / results["total_tests"] if results["total_tests"] > 0 else (0.5 if results["syntax_valid"] else 0.0)return results@weave.op()def instruction_scorer(output: str, constraints: dict) -> dict:results = {"checks": [], "passed": 0, "total": 0}output_stripped = output.strip()for key, val in constraints.items():passed = Falseif key == "line_count": lines = [l for l in output_stripped.split('\n') if l.strip()]; passed = len(lines) == valelif key == "must_contain_any": passed = any(w.lower() in output_stripped.lower() for w in val)elif key == "valid_json":try: json.loads(output_stripped); passed = Trueexcept:try:match = re.search(r'```(?:json)?\s*([\s\S]*?)\s*```', output_stripped)if match: json.loads(match.group(1)); passed = Trueexcept: passelif key == "forbidden_words": passed = not any(w.lower() in output_stripped.lower() for w in val)elif key == "word_count_min": passed = len(output_stripped.split()) >= valelif key == "word_count_max": passed = len(output_stripped.split()) <= valelif key.startswith("has_"):check = key.replace("has_", "").replace("_line", "").replace("_", " ").upper()if check in ["S", "E"]: passed = check in output_strippedelif "LINE" in key.upper(): passed = check.split()[0] in output_stripped.upper()elif key == "has_walls": passed = "#" in output_strippedelif key == "has_path": passed = "." in output_strippedelif key == "has_if": passed = " if " in output_strippedelif key == "has_else": passed = "else" in output_strippedelif key == "has_comments": passed = "#" in output_strippedelse: passed = Trueelif key == "function_name": passed = val in output_strippedelif key == "returns_list": passed = "return" in output_stripped and "[" in output_strippedelse: continueresults["checks"].append({"constraint": key, "passed": passed}); results["total"] += 1if passed: results["passed"] += 1results["score"] = results["passed"] / results["total"] if results["total"] > 0 else 0.0return results@weave.op()def long_context_scorer(output: str, expected: list, needle_count: int) -> dict:output_upper = output.upper()distractor_patterns = ["ALPHA-7749", "GAMMA-8832", "EPSILON-9921", "THETA-1156", "KAPPA-2267", "SIGMA-4478"]results = {"found_correct": False, "distractors_found": [d for d in distractor_patterns if d in output_upper]}for exp in expected:if exp.upper() in output_upper or exp.upper().replace(" ", "") in output_upper.replace(" ", ""): results["found_correct"] = True; breakif results["distractors_found"] and not results["found_correct"]: results["score"] = 0.0elif results["found_correct"] and not results["distractors_found"]: results["score"] = 1.0elif results["found_correct"]: results["score"] = 0.5else: results["score"] = 0.0return results@weave.op()def multilingual_scorer(output: str, requirements: dict) -> dict:results = {"checks": []}language_patterns = {"Spanish": r'[áéíóúñ¿¡]', "French": r'[àâçéèêëîïôùûü]', "German": r'[äöüß]', "Thai": r'[\u0E00-\u0E7F]'}lang = requirements.get("language", "")if lang in language_patterns: results["checks"].append({"constraint": f"has_{lang}", "passed": bool(re.search(language_patterns[lang], output))})for key in ["must_mention", "has_spanish", "has_french", "has_german"]:if key in requirements:if key == "must_mention":for term in requirements[key]: results["checks"].append({"constraint": f"mentions_{term}", "passed": term.lower() in output.lower()})else:tag = {"has_spanish": "[ES]", "has_french": "[FR]", "has_german": "[DE]"}[key]results["checks"].append({"constraint": key, "passed": tag in output})results["score"] = sum(1 for c in results["checks"] if c["passed"]) / len(results["checks"]) if results["checks"] else 0.5return results@weave.op()def debugging_scorer(output: str, expected_bugs: list, bug_count: int) -> dict:output_lower = output.lower()results = {"bugs_found": 0, "bugs_expected": bug_count}for bug in expected_bugs:line = bug.get("line", 0); issue = bug.get("issue", "").lower()line_mentioned = f"line {line}" in output_lower if line > 0 else Trueissue_words = [w for w in issue.split() if len(w) > 3]keywords_found = sum(1 for w in issue_words if w in output_lower)if (line_mentioned and keywords_found >= 1) or keywords_found >= 2: results["bugs_found"] += 1results["score"] = results["bugs_found"] / bug_count if bug_count > 0 else 0.0return results@weave.op()def data_extraction_scorer(output: str, expected) -> dict:results = {"valid_json": False, "score": 0.0}output_clean = output.strip()if "```" in output_clean:match = re.search(r'```(?:json)?\s*([\s\S]*?)\s*```', output_clean)if match: output_clean = match.group(1)array_match = re.search(r'(\[[\s\S]*\])', output_clean)object_match = re.search(r'(\{[\s\S]*\})', output_clean)if array_match: output_clean = array_match.group(1)elif object_match: output_clean = object_match.group(1)try:parsed = json.loads(output_clean); results["valid_json"] = Trueif isinstance(expected, str):try: expected_parsed = json.loads(expected); results["score"] = 1.0 if parsed == expected_parsed else 0.5except: results["score"] = 0.5else: results["score"] = 0.5except: results["score"] = 0.0return results
Step 7: Evaluation runner
The main evaluation loop that iterates through all categories and questions, calls the model, scores responses, aggregates results, and prints a visual summary with progress bars.
@weave.op()def run_comprehensive_evaluation(skip_long_context: bool = False) -> dict:model = GLM45Model(temperature=0.3)all_results = {}categories = [("math_reasoning", "📊 MATH REASONING", MATH_REASONING_DATASET, lambda i, o: math_scorer(o, i["expected"])),("logic_reasoning", "🧠 LOGIC REASONING", LOGIC_REASONING_DATASET, lambda i, o: logic_scorer(o, i["expected"])),("code_generation", "💻 CODE GENERATION", CODE_GENERATION_DATASET, lambda i, o: code_scorer(o, i.get("test_cases", []))),("instruction_following", "📝 INSTRUCTION FOLLOWING", INSTRUCTION_FOLLOWING_DATASET, lambda i, o: instruction_scorer(o, i["constraints"])),("multilingual", "🌍 MULTILINGUAL", MULTILINGUAL_DATASET, lambda i, o: multilingual_scorer(o, i["requirements"])),("debugging", "🐛 DEBUGGING", DEBUGGING_DATASET, lambda i, o: debugging_scorer(o, i["expected_bugs"], i["bug_count"])),("data_extraction", "📋 DATA EXTRACTION", DATA_EXTRACTION_DATASET, lambda i, o: data_extraction_scorer(o, i.get("expected") or i.get("expected_structure"))),]for cat_id, cat_name, dataset, scorer_fn in categories:print(f"\n{'='*70}\n{cat_name} ({len(dataset)} questions)\n{'='*70}")results = []for item in dataset:print(f" [{item['level']:10}] {item['id']}...", end=" ", flush=True)max_tokens = 3000 if cat_id == "code_generation" else 2500 if cat_id == "multilingual" else 2000output = model.predict(item["question"], max_tokens=max_tokens)scores = scorer_fn(item, output)results.append({"id": item["id"], "level": item["level"], "score": scores["score"]})status = "✅" if scores["score"] >= 0.5 else "❌"extra = f"({scores.get('tests_passed', '')}/{scores.get('total_tests', '')})" if 'tests_passed' in scores else ""extra = extra or (f"({scores.get('bugs_found', '')}/{scores.get('bugs_expected', '')})" if 'bugs_found' in scores else "")print(f"{status} {scores['score']:.0%} {extra}")all_results[cat_id] = {"results": results, "avg_score": sum(r["score"] for r in results) / len(results), "total": len(results)}if not skip_long_context:print(f"\n{'='*70}\n📚 LONG CONTEXT ({len(LONG_CONTEXT_DATASET)} questions)\n{'='*70}")lc_results = []for item in LONG_CONTEXT_DATASET:print(f" [{item['level']:10}] {item['id']} (~{item['word_count']} words)...", end=" ", flush=True)output = model.predict_long_context(item["document"], item["question"])scores = long_context_scorer(output, item["expected"], item["needle_count"])lc_results.append({"id": item["id"], "level": item["level"], "score": scores["score"]})print(f"{'✅' if scores['score'] >= 0.5 else '❌'} {scores['score']:.0%}")all_results["long_context"] = {"results": lc_results, "avg_score": sum(r["score"] for r in lc_results) / len(lc_results), "total": len(lc_results)}else:all_results["long_context"] = {"results": [], "avg_score": 0, "total": 0, "skipped": True}print(f"\n{'='*70}\n📈 EVALUATION SUMMARY - GLM 4.5\n{'='*70}")total_score, total_q = 0, 0for cat, data in all_results.items():if data.get("skipped"): print(f"⏭️ {cat.upper():25} SKIPPED"); continueavg, count = data.get("avg_score", 0), data.get("total", 0)if count == 0: continuetotal_score += avg * count; total_q += countemoji = "✅" if avg >= 0.7 else "⚠️" if avg >= 0.4 else "❌"bar = "█" * int(avg * 20) + "░" * (20 - int(avg * 20))print(f"{emoji} {cat.upper():25} {bar} {avg:6.1%} ({count} q)")print("-" * 70)overall = total_score / total_q if total_q > 0 else 0bar = "█" * int(overall * 20) + "░" * (20 - int(overall * 20))print(f"{'🏆' if overall >= 0.7 else '🎯'} {'OVERALL':25} {bar} {overall:6.1%} ({total_q} total)")print("=" * 70)all_results["summary"] = {"overall_score": overall, "total_questions": total_q}return all_results
Step 8: Save results & run
Save results to JSON for later analysis and execute the evaluation. The output includes a Weave dashboard link for exploring all traced predictions.
def save_results(results: dict, filename: str = "glm45_hard_benchmark_results.json"):with open(filename, "w", encoding="utf-8") as f:json.dump({"model": MODEL_ID, "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "results": results}, f, indent=2, default=str)print(f"\n📁 Results saved to {filename}")def main():print(f"\n{'='*70}")print(f"🚀 GLM 4.5 HARD Benchmark Evaluation")print(f" 355B Total Params | 32B Active | MoE Architecture")print(f" 46 Questions Across 8 Categories")print(f"{'='*70}")print(f"Model: {MODEL_ID}")print(f"Project: {TEAM_PROJECT}")print(f"{'='*70}")results = run_comprehensive_evaluation(skip_long_context=False)save_results(results)print(f"\n🔗 View traces: https://wandb.ai/{TEAM_PROJECT}/weave")print(f"{'='*70}")return resultsif __name__ == "__main__":results = main()
Below is our summary table showing how our model tested for the various range of prompts we have thrown its way.

GLM 4.5 demonstrates strong overall performance with an 84.3% average score across 46 evaluation tasks. The model excels in math reasoning, instruction following, multilingual understanding, and logical reasoning, achieving perfect or near-perfect results in these areas. It also performs well in code generation and data extraction, making it suitable for general-purpose and technical workloads. However, weaker results on debugging and long-context tasks highlight areas for improvement, particularly for use cases that require sustained reasoning over long inputs or detailed error analysis.
Inspecting the "Thinking" process in Weave
For our first use of Weave, we will log every prompt sent to the model along with its corresponding response. This allows us to compare the model’s outputs against other LLMs, as well as evaluate how the same model behaves across different parameter settings or fine-tuning configurations.

Weave also enables logging and inspection of the model’s token usage for each prompt. This is especially useful for understanding model efficiency and cost, since API based LLM pricing is typically tied directly to token consumption.

Finally, we will measure the model’s latency for each prompt. This is particularly important when comparing how long different models take to generate responses to the same question. In real-world applications, such as online or user-facing apps, model latency directly impacts the user experience, making it a critical metric to monitor.

⭐ Best practices
📈 Monitor quality, cost, and latency together
Large MoE models like GLM 4.5 have unique efficiency characteristics. With W&B, log evaluation scores alongside token usage and response time to understand the true cost-quality trade-off. GLM 4.5's 32B active parameters per forward pass offer a compelling balance between capability and inference cost.
🤖 Leverage dual mode reasoning
GLM 4.5 offers both "thinking" and "nonthinking" modes. Use the thinking mode for complex reasoning tasks requiring multi-step analysis, and the nonthinking mode for faster responses on straightforward queries. Monitor which mode performs better for your specific use cases in Weave.
🎯 Use the recommended temperature
For most evaluation and production tasks, a temperature of 0.3 to 0.6 provides a good balance between consistency and quality. For more deterministic outputs (like code generation or structured data extraction), consider lowering to 0.1 to 0.3.
🚦 Know when GLM 4.5 excels
GLM 4.5 is ideal for:
- Agentic AI applications requiring tool use and multi-step reasoning
- Instruction following complex, multi-constraint requirements
- Multilingual tasks across 24+ languages
- Long context tasks up to 128K tokens
- Mathematical reasoning and analytical workflows
Consider other models for tasks requiring deep debugging analysis or specialized domain knowledge, where GLM 4.5 showed weaker performance.
🧪 Evaluate on realistic, task-specific data
Generic benchmarks rarely reflect real-world performance. Build evaluation datasets that mirror actual production queries, including edge cases and agentic workflows. This ensures that GLM 4.5 is measured on what truly matters for your use case.
📊 Monitor everything
Continuously monitor your model using observability tools like Weights & Biases, rather than relying on one off tests. Platforms such as W&B Weave make it easy to track prompts, responses, latency, token usage, errors, and evaluation metrics across every inference call. This visibility helps you quickly identify performance regressions, rising costs, and recurring failure patterns as prompts, data, or traffic evolve.
🚀 What's next?
Now that you’ve seen how to evaluate GLM 4.5 using W&B Inference and Weave, you can take the next steps to deepen your evaluation workflow. Start by testing the model in ways that closely match your specific use case. For example, if code generation is a core requirement, focus your evaluations on coding tasks and debugging scenarios.
Continue evaluating the model after fine-tuning, and repeat the process when integrating enhancements, such as an RAG system, to understand how these changes affect performance. Finally, compare GLM 4.5 against other available models to identify the option that best aligns with your requirements for quality, latency, and cost.