Build an Agentic Coding Loop with GLM

Run an AI SDK tool-calling loop on a GLM model through AnyRouter, with streaming and reasoning effort.

The Vercel AI SDK runs the tool-calling loop; AnyRouter is the model provider. This example uses z-ai/glm-4.7-flash; any tool-capable model works by changing the id.

  1. Install:

    npm install @anyr/ai-sdk-provider ai zod
  2. Define tools and run the loop. stopWhen: stepCountIs(n) bounds the steps, and steps records each tool call and result:

    import { createAnyRouter } from "@anyr/ai-sdk-provider"
    import { generateText, tool, stepCountIs } from "ai"
    import { z } from "zod"
    import { readFile } from "node:fs/promises"
    
    const anyrouter = createAnyRouter() // reads ANYROUTER_API_KEY
    
    const { text, steps } = await generateText({
      model: anyrouter("z-ai/glm-4.7-flash"),
      system: "You are a coding agent. Use the tools to inspect the repo, then answer.",
      prompt: "What does src/index.ts export, and is it covered by a test?",
      stopWhen: stepCountIs(8),
      tools: {
        read_file: tool({
          description: "Read a UTF-8 text file from the repo.",
          parameters: z.object({ path: z.string() }),
          execute: async ({ path }) => ({ contents: await readFile(path, "utf8") }),
        }),
      },
    })
    
    console.log(text, `(${steps.length} steps)`)
  3. To stream progress, use streamText and read result.fullStream (text-delta, tool-call, and tool results arrive as they happen).

  4. To tune reasoning, pass reasoning_effort through extraBody:

    providerOptions: { anyrouter: { extraBody: { reasoning_effort: "high" } } },

With a Z-AI account or Coding Plan, add the key in Settings → BYOK. z-ai/* requests then use your key at list price, with the same code.

AnyRouter routes requests to third-party models. Models and outputs are provided as is, with no warranty; you use them at your own risk. Disclaimer