Source: https://ailoot.ai/models/en/codegeex-4/
Canonical: https://ailoot.ai/models/en/codegeex-4/
Language: en

# CodeGeeX-4

[Markdown](https://ailoot.ai/models/en/codegeex-4/index.md) · [JSON](https://ailoot.ai/models/en/codegeex-4/facts.json)

## [CodeGeeX-4](https://ailoot.ai/models/en/codegeex-4/)

CodeGeeX4 is a multilingual coding-model family for code generation, completion, explanation, repair and repository questions. Its native guides cover task-specific prompts, filling gaps between existing code and using related files to prepare changes with explicit file paths.

- [**Ailoot Ultra · OpenAI Chat** `POST /v1/chat/completions` `codegeex-4`](https://ailoot.ai/models/en/codegeex-4/#method-0)
- [**Ailoot Ultra · Anthropic Messages** `POST /v1/messages` `codegeex-4`](https://ailoot.ai/models/en/codegeex-4/#method-1)

About the model

This description covers the model’s capabilities. Available in Ailoot inputs, outputs and options are listed for the selected method below.

CodeGeeX4 is a multilingual coding-model family built around programming assistance and work across related source files. The maker publishes CodeGeeX4-ALL-9B as an open-source member of the series, developed through continued training of GLM-4-9B. Its documentation covers code generation and completion, programming questions, repository analysis and connected workflows involving a code interpreter, web search or function calls. The ordinary output is text: code, explanations, answers or file-labelled changes, according to the task instruction.

Start by choosing the operation and giving the model the code it needs. The native system-prompt guide has separate instructions for adding comments, explaining a program, translating between programming languages, reviewing or repairing code, generating tests and answering questions about a file. For a repair, include the failing code, the observed behaviour and the intended result. For translation, state the target programming language and supply the complete relevant function. For comments, the maker’s task instruction preserves the code and adds comments; for several code-producing tasks, it asks for code only. These distinctions help make the result usable as a code artifact or an explanation, rather than leaving the output format implicit.

The guides provide Chinese and English system prompts. The language of the system instruction does not by itself determine the language of the answer, so request the response language explicitly when an explanation is needed. The specialised review guidance describes Chinese output; the general programming-assistant prompt provides a separate way to ask for a review in another response language. Some task templates set the comment language to match the source and exclude mixed Chinese and English output. In a continuing conversation, repeat the relevant task instruction when switching operations so that a request for an explanation is not confused with the preceding request for code-only output.

For contextual completion, the native format describes the target file, its programming language and the code on both sides of the insertion point. Use the relative file path with ###PATH: and include ###LANGUAGE:; the guide permits an empty language value when it is unknown. ###MODE: selects LINE for a single-line completion or BLOCK for multiple lines, with BLOCK as the documented default. The fill-in-the-middle sequence is suffix first, then prefix, then the missing middle, marked with \<|code\_suffix|\>, \<|code\_prefix|\> and \<|code\_middle|\>. The maker’s infilling template omits the system prompt. Keeping the suffix gives the model the surrounding control flow and the code that must remain after the insertion. The result is the proposed missing code, which can then be checked in its original location.

Cross-file completion adds related snippets as reference material, each introduced by ###REFERENCE: and its own ###PATH:. Keep these references separate from the target file and its insertion point. For example, when completing a function that calls an existing helper, provide the helper’s signature and implementation alongside the target function’s prefix and suffix. The project-level completion guide extends this approach to generating a new file from the project requirements and relevant existing code. Clear paths and selected dependencies make it possible to distinguish code supplied as evidence from the file the model is asked to complete.

Repository questions use a different native layout: list each file under ###PATH:, include its code, then ask the question. A useful brief can ask where a value is defined or how a call passes between the supplied modules. Repository editing uses its own system instruction for adding, deleting or modifying files and requests output in ###PATH: {PATH} followed by the code. Prepare the relevant files and describe the required change, including the file to add or the behaviour to preserve. Read the returned path-labelled blocks as proposed changes; they are not evidence that a repository has already been modified or that the code has run.

For the published CodeGeeX4-ALL-9B member, the maker documents a 128K context and recommends selecting relevant repository content when a project exceeds that window. Retrieval of related snippets and trimming oversized inputs are preparation steps in the repository guide. Context must accommodate the instructions, supplied code and generated continuation, so a targeted set of files is often more useful than an undifferentiated project dump. The maker’s example generation settings control the length of a particular run; they do not define a universal maximum answer length for every CodeGeeX4 edition.

The series also describes connected programming workflows with interpreters, search and function calls. Such a workflow needs the surrounding application to provide the named tools and return their results to the conversation. When asking for runnable code, state the intended language, dependencies and expected behaviour; when asking for an analysis, request the relevant file or function references. Compile or run the proposed changes in the intended environment and check the behaviour against the supplied requirement before incorporating them into a project.

**Ailoot Ultra · OpenAI Chat** `POST /v1/chat/completions` `codegeex-4`

[`codegeex-4`](https://ailoot.ai/models/en/#m=codegeex-4&route=Ultra&caller=codegeex-4&fmt=chat)

Zhipu /`codegeex-4`

### Overview

CodeGeeX4 is a multilingual coding-model family for code generation, completion, explanation, repair and repository questions. Its native guides cover task-specific prompts, filling gaps between existing code and using related files to prepare changes with explicit file paths.

Accepted inputs

Text

Results

Text

### Available in Ailoot · inputs & methods

**Ailoot Ultra · OpenAI Chat** `POST /v1/chat/completions`

Input types

`text`

Output types

`text`

Output format

json or SSE

| Field | Type | Requirement | Values & limits | Default |
| --- | --- | --- | --- | --- |
| Field`model` | Type`string` | RequirementRequired | Values & limits codegeex-4 | Default— |
| Field`messages` | Type`message[]` | RequirementRequired | Values & limits Minimum items: 1 | Default— |
| Field`messages[].role` | Type`string` | RequirementRequired | Values & limits Model-specific | Default— |
| Field`messages[].content` | Type`string` | RequirementOptional | Values & limits Applies when: Text conversation | Default— |
| Field`stream` | Type`boolean` | RequirementOptional | Values & limits | Defaultfalse |

Input material combinations

**Text** · UTF8 text

`messages[].content`

Method parameters and lifecycle

| Parameter | Contract |
| --- | --- |
| Parameter`content_type` | Contractapplication/json |
| Parameter`required` | Contractmodel, messages |
| Parameter`material_types` | Contracttext |
| Parameter`messages` | Contractmessage array with role/content shape |
| Parameter`file_material` | Contractactual UTF-8 document inserted as literal text; no file ID inferred |
| Parameter`optional_controls` | Contractstream |
| Parameter`control_scope` | ContractText conversation; stream is a boolean and defaults to false. |
| Parameter`output_modalities` | Contracttext |
| Parameter`hosted_operations` | Contractfalse |
| Parameter`multimodal_input_binding` | Contractnull |

Method aliases: `/chat/completions`

Lifecycle: `synchronous_or_streamed`

Send exact model ID with messages.

Context length is not an output cap.

A text file may supply literal text; image/audio/file-object inputs need exact binding.

### Pricing

Tariff references do not add request options. Supported parameters are listed for the selected method.

Fast mode

Not specified When fast mode is selected

Flex mode

Not specified When flex mode is selected

Maximum reasoning effort

Not specified When maximum reasoning effort uses the default adjustment

#### Ailoot rates

#### Prices by configuration

| Configuration | Rate schedule | Charge |
| --- | --- | --- |
| ConfigurationBase token rates | Rate scheduleBase rate | Charge Input · Input tokens **$0.028** / 1K tokens Output · Output tokens **$0.028** / 1K tokens Input · Cache read **$0** / 1K tokens Input · Cache write **$0** / 1K tokens Input · Cache write, 1 hour **—** / 1K tokens |

Ailoot reserves an estimated amount before a request. After the result, it settles the final charge from measured usage. Streaming settlement uses the final usage record. [How reservation and settlement work →](https://ailoot.ai/docs/en/billing/reserve/)

### Example requests

#### Ailoot Ultra · OpenAI Chat

curlPython SDK

```bash
set -eu
: "${AILOOT_API_KEY:?Set your Ailoot API key}"
python3 - <<'PY_REQUEST'
import json,os
from pathlib import Path
p=json.loads('{"model":"codegeex-4","messages":[{"role":"user","content":"hello"}],"stream":false}')

Path("request.json").write_text(json.dumps(p,ensure_ascii=False))
PY_REQUEST
curl --fail-with-body --silent --show-error https://api.ailoot.ai/v1/chat/completions \
  -H "Authorization: Bearer $AILOOT_API_KEY" -H 'Content-Type: application/json' \
  --data-binary @request.json -D response-headers.txt -o result.json
python3 - <<'PY_RESULT'
import json
from pathlib import Path
r=json.loads(Path("result.json").read_text())
for x in r.get("choices",[]):
    if x.get("message",{}).get("content"): print(x["message"]["content"])
PY_RESULT
```

```python
from openai import OpenAI
import os

if not os.environ.get("AILOOT_API_KEY", "").strip(): raise SystemExit("Set AILOOT_API_KEY before making a request")
client=OpenAI(base_url="https://api.ailoot.ai/v1",api_key=os.environ["AILOOT_API_KEY"],max_retries=0)
result=client.chat.completions.create(model="codegeex-4", messages=[{"role":"user","content":"hello"}], stream=False)
import base64, json
from pathlib import Path

def save_result(data, stem="result"):
    # Keep every field, including usage, IDs, reasoning and tool requests.
    Path(stem + ".json").write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(data, ensure_ascii=False, indent=2))
    def save_blob(encoded, suffix, label):
        raw = base64.b64decode(encoded, altchars=b"-_", validate=True)
        ext = "png" if raw.startswith(b"\x89PNG\r\n\x1a\n") else "jpg" if raw.startswith(b"\xff\xd8") else "webp" if raw[:4] == b"RIFF" and raw[8:12] == b"WEBP" else suffix
        file = Path(stem + "-" + label + "." + ext)
        file.write_bytes(raw)
        print("Saved", file)
    for index, block in enumerate(data.get("content") or []):
        print("Content", index, json.dumps(block, ensure_ascii=False))
    for choice in data.get("choices") or []:
        print("Choice", choice.get("index"), json.dumps(choice.get("message", choice.get("delta", {})), ensure_ascii=False))
    for index, item in enumerate(data.get("output") or []):
        print("Output", index, json.dumps(item, ensure_ascii=False))
        if item.get("type") == "image_generation_call" and item.get("result"):
            save_blob(item["result"], item.get("output_format") or "bin", "output-" + str(index))
    for ci, candidate in enumerate(data.get("candidates") or []):
        for pi, part in enumerate((candidate.get("content") or {}).get("parts") or []):
            print("Candidate/part", ci, pi, json.dumps(part, ensure_ascii=False))
            blob = part.get("inlineData") or part.get("inline_data")
            if blob and blob.get("data"):
                mime = blob.get("mimeType") or blob.get("mime_type")
                suffix = {"image/png":"png", "image/jpeg":"jpg", "image/webp":"webp", "audio/wav":"wav", "audio/mpeg":"mp3", "video/mp4":"mp4"}.get(mime, "bin")
                save_blob(blob["data"], suffix, "candidate-" + str(ci) + "-part-" + str(pi))

save_result(result.to_dict(mode="json"))
```

### Receive and save results

#### Ailoot Ultra · OpenAI Chat

json or SSE

##### Keep all completed results

Keep every complete returned response, file and content part.

Keep every choice and its content/tool calls/reasoning. In SSE assemble deltas by choice/tool index, retain the final finish reason and usage.

##### If the original response needs checking

Keep request/response IDs and headers. No generic text job retrieval URL is supplied.

Response fields

| Field | Type |
| --- | --- |
| Field`choices[].index` | Typeinteger |
| Field`choices[].message.content` | Typestring\|null |
| Field`choices[].message.tool_calls` | Typetool\_call\[\] |
| Field`choices[].message.reasoning_content` | Typestring |
| Field`choices[].message.reasoning_details` | Typeobject\|array |
| Field`choices[].finish_reason` | Typestring\|null |
| Field`usage` | Typeobject |

Errors and next steps

| Response | Condition | Next step |
| --- | --- | --- |
| Response400 · `invalid_request_error` | ConditionInvalid required fields, material representation or parameter value | Next stepCorrect the indicated fields before a new creation request. |

### Aliases

#### Model aliases

**Ailoot Ultra** [`codegeex-4`](https://ailoot.ai/models/en/#m=codegeex-4&route=Ultra&caller=codegeex-4&fmt=chat)

#### Method path aliases

`/chat/completions`

#### Related caller IDs

[`codegeex-4`](https://ailoot.ai/models/en/#m=codegeex-4&route=Ultra&caller=codegeex-4&fmt=chat)

**Ailoot Ultra · Anthropic Messages** `POST /v1/messages` `codegeex-4`

[`codegeex-4`](https://ailoot.ai/models/en/#m=codegeex-4&route=Ultra&caller=codegeex-4&fmt=messages)

Zhipu /`codegeex-4`

### Overview

CodeGeeX4 is a multilingual coding-model family for code generation, completion, explanation, repair and repository questions. Its native guides cover task-specific prompts, filling gaps between existing code and using related files to prepare changes with explicit file paths.

Accepted inputs

Text

Results

json · sse

### Available in Ailoot · inputs & methods

**Ailoot Ultra · Anthropic Messages** `POST /v1/messages`

Input types

`text`

Output types

`json`, `sse`

Output format

JSON or SSE

| Field | Type | Requirement | Values & limits | Default |
| --- | --- | --- | --- | --- |
| Field`model` | Type`string` | RequirementRequired | Values & limits codegeex-4 | Default— |
| Field`messages` | Type`message[]` | RequirementRequired | Values & limits | Default— |
| Field`messages[].role` | Type`string` | RequirementRequired | Values & limits user, assistant | Default— |
| Field`messages[].content` | Type`string` | RequirementRequired | Values & limits | Default— |
| Field`max_tokens` | Type`integer` | RequirementRequired | Values & limits | Default— |
| Field`stream` | Type`boolean` | RequirementOptional | Values & limits | Defaultfalse |

Input material combinations

**Text** · UTF-8 text

`messages[].content string`

Method parameters and lifecycle

| Parameter | Contract |
| --- | --- |
| Parameter`content_type` | Contractapplication/json |
| Parameter`required` | Contractmodel, messages, max\_tokens |
| Parameter`optional_controls` | Contractstream |
| Parameter`material_types` | Contracttext |
| Parameter`text_file_material` | ContractRead the actual UTF-8 document and put its text in the indicated input or message content string. |

Lifecycle: `synchronous_or_streamed`

### Pricing

Tariff references do not add request options. Supported parameters are listed for the selected method.

Fast mode

Not specified When fast mode is selected

Flex mode

Not specified When flex mode is selected

Maximum reasoning effort

Not specified When maximum reasoning effort uses the default adjustment

#### Ailoot rates

#### Prices by configuration

| Configuration | Rate schedule | Charge |
| --- | --- | --- |
| ConfigurationBase token rates | Rate scheduleBase rate | Charge Input · Input tokens **$0.028** / 1K tokens Output · Output tokens **$0.028** / 1K tokens Input · Cache read **$0** / 1K tokens Input · Cache write **$0** / 1K tokens Input · Cache write, 1 hour **—** / 1K tokens |

Ailoot reserves an estimated amount before a request. After the result, it settles the final charge from measured usage. Streaming settlement uses the final usage record. [How reservation and settlement work →](https://ailoot.ai/docs/en/billing/reserve/)

### Example requests

#### Ailoot Ultra · Anthropic Messages

Complete minimal JSON bodycurl · use your UTF-8 documentPython · save the complete result

```json
{
  "model": "codegeex-4",
  "max_tokens": 128,
  "messages": [
    {
      "role": "user",
      "content": "Summarize the incident report."
    }
  ],
  "stream": false
}
```

```bash
set -eu
: "${AILOOT_API_KEY:?Set your Ailoot API key}"
: "${AILOOT_TEXT_FILE:?Set your actual UTF-8 document}"
export AILOOT_TEXT_FILE
python3 - <<'PY_REQUEST'
import json, os
from pathlib import Path

source_file = Path(os.environ['AILOOT_TEXT_FILE'])
if not source_file.is_file():
    raise SystemExit('Set AILOOT_TEXT_FILE to your actual UTF-8 document')
text = source_file.read_text(encoding='utf-8')
if not text.strip():
    raise SystemExit('Choose a document containing text')
payload = {'model': 'codegeex-4', 'max_tokens': 128, 'messages': [{'role': 'user', 'content': 'Summarize the incident report.'}]}
payload['messages'][0]['content'] = 'Summarize this material and quote supporting source passages.\n\n' + text
Path('request.json').write_text(json.dumps(payload, ensure_ascii=False), encoding='utf-8')
PY_REQUEST
curl --fail-with-body --silent --show-error https://api.ailoot.ai/v1/messages \
  -H "x-api-key: $AILOOT_API_KEY" -H 'anthropic-version: 2023-06-01' -H 'Content-Type: application/json' \
  --data-binary @request.json -D response-headers.txt -o result.json
python3 - <<'PY_RESULT'
import json
from pathlib import Path

result = json.loads(Path('result.json').read_text(encoding='utf-8'))
print(json.dumps(result, ensure_ascii=False, indent=2))
PY_RESULT
```

```python
import json, os
from pathlib import Path

source_file = Path(os.environ['AILOOT_TEXT_FILE'])
if not source_file.is_file():
    raise SystemExit('Set AILOOT_TEXT_FILE to your actual UTF-8 document')
text = source_file.read_text(encoding='utf-8')
if not text.strip():
    raise SystemExit('Choose a document containing text')
payload = {'model': 'codegeex-4', 'max_tokens': 128, 'messages': [{'role': 'user', 'content': 'Summarize the incident report.'}]}
payload['messages'][0]['content'] = 'Summarize this material and quote supporting source passages.\n\n' + text
from urllib.request import Request, urlopen
from urllib.error import HTTPError

api_key = os.environ['AILOOT_API_KEY']
if not api_key.strip():
    raise SystemExit('Set AILOOT_API_KEY before making a request')
headers = {'x-api-key': 'PLACEHOLDER_KEY', 'anthropic-version': '2023-06-01', 'Content-Type': 'application/json'}
headers['x-api-key'] = api_key
request = Request('https://api.ailoot.ai/v1/messages', data=json.dumps(payload, ensure_ascii=False).encode('utf-8'), headers=headers, method='POST')
try:
    with urlopen(request, timeout=120) as response:
        raw = response.read()
        Path('response-headers.txt').write_text(str(response.headers), encoding='utf-8')
except HTTPError as error:
    Path('result.json').write_bytes(error.read())
    Path('response-headers.txt').write_text(str(error.headers), encoding='utf-8')
    raise
Path('result.json').write_bytes(raw)
import json
from pathlib import Path

result = json.loads(Path('result.json').read_text(encoding='utf-8'))
print(json.dumps(result, ensure_ascii=False, indent=2))
```

### Receive and save results

#### Ailoot Ultra · Anthropic Messages

JSON or SSE

##### Keep all completed results

Keep every complete returned response, file and content part.

Keep all content blocks, thinking signatures and actual tool-use IDs. Assemble all SSE block deltas; a first text block is not the complete output.

##### If the original response needs checking

Keep request/response IDs and headers. No generic text job retrieval URL is supplied.

Response fields

| Field | Type |
| --- | --- |
| Field`id` | Typestring |
| Field`model` | Typestring |
| Field`content[]` | Typetext\|thinking\|tool\_use\|other content block |
| Field`stop_reason` | Typestring\|null |
| Field`usage` | Typeobject |

Errors and next steps

| Response | Condition | Next step |
| --- | --- | --- |
| Response400 · `invalid_request_error` | ConditionInvalid required fields, material representation or parameter value | Next stepCorrect the indicated fields before a new creation request. |

### Aliases

#### Model aliases

**Ailoot Ultra** [`codegeex-4`](https://ailoot.ai/models/en/#m=codegeex-4&route=Ultra&caller=codegeex-4&fmt=messages)

#### Method path aliases

`/chat/completions`

#### Related caller IDs

[`codegeex-4`](https://ailoot.ai/models/en/#m=codegeex-4&route=Ultra&caller=codegeex-4&fmt=messages)

FAQ · CodeGeeX-4

What inputs and results are available?

`POST /v1/chat/completions` · `codegeex-4`: `text` → `text` `POST /v1/messages` · `codegeex-4`: `text` → `json`, `sse`

Which fields does the request use?

`POST /v1/chat/completions` · `codegeex-4`: `model`, `messages`, `stream` `POST /v1/messages` · `codegeex-4`: `model`, `messages`, `max_tokens`, `stream`

What limits apply?

`POST /v1/chat/completions` · `codegeex-4`: `messages.min_items`: `1`

Connect Ailoot to Claude Code, OpenCode, Hermes or your own app.

## The company and its project portfolio

The company and its project portfolio: millions of customers; monthly sales in the billions.

## Buy tokens at a discount.

Subscription discounts for regular use. Promo codes offer up to 50% off token purchases.

Subscription

Choose a discounted plan for your regular requests.

Promo code: up to 50% off

Enter your code at checkout. The price updates to reflect the current promotion.

Spending in your history

The model, tokens and amount are recorded for each request.

[Choose a subscription](https://ailoot.ai/docs/en/billing/subscriptions/) · [View model prices](https://ailoot.ai/models/en/)

## Connect the API to a product you sell.

Use Ailoot in SaaS, apps and bots under its official service offer and licence agreement. Request a reseller licence for resale.

Commercial application

Add text, image, video and audio generation to paid features in your service.

Reseller licence

Send a description of your project and how you provide access. Request written terms for use and resale.

Documents on the website

The service offer, licence agreement and data processing policy are available before you connect.

[Request a reseller licence](mailto:support@ailoot.ai) · [Service offer and licence agreement](https://ailoot.ai/legal/offer?lang=en)

## Ailoot · The company and its project portfolio





Ailoot combines established operating experience, a large client base, stable service and ongoing KPI control.





The company and its project portfolio: millions of customers; monthly sales in the billions.





Ailoot brings that operating experience to API access for AI features in customer products, agents, applications and automations.
