main ccbec4c7b53c cached
195 files
404.2 KB
108.4k tokens
701 symbols
1 requests
Download .txt
Showing preview only (465K chars total). Download the full file or copy to clipboard to get everything.
Repository: MetaGLM/zhipuai-sdk-python-v4
Branch: main
Commit: ccbec4c7b53c
Files: 195
Total size: 404.2 KB

Directory structure:
gitextract_z9p34zne/

├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug-report.yml
│   │   └── feature-request.yml
│   ├── PULL_REQUEST_TEMPLATE.md
│   ├── actions/
│   │   └── poetry_setup/
│   │       └── action.yml
│   └── workflows/
│       ├── _integration_test.yml
│       ├── _release.yml
│       ├── _test.yml
│       ├── _test_release.yml
│       └── lint-pr.yaml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── README_CN.md
├── Release-Note.md
├── poetry.toml
├── pyproject.toml
├── tests/
│   ├── conftest.py
│   ├── integration_tests/
│   │   ├── batchinput.jsonl
│   │   ├── demo.jsonl
│   │   ├── file.xlsx
│   │   ├── test.py
│   │   ├── test_agents.py
│   │   ├── test_assistant.py
│   │   ├── test_audio.py
│   │   ├── test_batches.py
│   │   ├── test_charglm3.py
│   │   ├── test_chat.py
│   │   ├── test_code_geex.py
│   │   ├── test_embedding.py
│   │   ├── test_emohaa.py
│   │   ├── test_file.py
│   │   ├── test_file_parser.py
│   │   ├── test_finetuning.py
│   │   ├── test_images.py
│   │   ├── test_knowledge.py
│   │   ├── test_moderation.py
│   │   ├── test_tools.py
│   │   ├── test_transcriptions.py
│   │   ├── test_videos.py
│   │   ├── test_vlm_thinking.py
│   │   └── test_web_search.py
│   └── unit_tests/
│       ├── batchinput.jsonl
│       ├── maybe/
│       │   └── test_maybe_transform.py
│       ├── response_model/
│       │   ├── __init__.py
│       │   └── test_response.py
│       ├── sse_client/
│       │   ├── __init__.py
│       │   └── test_stream.py
│       ├── test_agents.py
│       ├── test_audio.py
│       ├── test_jwt.py
│       ├── test_request_opt.py
│       ├── test_response.py
│       ├── test_sdk_import.py
│       └── test_streaming.py
└── zhipuai/
    ├── __init__.py
    ├── __version__.py
    ├── _client.py
    ├── api_resource/
    │   ├── __init__.py
    │   ├── agents/
    │   │   ├── __init__.py
    │   │   └── agents.py
    │   ├── assistant/
    │   │   ├── __init__.py
    │   │   └── assistant.py
    │   ├── audio/
    │   │   ├── __init__.py
    │   │   ├── audio.py
    │   │   └── transcriptions.py
    │   ├── batches.py
    │   ├── chat/
    │   │   ├── __init__.py
    │   │   ├── async_completions.py
    │   │   ├── chat.py
    │   │   └── completions.py
    │   ├── embeddings.py
    │   ├── file_parser/
    │   │   ├── __init__.py
    │   │   └── file_parser.py
    │   ├── files.py
    │   ├── fine_tuning/
    │   │   ├── __init__.py
    │   │   ├── fine_tuning.py
    │   │   ├── jobs/
    │   │   │   ├── __init__.py
    │   │   │   └── jobs.py
    │   │   └── models/
    │   │       ├── __init__.py
    │   │       └── fine_tuned_models.py
    │   ├── images.py
    │   ├── knowledge/
    │   │   ├── __init__.py
    │   │   ├── document/
    │   │   │   ├── __init__.py
    │   │   │   └── document.py
    │   │   └── knowledge.py
    │   ├── moderation/
    │   │   ├── __init__.py
    │   │   └── moderations.py
    │   ├── tools/
    │   │   ├── __init__.py
    │   │   └── tools.py
    │   ├── videos/
    │   │   ├── __init__.py
    │   │   └── videos.py
    │   └── web_search/
    │       ├── __init__.py
    │       └── web_search.py
    ├── core/
    │   ├── __init__.py
    │   ├── _base_api.py
    │   ├── _base_compat.py
    │   ├── _base_models.py
    │   ├── _base_type.py
    │   ├── _constants.py
    │   ├── _errors.py
    │   ├── _files.py
    │   ├── _http_client.py
    │   ├── _jwt_token.py
    │   ├── _legacy_binary_response.py
    │   ├── _legacy_response.py
    │   ├── _request_opt.py
    │   ├── _response.py
    │   ├── _sse_client.py
    │   ├── _utils/
    │   │   ├── __init__.py
    │   │   ├── _transform.py
    │   │   ├── _typing.py
    │   │   └── _utils.py
    │   ├── logs.py
    │   └── pagination.py
    └── types/
        ├── __init__.py
        ├── agents/
        │   ├── __init__.py
        │   ├── agents_completion.py
        │   ├── agents_completion_chunk.py
        │   └── chat_completions_create_param.py
        ├── assistant/
        │   ├── __init__.py
        │   ├── assistant_completion.py
        │   ├── assistant_conversation_params.py
        │   ├── assistant_conversation_resp.py
        │   ├── assistant_create_params.py
        │   ├── assistant_support_resp.py
        │   └── message/
        │       ├── __init__.py
        │       ├── message_content.py
        │       ├── text_content_block.py
        │       ├── tools/
        │       │   ├── code_interpreter_delta_block.py
        │       │   ├── drawing_tool_delta_block.py
        │       │   ├── function_delta_block.py
        │       │   ├── retrieval_delta_black.py
        │       │   ├── tools_type.py
        │       │   └── web_browser_delta_block.py
        │       └── tools_delta_block.py
        ├── audio/
        │   ├── __init__.py
        │   ├── audio_customization_param.py
        │   ├── audio_speech_chunk.py
        │   ├── audio_speech_params.py
        │   └── transcriptions_create_param.py
        ├── batch.py
        ├── batch_create_params.py
        ├── batch_error.py
        ├── batch_list_params.py
        ├── batch_request_counts.py
        ├── chat/
        │   ├── __init__.py
        │   ├── async_chat_completion.py
        │   ├── chat_completion.py
        │   ├── chat_completion_chunk.py
        │   ├── chat_completions_create_param.py
        │   └── code_geex/
        │       └── code_geex_params.py
        ├── embeddings.py
        ├── file_parser/
        │   ├── __init__.py
        │   ├── file_parser_create_params.py
        │   └── file_parser_resp.py
        ├── files/
        │   ├── __init__.py
        │   ├── file_create_params.py
        │   ├── file_deleted.py
        │   ├── file_object.py
        │   └── upload_detail.py
        ├── fine_tuning/
        │   ├── __init__.py
        │   ├── fine_tuning_job.py
        │   ├── fine_tuning_job_event.py
        │   ├── job_create_params.py
        │   └── models/
        │       ├── __init__.py
        │       └── fine_tuned_models.py
        ├── image.py
        ├── knowledge/
        │   ├── __init__.py
        │   ├── document/
        │   │   ├── __init__.py
        │   │   ├── document.py
        │   │   ├── document_edit_params.py
        │   │   ├── document_list_params.py
        │   │   └── document_list_resp.py
        │   ├── knowledge.py
        │   ├── knowledge_create_params.py
        │   ├── knowledge_list_params.py
        │   ├── knowledge_list_resp.py
        │   └── knowledge_used.py
        ├── moderation/
        │   ├── __init__.py
        │   └── moderation_completion.py
        ├── sensitive_word_check/
        │   ├── __init__.py
        │   └── sensitive_word_check.py
        ├── tools/
        │   ├── __init__.py
        │   ├── tools_web_search_params.py
        │   ├── web_search.py
        │   └── web_search_chunk.py
        ├── video/
        │   ├── __init__.py
        │   ├── video_create_params.py
        │   └── video_object.py
        └── web_search/
            ├── __init__.py
            ├── web_search_create_params.py
            └── web_search_resp.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/ISSUE_TEMPLATE/bug-report.yml
================================================
name: 🐞 Bug Report
description: File a bug report
title: "[Bug]: "
type: "Bug"
body:
  - type: markdown
    attributes:
      value: |
        Thanks for stopping by to let us know something could be better!
  - type: textarea
    id: what-happened
    attributes:
      label: What happened?
      description: Also tell us what you expected to happen and how to reproduce the issue.
      placeholder: Tell us what you see!
      value: "A bug happened!"
    validations:
      required: true
  - type: textarea
    id: logs
    attributes:
      label: Relevant log output
      description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
      render: shell
  - type: checkboxes
    id: terms
    attributes:
      label: Code of Conduct
      description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/MetaGLM/zhipuai-sdk-python-v4/blob/main/CODE_OF_CONDUCT.md)
      options:
        - label: I agree to follow this project's Code of Conduct
          required: true


================================================
FILE: .github/ISSUE_TEMPLATE/feature-request.yml
================================================
name: 💡 Feature Request
description: Suggest an idea for this repository
title: "[Feat]: "
type: "Feature"
body:
  - type: markdown
    attributes:
      value: |
        Thanks for stopping by to let us know something could be better!
  - type: textarea
    id: problem
    attributes:
      label: Is your feature request related to a problem? Please describe.
      description: A clear and concise description of what the problem is.
      placeholder: Ex. I'm always frustrated when [...]
  - type: textarea
    id: describe
    attributes:
      label: Describe the solution you'd like
      description: A clear and concise description of what you want to happen.
    validations:
      required: true
  - type: textarea
    id: alternatives
    attributes:
      label: Describe alternatives you've considered
      description: A clear and concise description of any alternative solutions or features you've considered.
  - type: textarea
    id: context
    attributes:
      label: Additional context
      description: Add any other context or screenshots about the feature request here.
  - type: checkboxes
    id: terms
    attributes:
      label: Code of Conduct
      description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/MetaGLM/zhipuai-sdk-python-v4/blob/main/CODE_OF_CONDUCT.md)
      options:
        - label: I agree to follow this project's Code of Conduct
          required: true


================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
# Description

Thank you for opening a Pull Request!
Before submitting your PR, there are a few things you can do to make sure it goes smoothly:

- [ ] Follow the [`CONTRIBUTING` Guide](https://github.com/MetaGLM/zhipuai-sdk-python-v4/blob/main/CONTRIBUTING.md).
- [ ] Make your Pull Request title in the <https://www.conventionalcommits.org/> specification.
- [ ] Ensure the tests pass (Run `mvn clean test` from the repository root)
- [ ] Appropriate docs were updated (if necessary)

Fixes #<issue_number_goes_here> 


================================================
FILE: .github/actions/poetry_setup/action.yml
================================================
# An action for setting up poetry install with caching.
# Using a custom action since the default action does not
# take poetry install groups into account.
# Action code from:
# https://github.com/actions/setup-python/issues/505#issuecomment-1273013236
name: poetry-install-with-caching
description: Poetry install with support for caching of dependency groups.

inputs:
  python-version:
    description: Python version, supporting MAJOR.MINOR only
    required: true

  poetry-version:
    description: Poetry version
    required: true

  cache-key:
    description: Cache key to use for manual handling of caching
    required: true

  working-directory:
    description: Directory whose poetry.lock file should be cached
    required: true

runs:
  using: composite
  steps:
    - uses: actions/setup-python@v5
      name: Setup python ${{ inputs.python-version }}
      id: setup-python
      with:
        python-version: ${{ inputs.python-version }}

#    - uses: actions/cache@v4
#      id: cache-bin-poetry
#      name: Cache Poetry binary - Python ${{ inputs.python-version }}
#      env:
#        SEGMENT_DOWNLOAD_TIMEOUT_MIN: "1"
#      with:
#        path: |
#          /opt/pipx/venvs/poetry
#        # This step caches the poetry installation, so make sure it's keyed on the poetry version as well.
#        key: bin-poetry-${{ runner.os }}-${{ runner.arch }}-py-${{ inputs.python-version }}-${{ inputs.poetry-version }}

    - name: Refresh shell hashtable and fixup softlinks
      if: steps.cache-bin-poetry.outputs.cache-hit == 'true'
      shell: bash
      env:
        POETRY_VERSION: ${{ inputs.poetry-version }}
        PYTHON_VERSION: ${{ inputs.python-version }}
      run: |
        set -eux

        # Refresh the shell hashtable, to ensure correct `which` output.
        hash -r

        # `actions/cache@v3` doesn't always seem able to correctly unpack softlinks.
        # Delete and recreate the softlinks pipx expects to have.
        rm /opt/pipx/venvs/poetry/bin/python
        cd /opt/pipx/venvs/poetry/bin
        ln -s "$(which "python$PYTHON_VERSION")" python
        chmod +x python
        cd /opt/pipx_bin/
        ln -s /opt/pipx/venvs/poetry/bin/poetry poetry
        chmod +x poetry

        # Ensure everything got set up correctly.
        /opt/pipx/venvs/poetry/bin/python --version
        /opt/pipx_bin/poetry --version

    - name: Install poetry via pip
      if: steps.cache-bin-poetry.outputs.cache-hit != 'true'
      shell: bash
      env:
        POETRY_VERSION: ${{ inputs.poetry-version }}
      run: |
        python -m pip install --upgrade pip
        python -m pip install "poetry==$POETRY_VERSION"
        poetry --version

    - name: Restore pip and poetry cached dependencies
      uses: actions/cache@v4
      env:
        SEGMENT_DOWNLOAD_TIMEOUT_MIN: "4"
        WORKDIR: ${{ inputs.working-directory == '' && '.' || inputs.working-directory }}
      with:
        path: |
          ~/.cache/pip
          ~/.cache/pypoetry/virtualenvs
          ~/.cache/pypoetry/cache
          ~/.cache/pypoetry/artifacts
          ${{ env.WORKDIR }}/.venv
        key: py-deps-${{ runner.os }}-${{ runner.arch }}-py-${{ inputs.python-version }}-poetry-${{ inputs.poetry-version }}-${{ inputs.cache-key }}-${{ hashFiles(format('{0}/**/poetry.lock', env.WORKDIR)) }}


================================================
FILE: .github/workflows/_integration_test.yml
================================================
name: integration_test

on:
  workflow_dispatch:
    inputs:
      working-directory:
        required: true
        type: string
        default: '.'
        description: "From which folder this pipeline executes"

env:
  POETRY_VERSION: "1.8.2"

jobs:
  build:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest

    environment: Scheduled testing publish
    outputs:
      pkg-name: ${{ steps.check-version.outputs.pkg-name }}
      version: ${{ steps.check-version.outputs.version }}
    strategy:
      matrix:
        python-version:
          - "3.8"
          - "3.9"
          - "3.10"
          - "3.11"
          - "3.12"
    name: "make integration_test #${{ matrix.python-version }}"
    steps:
        - uses: actions/checkout@v4

        - name: Set up Python ${{ matrix.python-version }} + Poetry ${{ env.POETRY_VERSION }}
          uses: "./.github/actions/poetry_setup"
          with:
            python-version: ${{ matrix.python-version }}
            poetry-version: ${{ env.POETRY_VERSION }}
            working-directory: ${{ inputs.working-directory }}
            cache-key: core

        - name: Import test dependencies
          run: poetry install --with test
          working-directory: ${{ inputs.working-directory }}

        - name: Run integration tests
          shell: bash
          env:
            ZHIPUAI_API_KEY: ${{ secrets.ZHIPUAI_API_KEY }}
            ZHIPUAI_BASE_URL: ${{ secrets.ZHIPUAI_BASE_URL }}
          run: |
            make integration_tests

        - name: Ensure the tests did not create any additional files
          shell: bash
          run: |
            set -eu
            
            STATUS="$(git status)"
            echo "$STATUS"
            
            # grep will exit non-zero if the target message isn't found,
            # and `set -e` above will cause the step to fail.
            echo "$STATUS" | grep 'nothing to commit, working tree clean'


================================================
FILE: .github/workflows/_release.yml
================================================
name: release
run-name: Release ${{ inputs.working-directory }} by @${{ github.actor }}
on:
  workflow_call:
    inputs:
      working-directory:
        required: true
        type: string
        description: "From which folder this pipeline executes"
  workflow_dispatch:
    inputs:
      working-directory:
        required: true
        type: string
        default: '.'
        description: "From which folder this pipeline executes"
env:
  PYTHON_VERSION: "3.9"
  POETRY_VERSION: "1.8.2"

jobs:
  build:
    if: github.ref == 'refs/heads/main'
    environment: Scheduled testing publish
    runs-on: ubuntu-latest

    outputs:
      pkg-name: ${{ steps.check-version.outputs.pkg-name }}
      version: ${{ steps.check-version.outputs.version }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python + Poetry ${{ env.POETRY_VERSION }}
        uses: "./.github/actions/poetry_setup"
        with:
          python-version: ${{ env.PYTHON_VERSION }}
          poetry-version: ${{ env.POETRY_VERSION }}
          working-directory: ${{ inputs.working-directory }}
          cache-key: release

      # We want to keep this build stage *separate* from the release stage,
      # so that there's no sharing of permissions between them.
      # The release stage has trusted publishing and GitHub repo contents write access,
      # and we want to keep the scope of that access limited just to the release job.
      # Otherwise, a malicious `build` step (e.g. via a compromised dependency)
      # could get access to our GitHub or PyPI credentials.
      #
      # Per the trusted publishing GitHub Action:
      # > It is strongly advised to separate jobs for building [...]
      # > from the publish job.
      # https://github.com/pypa/gh-action-pypi-publish#non-goals
      - name: Build project for distribution
        run: poetry build
        working-directory: ${{ inputs.working-directory }}

      - name: Upload build
        uses: actions/upload-artifact@v4
        with:
          name: dist
          path: ${{ inputs.working-directory }}/dist/

      - name: Check Version
        id: check-version
        shell: bash
        working-directory: ${{ inputs.working-directory }}
        run: |
          echo pkg-name="$(poetry version | cut -d ' ' -f 1)" >> $GITHUB_OUTPUT
          echo version="$(poetry version --short)" >> $GITHUB_OUTPUT

  test-pypi-publish:
    needs:
      - build
    uses:
      ./.github/workflows/_test_release.yml
    with:
      working-directory: ${{ inputs.working-directory }}
    secrets: inherit

  pre-release-checks:
    needs:
      - build
      - test-pypi-publish
    environment: Scheduled testing publish
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      # We explicitly *don't* set up caching here. This ensures our tests are
      # maximally sensitive to catching breakage.
      #
      # For example, here's a way that caching can cause a falsely-passing test:
      # - Make the langchain package manifest no longer list a dependency package
      #   as a requirement. This means it won't be installed by `pip install`,
      #   and attempting to use it would cause a crash.
      # - That dependency used to be required, so it may have been cached.
      #   When restoring the venv packages from cache, that dependency gets included.
      # - Tests pass, because the dependency is present even though it wasn't specified.
      # - The package is published, and it breaks on the missing dependency when
      #   used in the real world.

      - name: Set up Python + Poetry ${{ env.POETRY_VERSION }}
        uses: "./.github/actions/poetry_setup"
        with:
          python-version: ${{ env.PYTHON_VERSION }}
          poetry-version: ${{ env.POETRY_VERSION }}
          working-directory: ${{ inputs.working-directory }}

      - name: Import published package
        shell: bash
        working-directory: ${{ inputs.working-directory }}
        env:
          PKG_NAME: ${{ needs.build.outputs.pkg-name }}
          VERSION: ${{ needs.build.outputs.version }}
        # Here we use:
        # - The default regular PyPI index as the *primary* index, meaning
        #   that it takes priority (https://pypi.org/simple)
        # - The test PyPI index as an extra index, so that any dependencies that
        #   are not found on test PyPI can be resolved and installed anyway.
        #   (https://test.pypi.org/simple). This will include the PKG_NAME==VERSION
        #   package because VERSION will not have been uploaded to regular PyPI yet.
        # - attempt install again after 5 seconds if it fails because there is
        #   sometimes a delay in availability on test pypi
        run: |
          poetry run pip install \
            --extra-index-url https://test.pypi.org/simple/ \
            "$PKG_NAME==$VERSION" || \
          ( \
            sleep 5 && \
            poetry run pip install \
              --extra-index-url https://test.pypi.org/simple/ \
              "$PKG_NAME==$VERSION" \
          )

          # Replace all dashes in the package name with underscores,
          # since that's how Python imports packages with dashes in the name.
          IMPORT_NAME="$(echo "$PKG_NAME" | sed s/-/_/g)"

          poetry run python -c "import $IMPORT_NAME; print(dir($IMPORT_NAME))"

      - name: Import test dependencies
        run: poetry install --with test
        working-directory: ${{ inputs.working-directory }}

      # Overwrite the local version of the package with the test PyPI version.
      - name: Import published package (again)
        working-directory: ${{ inputs.working-directory }}
        shell: bash
        env:
          PKG_NAME: ${{ needs.build.outputs.pkg-name }}
          VERSION: ${{ needs.build.outputs.version }}
        run: |
          poetry run pip install \
            --extra-index-url https://test.pypi.org/simple/ \
            "$PKG_NAME==$VERSION"

      # - name: Run unit tests
      #   run: make tests
      #   env:
      #     ZHIPUAI_API_KEY: ${{ secrets.ZHIPUAI_API_KEY }}
      #     ZHIPUAI_BASE_URL: ${{ secrets.ZHIPUAI_BASE_URL }}
      #   working-directory: ${{ inputs.working-directory }}

      # - name: Run integration tests
      #   env:
      #     ZHIPUAI_API_KEY: ${{ secrets.ZHIPUAI_API_KEY }}
      #     ZHIPUAI_BASE_URL: ${{ secrets.ZHIPUAI_BASE_URL }}
      #   run: make integration_tests
      #   working-directory: ${{ inputs.working-directory }}

  publish:
    needs:
      - build
      - test-pypi-publish
      - pre-release-checks
    environment: Scheduled testing publish
    runs-on: ubuntu-latest 

    defaults:
      run:
        working-directory: ${{ inputs.working-directory }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python + Poetry ${{ env.POETRY_VERSION }}
        uses: "./.github/actions/poetry_setup"
        with:
          python-version: ${{ env.PYTHON_VERSION }}
          poetry-version: ${{ env.POETRY_VERSION }}
          working-directory: ${{ inputs.working-directory }}
          cache-key: release

      - uses: actions/download-artifact@v4
        with:
          name: dist
          path: ${{ inputs.working-directory }}/dist/

      - name: Publish package distributions to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
       
        with:
          packages-dir: ${{ inputs.working-directory }}/dist/
          verbose: true
          print-hash: true
          user: __token__ 
          password: ${{ secrets.PYPI_API_TOKEN }}
          # We overwrite any existing distributions with the same name and version.
          # This is *only for CI use* and is *extremely dangerous* otherwise!
          # https://github.com/pypa/gh-action-pypi-publish#tolerating-release-package-file-duplicates
          skip-existing: true

  mark-release:
    needs:
      - build
      - test-pypi-publish
      - pre-release-checks
      - publish
    environment: Scheduled testing publish
    runs-on: ubuntu-latest
    permissions:
      # This permission is needed by `ncipollo/release-action` to
      # create the GitHub release.
      contents: write
      id-token: none

    defaults:
      run:
        working-directory: ${{ inputs.working-directory }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python + Poetry ${{ env.POETRY_VERSION }}
        uses: "./.github/actions/poetry_setup"
        with:
          python-version: ${{ env.PYTHON_VERSION }}
          poetry-version: ${{ env.POETRY_VERSION }}
          working-directory: ${{ inputs.working-directory }}
          cache-key: release

      - uses: actions/download-artifact@v4
        with:
          name: dist
          path: ${{ inputs.working-directory }}/dist/

      - name: Create Release
        uses: ncipollo/release-action@v1
        if: ${{ inputs.working-directory == '.' }}
        with:
          artifacts: "dist/*"
          token: ${{ secrets.GITHUB_TOKEN }}
          draft: false
          generateReleaseNotes: true
          tag: v${{ needs.build.outputs.version }}
          commit: main


================================================
FILE: .github/workflows/_test.yml
================================================
name: test

on:
  workflow_dispatch:
    inputs:
      working-directory:
        required: true
        type: string
        default: '.'
        description: "From which folder this pipeline executes"
  pull_request:
    branches:
      - main
  push:
    branches:
      - 'action*'

env:
  POETRY_VERSION: "1.8.2"

jobs:
  build:
    defaults:
      run:
        working-directory: ${{ inputs.working-directory || '.' }}
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version:
          - "3.8"
          - "3.9"
          - "3.10"
          - "3.11"
          - "3.12"
    name: "make test #${{ matrix.python-version }}"
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python ${{ matrix.python-version }} + Poetry ${{ env.POETRY_VERSION }}
        uses: "./.github/actions/poetry_setup"
        with:
          python-version: ${{ matrix.python-version }}
          poetry-version: ${{ env.POETRY_VERSION }}
          working-directory: ${{ inputs.working-directory || '.' }}
          cache-key: core


      - name: Import test dependencies
        run: poetry install --with test
        working-directory: ${{ inputs.working-directory || '.' }}

      - name: Run core tests
        shell: bash
        run: |
          make test

      - name: Ensure the tests did not create any additional files
        shell: bash
        run: |
          set -eu

          STATUS="$(git status)"
          echo "$STATUS"

          # grep will exit non-zero if the target message isn't found,
          # and `set -e` above will cause the step to fail.
          echo "$STATUS" | grep 'nothing to commit, working tree clean'


================================================
FILE: .github/workflows/_test_release.yml
================================================
name: test-release

on:
  workflow_call:
    inputs:
      working-directory:
        required: true
        type: string
        description: "From which folder this pipeline executes"

env:
  POETRY_VERSION: "1.8.2"
  PYTHON_VERSION: "3.9"

jobs:
  build:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest

    outputs:
      pkg-name: ${{ steps.check-version.outputs.pkg-name }}
      version: ${{ steps.check-version.outputs.version }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python + Poetry ${{ env.POETRY_VERSION }}
        uses: "./.github/actions/poetry_setup"
        with:
          python-version: ${{ env.PYTHON_VERSION }}
          poetry-version: ${{ env.POETRY_VERSION }}
          working-directory: ${{ inputs.working-directory }}
          cache-key: release

      # We want to keep this build stage *separate* from the release stage,
      # so that there's no sharing of permissions between them.
      # The release stage has trusted publishing and GitHub repo contents write access,
      # and we want to keep the scope of that access limited just to the release job.
      # Otherwise, a malicious `build` step (e.g. via a compromised dependency)
      # could get access to our GitHub or PyPI credentials.
      #
      # Per the trusted publishing GitHub Action:
      # > It is strongly advised to separate jobs for building [...]
      # > from the publish job.
      # https://github.com/pypa/gh-action-pypi-publish#non-goals
      - name: Build project for distribution
        run: poetry build
        working-directory: ${{ inputs.working-directory }}

      - name: Upload build
        uses: actions/upload-artifact@v4
        with:
          name: test-dist
          path: ${{ inputs.working-directory }}/dist/

      - name: Check Version
        id: check-version
        shell: bash
        working-directory: ${{ inputs.working-directory }}
        run: |
          echo pkg-name="$(poetry version | cut -d ' ' -f 1)" >> $GITHUB_OUTPUT
          echo version="$(poetry version --short)" >> $GITHUB_OUTPUT

  publish:
    needs:
      - build
    runs-on: ubuntu-latest
    environment: Scheduled testing publish
    # permissions:
    #   id-token: none  # This is required for requesting the JWT

    steps:
      - uses: actions/checkout@v4

      - uses: actions/download-artifact@v4
        with:
          name: test-dist
          path: ${{ inputs.working-directory }}/dist/

      - name: Publish to test PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          user: __token__ 
          password: ${{ secrets.TEST_PYPI_API_TOKEN }}
          packages-dir: ${{ inputs.working-directory }}/dist/
          verbose: true
          print-hash: true
          repository-url: https://test.pypi.org/legacy/ 
          # We overwrite any existing distributions with the same name and version.
          # This is *only for CI use* and is *extremely dangerous* otherwise!
          # https://github.com/pypa/gh-action-pypi-publish#tolerating-release-package-file-duplicates
          skip-existing: true


================================================
FILE: .github/workflows/lint-pr.yaml
================================================
name: "Lint PR"

on:
  pull_request_target:
    types:
      - opened
      - edited
      - reopened

jobs:
  lint-pr:
    name: Validate PR title
    runs-on: ubuntu-latest
    permissions:
      pull-requests: read
    steps:
      - uses: amannn/action-semantic-pull-request@v5
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

================================================
FILE: .gitignore
================================================
.vscode
.idea
*.pyc
__pycache__/
.pytest_cache/
.DS_Store/

*.swp
*~

build/
dist/
eggs/
.eggs/
*.egg-info/
test/
examples/
.pypirc
/poetry.lock
logs
/tests/integration_tests/batchoutput.jsonl
/tests/integration_tests/content_batchoutput.jsonl
/tests/integration_tests/write_to_file_batchoutput.jsonl


================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of
experience, education, socio-economic status, nationality, personal appearance,
race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

*   Using welcoming and inclusive language
*   Being respectful of differing viewpoints and experiences
*   Gracefully accepting constructive criticism
*   Focusing on what is best for the community
*   Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

*   The use of sexualized language or imagery and unwelcome sexual attention or
    advances
*   Trolling, insulting/derogatory comments, and personal or political attacks
*   Public or private harassment
*   Publishing others' private information, such as a physical or electronic
    address, without explicit permission
*   Other conduct which could reasonably be considered inappropriate in a
    professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, or to ban temporarily or permanently any
contributor for other behaviors that they deem inappropriate, threatening,
offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

This Code of Conduct also applies outside the project spaces when the Project
Steward has a reasonable belief that an individual's behavior may have a
negative impact on the project or its community.

## Conflict Resolution

We do not believe that all conflict is bad; healthy debate and disagreement
often yield positive results. However, it is never okay to be disrespectful or
to engage in behavior that violates the project’s code of conduct.

If you see someone violating the code of conduct, you are encouraged to address
the behavior directly with those involved. Many issues can be resolved quickly
and easily, and this gives people more control over the outcome of their
dispute. If you are unable to resolve the matter for any reason, or if the
behavior is threatening or harassing, report it. We are dedicated to providing
an environment where participants feel welcome and safe.

Reports should be directed to *Weijun Zheng (weijun.zheng@aminer.cn)*, the
Project Steward(s) for *zhipuai-sdk-python-v4*. It is the Project Steward’s duty to
receive and address reported violations of the code of conduct. They will then
work with a committee consisting of representatives from the Open Source
Programs Office and the Z.ai Open Source Strategy team. 

We will investigate every complaint, but you may not receive a direct response.
We will use our discretion in determining when and how to follow up on reported
incidents, which may range from not taking action to permanent expulsion from
the project and project-sponsored spaces. We will notify the accused of the
report and provide them an opportunity to discuss it before any action is taken.
The identity of the reporter will be omitted from the details of the report
supplied to the accused. In potentially harmful situations, such as ongoing
harassment or threats to anyone's safety, we may take action without notice.

## Attribution

This Code of Conduct is adapted from the Contributor Covenant, version 1.4,
available at
https://www.contributor-covenant.org/version/1/4/code-of-conduct.html


================================================
FILE: CONTRIBUTING.md
================================================
# How to contribute

We'd love to accept your patches and contributions to this project.

## Contribution process

### Code reviews

All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.

### Contributor Guide

You may follow these steps to contribute:

1. **Fork the official repository.** This will create a copy of the official repository in your own account.
2. **Sync the branches.** This will ensure that your copy of the repository is up-to-date with the latest changes from the official repository.
3. **Work on your forked repository's feature branch.** This is where you will make your changes to the code.
4. **Commit your updates on your forked repository's feature branch.** This will save your changes to your copy of the repository.
5. **Submit a pull request to the official repository's main branch.** This will request that your changes be merged into the official repository.
6. **Resolve any linting errors.** This will ensure that your changes are formatted correctly.

Here are some additional things to keep in mind during the process:

- **Test your changes.** Before you submit a pull request, make sure that your changes work as expected.
- **Be patient.** It may take some time for your pull request to be reviewed and merged.





Have Fun!
---


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) Zhipu, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: Makefile
================================================
.PHONY: all format lint test tests test_watch integration_tests docker_tests help extended_tests

# Default target executed when no arguments are given to make.
all: help

######################
# TESTING AND COVERAGE
######################

# Define a variable for the test file path.
TEST_FILE ?= tests/unit_tests/


test tests:
	poetry run pytest --disable-socket --allow-unix-socket $(TEST_FILE)
integration_tests:
	poetry run pytest tests/integration_tests


######################
# LINTING AND FORMATTING
######################

# Define a variable for Python and notebook files.
PYTHON_FILES=.
MYPY_CACHE=.mypy_cache
lint format: PYTHON_FILES=.
lint_diff format_diff: PYTHON_FILES=$(shell git diff --relative=libs/langchain --name-only --diff-filter=d master | grep -E '\.py$$|\.ipynb$$')
lint_package: PYTHON_FILES=zhipuai
lint_tests: PYTHON_FILES=tests
lint_tests: MYPY_CACHE=.mypy_cache_test

lint lint_diff lint_package lint_tests:
	./scripts/check_pydantic.sh .
	./scripts/lint_imports.sh
	poetry run ruff .
	[ "$(PYTHON_FILES)" = "" ] || poetry run ruff format $(PYTHON_FILES) --diff
	[ "$(PYTHON_FILES)" = "" ] || poetry run ruff --select I $(PYTHON_FILES)
	[ "$(PYTHON_FILES)" = "" ] || mkdir -p $(MYPY_CACHE) && poetry run mypy $(PYTHON_FILES) --cache-dir $(MYPY_CACHE)

format format_diff:
	[ "$(PYTHON_FILES)" = "" ] || poetry run ruff format $(PYTHON_FILES)
	[ "$(PYTHON_FILES)" = "" ] || poetry run ruff --select I --fix $(PYTHON_FILES)


######################
# HELP
######################

help:
	@echo '-- LINTING --'
	@echo 'format                       - run code formatters'
	@echo 'lint                         - run linters'
	@echo '-- TESTS --'
	@echo 'test                         - run unit tests'
	@echo 'tests                        - run unit tests (alias for "make test")'
	@echo 'test TEST_FILE=<test_file>   - run all tests in file'


================================================
FILE: README.md
================================================
**The [New Python SDK](https://github.com/zai-org/z-ai-sdk-python) for Z.AI and ZhipuAI has released: [z-ai-sdk-python](https://github.com/zai-org/z-ai-sdk-python)!** It is recommended to use this SDK for better, faster, and long-term support.


# ZhipuAI Open Platform Python SDK

[![PyPI version](https://img.shields.io/pypi/v/zhipuai.svg)](https://pypi.org/project/zhipuai/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)

[中文文档](README_CN.md) | English

The official Python SDK for ZhipuAI's large model open interface, making it easier for developers to call ZhipuAI's open APIs.

## ✨ Features

- **Type Safety**: Complete type annotations for all interfaces
- **Easy Integration**: Simple initialization and intuitive method calls
- **High Performance**: Built-in connection pooling and request optimization
- **Secure**: Automatic token caching and secure API key management
- **Lightweight**: Minimal dependencies with efficient resource usage
- **Streaming Support**: Real-time streaming responses for chat completions

## 📦 Installation

### Requirements

- **Python**: 3.9+
- **Package Manager**: pip

### Install via pip

```bash
pip install zhipuai
```

### Core Dependencies

| Package | Version | Purpose |
|---------|---------|----------|
| `httpx` | `>=0.23.0` | HTTP client for API requests |
| `pydantic` | `>=1.9.0,<3.0.0` | Data validation and serialization |
| `typing-extensions` | `>=4.0.0` | Enhanced type hints support |

## 🚀 Quick Start

### Basic Usage

```python
from zhipuai import ZhipuAI

# Initialize client
client = ZhipuAI(api_key="your-api-key")

# Create chat completion
response = client.chat.completions.create(
    model="glm-4",
    messages=[
        {"role": "user", "content": "Hello, ZhipuAI!"}
    ]
)
print(response.choices[0].message.content)
```

### Client Configuration

#### Environment Variables

```bash
export ZHIPUAI_API_KEY="your-api-key"
export ZHIPUAI_BASE_URL="https://open.bigmodel.cn/api/paas/v4/"  # Optional
```

#### Code Configuration

```python
from zhipuai import ZhipuAI

client = ZhipuAI(
    api_key="your-api-key",
    base_url="https://open.bigmodel.cn/api/paas/v4/"  # Optional
)
```

### Advanced Configuration

Customize client behavior with additional parameters:

```python
from zhipuai import ZhipuAI
import httpx

client = ZhipuAI(
    api_key="your-api-key",
    timeout=httpx.Timeout(timeout=300.0, connect=8.0),  # Request timeout
    max_retries=3,  # Retry attempts
    base_url="https://open.bigmodel.cn/api/paas/v4/"  # Custom API endpoint
)
```

## 📖 Usage Examples

### Basic Chat

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")  # Uses environment variable ZHIPUAI_API_KEY
response = client.chat.completions.create(
    model="glm-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is artificial intelligence?"}
    ],
    tools=[
        {
            "type": "web_search",
            "web_search": {
                "search_query": "Search the Zhipu",
                "search_result": True,
            }
        }
    ],
    extra_body={"temperature": 0.5, "max_tokens": 50}
)
print(response)
```

### Streaming Chat

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")
response = client.chat.completions.create(
    model="glm-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Tell me a story about AI."}
    ],
    stream=True
)

for chunk in response:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta)
```

### Multimodal Chat

```python
import base64
from zhipuai import ZhipuAI

def encode_image(image_path):
    """Encode image to base64 format"""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

client = ZhipuAI(api_key="your-api-key")
base64_image = encode_image("path/to/your/image.jpg")

response = client.chat.completions.create(
    model="glm-4v",
    extra_body={"temperature": 0.5, "max_tokens": 50},
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What's in this image?"
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{base64_image}"
                    }
                }
            ]
        }
    ]
)
print(response)
```

### Character Role-Playing

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")
response = client.chat.completions.create(
    model="charglm-3",
    messages=[
        {
            "role": "user",
            "content": "Hello, how are you doing lately?"
        }
    ],
    meta={
        "user_info": "I am a film director who specializes in music-themed movies.",
        "bot_info": "You are a popular domestic female singer and actress with outstanding musical talent.",
        "bot_name": "Xiaoya",
        "user_name": "Director"
    }
)
print(response)
```

### Assistant Conversation

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")
response = client.assistant.conversation(
    assistant_id="your_assistant_id", # You can use 65940acff94777010aa6b796 for testing
    model="glm-4-assistant",
    messages=[
        {
            "role": "user",
            "content": [{
                "type": "text",
                "text": "Help me search for the latest ZhipuAI product information"
            }]
        }
    ],
    stream=True,
    attachments=None,
    metadata=None,
    request_id="request_1790291013237211136",
    user_id="12345678"
)

for chunk in response:
    print(chunk)
```

### Video Generation

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")
response = client.videos.generations(
    model="cogvideox-2",
    prompt="A beautiful sunset beach scene",
    quality="quality",          # Output mode: use "quality" for higher quality, "speed" for faster generation
    with_audio=True,            # Generate video with background audio
    size="1920x1080",           # Video resolution (up to 4K, e.g. "3840x2160")
    fps=30,                     # Frames per second (choose 30 fps or 60 fps)
    user_id="user_12345"
)

# Generation may take some time
result = client.videos.retrieve_videos_result(id=response.id)
print(result)
```

## 🚨 Error Handling

The SDK provides comprehensive error handling:

```python
from zhipuai import ZhipuAI
import zhipuai

client = ZhipuAI()

try:
    response = client.chat.completions.create(
        model="glm-4",
        messages=[
            {"role": "user", "content": "Hello, ZhipuAI!"}
        ]
    )
    print(response.choices[0].message.content)
    
except zhipuai.APIStatusError as err:
    print(f"API Status Error: {err}")
except zhipuai.APITimeoutError as err:
    print(f"Request Timeout: {err}")
except Exception as err:
    print(f"Other Error: {err}")
```

### Error Codes

| Status Code | Error Type | Description |
|-------------|------------|-------------|
| 400 | `APIRequestFailedError` | Invalid request parameters |
| 401 | `APIAuthenticationError` | Authentication failed |
| 429 | `APIReachLimitError` | Rate limit exceeded |
| 500 | `APIInternalError` | Internal server error |
| 503 | `APIServerFlowExceedError` | Server overloaded |
| N/A | `APIStatusError` | General API error |

## 📈 Version Updates

For detailed version history and update information, please see [Release-Note.md](Release-Note.md).

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## 📞 Support

For questions and technical support, please visit [ZhipuAI Open Platform](https://open.bigmodel.cn/) or check our documentation.
  


================================================
FILE: README_CN.md
================================================
Z.AI 和 智谱AI 的 [全新 Python SDK](https://github.com/zai-org/z-ai-sdk-python) 已经发布:[z-ai-sdk-python](https://github.com/zai-org/z-ai-sdk-python)!推荐使用此 SDK,以获得更好、更快的长期支持。


# 智谱AI开放平台 Python SDK

[![PyPI version](https://img.shields.io/pypi/v/zhipuai.svg)](https://pypi.org/project/zhipuai/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/)

[English Readme](README.md)

[智谱AI开放平台](https://open.bigmodel.cn/dev/api)官方 Python SDK,帮助开发者快速集成智谱AI强大的人工智能能力到Python应用中。

## ✨ 特性

- 🚀 **类型安全**: 所有接口完全类型封装,无需查阅API文档即可完成接入
- 🔧 **简单易用**: 简洁直观的API设计,快速上手
- ⚡ **高性能**: 基于现代Python库构建,性能优异
- 🛡️ **安全可靠**: 内置身份验证和令牌管理
- 📦 **轻量级**: 最小化依赖,易于项目集成
- 🔄 **流式支持**: 支持SSE流式响应和异步调用

## 📦 安装

### 环境要求
- Python 3.9 或更高版本
- pip 包管理器

### 使用 pip 安装

```sh
pip install zhipuai
```

### 📋 核心依赖

本SDK使用以下核心依赖库:

| 依赖库 | 用途 |
|--------|------|
| httpx | HTTP客户端库 |
| pydantic | 数据验证和序列化 |
| typing-extensions | 类型注解扩展 |

## 🚀 快速开始

### 基本用法

1. **使用API密钥创建客户端**
2. **调用相应的API方法**

完整示例请参考开放平台[接口文档](https://open.bigmodel.cn/dev/api)以及[使用指南](https://open.bigmodel.cn/dev/howuse/),记得替换为您自己的API密钥。

### 客户端配置

SDK支持多种方式配置API密钥:

**环境变量配置:**
```bash
export ZHIPUAI_API_KEY="your_api_key_here"
export ZHIPUAI_BASE_URL="https://open.bigmodel.cn/api/paas/v4/"  # 可选
```

**代码配置:**
```python
from zhipuai import ZhipuAI

client = ZhipuAI(
    api_key="your_api_key_here",  # 填写您的 APIKey
) 
```
**高级配置:**

SDK提供了灵活的客户端配置选项:

```python
import httpx
from zhipuai import ZhipuAI

client = ZhipuAI(
    api_key="your_api_key_here",
    timeout=httpx.Timeout(timeout=300.0, connect=8.0),  # 超时配置
    max_retries=3,  # 重试次数
    base_url="https://open.bigmodel.cn/api/paas/v4/"  # Custom API endpoint
)
```

**配置选项:**
- `timeout`: 控制接口连接和读取超时时间
- `max_retries`: 控制重试次数,默认为3次
- `base_url`: 自定义API基础URL


## 💡 使用示例

### 基础对话

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")  # 请填写您自己的APIKey
response = client.chat.completions.create(
    model="glm-4",  # 填写需要调用的模型名称
    messages=[
        {"role": "user", "content": "你好,请介绍一下智谱AI"}
    ],
    tools=[
        {
            "type": "web_search",
            "web_search": {
                "search_query": "Search the Zhipu",
                "search_result": True,
            }
        }
    ],
    extra_body={"temperature": 0.5, "max_tokens": 50}
)
print(response.choices[0].message.content)
```

### 流式对话

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")  # 请填写您自己的APIKey
response = client.chat.completions.create(
    model="glm-4",  # 填写需要调用的模型名称
    messages=[
        {"role": "system", "content": "你是一个人工智能助手,你叫ChatGLM"},
        {"role": "user", "content": "你好!你叫什么名字"},
    ],
    stream=True,
)

for chunk in response:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta)
```

### 多模态对话

```python
import base64
from zhipuai import ZhipuAI

def encode_image(image_path):
    """将图片编码为base64格式"""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

client = ZhipuAI()  # 请填写您自己的APIKey
base64_image = encode_image("path/to/your/image.jpg")

response = client.chat.completions.create(
    model="glm-4v",  # 视觉模型
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "请描述这张图片的内容"
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{base64_image}"
                    }
                }
            ]
        }
    ],
    extra_body={"temperature": 0.5, "max_tokens": 50}
)
print(response.choices[0].message.content)
```

### 角色扮演

```python
from zhipuai import ZhipuAI

client = ZhipuAI()  # 请填写您自己的APIKey
response = client.chat.completions.create(
    model="charglm-3",  # 角色扮演模型
    messages=[
        {
            "role": "user",
            "content": "你好,最近在忙什么呢?"
        }
    ],
    meta={
        "user_info": "我是一位电影导演,擅长拍摄音乐题材的电影。",
        "bot_info": "你是一位当红的国内女歌手及演员,拥有出众的音乐才华。",
        "bot_name": "小雅",
        "user_name": "导演"
    },
)
print(response.choices[0].message.content)
```

### 智能体对话

```python
from zhipuai import ZhipuAI

client = ZhipuAI()  # 请填写您自己的APIKey

response = client.assistant.conversation(
    assistant_id="your_assistant_id",  # 智能体ID,可用 65940acff94777010aa6b796 进行测试
    model="glm-4-assistant",
    messages=[
        {
            "role": "user",
            "content": [{
                "type": "text",
                "text": "帮我搜索智谱AI的最新产品信息"
            }]
        }
    ],
    stream=True,
    attachments=None,
    metadata=None,
    request_id="request_1790291013237211136",
    user_id="12345678"
)

for chunk in response:
    print(chunk)
```

### 视频生成

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")
response = client.videos.generations(
    model="cogvideox-2",
    prompt="一个美丽的日落海滩场景",   # 生成内容的提示词
    quality="quality",          # 输出模式:'quality' 表示质量优先,'speed' 表示速度优先
    with_audio=True,            # 生成带背景音频的视频
    size="1920x1080",           # 视频分辨率(最高支持 4K,例如 "3840x2160")
    fps=30,                     # 帧率(可选 30 或 60)
    user_id="user_12345"
)

# 生成过程可能需要一些时间
result = client.videos.retrieve_videos_result(id=response.id)
print(result)
```

## 🚨 异常处理

SDK提供了完善的异常处理机制:

```python
from zhipuai import ZhipuAI
import zhipuai

client = ZhipuAI()  # 请填写您自己的APIKey

try:
    response = client.chat.completions.create(
        model="glm-4",
        messages=[
            {"role": "user", "content": "你好,智谱AI!"}
        ]
    )
    print(response.choices[0].message.content)
    
except zhipuai.APIStatusError as err:
    print(f"API状态错误: {err}")
except zhipuai.APITimeoutError as err:
    print(f"请求超时: {err}")
except Exception as err:
    print(f"其他错误: {err}")
```

### 错误码说明

| 状态码 | 错误类型 | 说明 |
|--------|----------|------|
| 400 | `APIRequestFailedError` | 请求参数错误 |
| 401 | `APIAuthenticationError` | 身份验证失败 |
| 429 | `APIReachLimitError` | 请求频率超限 |
| 500 | `APIInternalError` | 服务器内部错误 |
| 503 | `APIServerFlowExceedError` | 服务器流量超限 |
| N/A | `APIStatusError` | 通用API错误 |

## 📈 版本更新

详细的版本更新记录和历史信息,请查看 [Release-Note.md](Release-Note.md)。

## 📄 许可证

本项目基于 MIT 许可证开源 - 详情请查看 [LICENSE](LICENSE) 文件。

## 🤝 贡献

欢迎贡献代码!请随时提交 Pull Request。

## 📞 支持

如有问题和技术支持,请访问 [智谱AI开放平台](https://open.bigmodel.cn/) 或查看我们的文档。
  


================================================
FILE: Release-Note.md
================================================
## Release Notes

### 2024-08-12

**New Features:**
- Modified video prompt to be optional, added file deletion functionality
- Added Assistant business logic
- Fixed embedding 3 dimensions

### 2024-07-25

**Bug Fixes:**
- Fixed cogvideo related issues

### 2024-07-12

**New Features:**
- Added advanced search tool Web search business logic
- Specified Python versions support (3.8, 3.9, 3.10, 3.11, 3.12)
- Integrated cogvideo business functionality

### 2024-05-20

**Improvements:**
- Fixed some `python3.12` dependency issues
- Added pagination processing code, rewrote instantiation rules for some response classes
- Added type conversion validation
- Added batch task related APIs
- Added file stream response wrapper

### 2024-04-29

**Improvements:**
- Fixed some `python3.7` code compatibility issues
- Added interface failure retry mechanism, controlled by `retry` parameter with default of 3 retries
- Adjusted interface timeout strategy, controlled by `Timeout` for interface `connect` and `read` timeout, default `timeout=300.0, connect=8.0`
- Added support for super-humanoid large model parameters in conversation module, `model="charglm-3"`, `meta` parameter support

### 2024-04-23

**Improvements:**
- Fixed some compatibility issues with `pydantic<3,>=1.9.0`
- Message processing business request and response parameters can be extended through configuration
- Compatible with some parameters `top_p:1`, `temperature:0` (do_sample rewritten to false, parameters top_p temperature do not take effect)
- Image understanding part, image_url parameter base64 content containing `data:image/jpeg;base64` compatibility
- Removed JWT authentication logic

---

## Migration Guide

For users upgrading from older versions, please note the following breaking changes:

### From v3.x to v4.x

- API key configuration has been simplified
- Some method signatures have changed for better type safety
- Error handling has been improved with more specific exception types

## Support

For questions about specific versions or upgrade assistance, please visit our [documentation](https://open.bigmodel.cn/) or contact our support team.

---

## 版本更新

### 2024-08-12

**新功能:**
- ✅ 视频提示词设为可选,新增文件删除功能
- ✅ 智能助手业务逻辑
- 🔧 修复 embedding 3 维度问题

### 2024-07-25

**问题修复:**
- 🔧 修复 cogvideo 相关问题

### 2024-07-12

**新功能:**
- ✅ 高级搜索工具 Web search 业务逻辑
- ✅ 指定 Python 版本支持 (3.8, 3.9, 3.10, 3.11, 3.12)
- ✅ 集成 cogvideo 业务功能

### 2024-05-20

**改进优化:**
- 🔧 修复部分 `python3.12` 依赖问题
- ✅ 新增分页处理代码,重写部分响应类实例化规则
- ✅ 新增类型转换校验
- ✅ 批处理任务相关 API
- ✅ 文件流响应包装器

### 2024-04-29

**改进优化:**
- 🔧 修复部分 `python3.7` 代码兼容性问题
- ✅ 接口失败重试机制,通过 `retry` 参数控制重试次数,默认 3 次
- ⏱️ 调整接口超时策略,通过 `Timeout` 控制接口 `connect` 和 `read` 超时时间,默认 `timeout=300.0, connect=8.0`
- ✅ 对话模块新增超拟人大模型参数支持,`model="charglm-3"`,`meta` 参数支持

### 2024-04-23

**改进优化:**
- 🔧 修复部分 `pydantic<3,>=1.9.0` 兼容性问题
- ✅ 报文处理的业务请求参数和响应参数可通过配置扩充
- ✅ 兼容部分参数 `top_p:1`,`temperature:0`(do_sample 重写为 false,参数 top_p temperature 不生效)
- ✅ 图像理解部分,image_url 参数 base64 内容包含 `data:image/jpeg;base64` 兼容性
- 🔄 删除 JWT 认证逻辑

---

## 迁移指南

对于从旧版本升级的用户,请注意以下重大变更:

### 从 v3.x 到 v4.x

- API 密钥配置已简化
- 部分方法签名已更改以提供更好的类型安全性
- 错误处理已改进,提供更具体的异常类型

## 技术支持

如有特定版本问题或升级协助需求,请访问我们的[文档](https://open.bigmodel.cn/)或联系我们的支持团队。

================================================
FILE: poetry.toml
================================================
[virtualenvs]
in-project = true

[installer]
modern-installation = false


================================================
FILE: pyproject.toml
================================================
[tool.poetry]
name = "zhipuai"
version = "2.1.5.20250825"
description = "A SDK library for accessing big model apis from ZhipuAI"
authors = ["Zhipu AI"]
readme = "README.md"

[tool.poetry.dependencies]
python = ">=3.8,<4.0.0,!=3.9.7 "
httpx = ">=0.23.0"
pydantic = ">=1.9.0,<3.0"
pydantic-core = ">=2.14.6"
cachetools = ">=4.2.2"
pyjwt = "~=2.8.0"


[tool.poetry.group.test.dependencies]
# The only dependencies that should be added are
# dependencies used for running tests (e.g., pytest, freezegun, response).
# Any dependencies that do not meet that criteria will be removed.
pytest = "^7.3.0"
pytest-cov = "^4.0.0"
pytest-dotenv = "^0.5.2"
duckdb-engine = "^0.9.2"
pytest-watcher = "^0.2.6"
freezegun = "^1.2.2"
responses = "^0.22.0"
pytest-asyncio = { version = "^0.23.2", python = "^3.8" }
lark = "^1.1.5"
pytest-mock = "^3.10.0"
pytest-socket = { version = "^0.6.0", python = ">=3.8.1,<3.9.7 || >3.9.7,<4.0" }
syrupy = { version = "^4.0.2", python = ">=3.8.1,<3.9.7 || >3.9.7,<4.0" }
requests-mock = "^1.11.0"
respx = "0.21.1"


[tool.poetry.group.lint]
optional = true

[tool.poetry.group.lint.dependencies]
ruff = "^0.1.5"

[tool.poetry.extras]
cli = ["typer"]
# An extra used to be able to add extended testing.
# Please use new-line on formatting to make it easier to add new packages without
# merge-conflicts
extended_testing = [
    "langchain",
]

[tool.ruff.lint]
select = [
    "E",    # pycodestyle
    "F",    # pyflakes
    "I",    # isort
    "T201", # print
]

[tool.ruff]
line-length = 88

[tool.ruff.format]
quote-style = "single"
indent-style = "tab"
docstring-code-format = true

[tool.coverage.run]
omit = [
    "tests/*",
]

[build-system]
requires = ["poetry-core>=1.0.0", "poetry-plugin-pypi-mirror==0.4.2"]
build-backend = "poetry.core.masonry.api"

[tool.pytest.ini_options]
# --strict-markers will raise errors on unknown marks.
# https://docs.pytest.org/en/7.1.x/how-to/mark.html#raising-errors-on-unknown-marks
#
# https://docs.pytest.org/en/7.1.x/reference/reference.html
# --strict-config       any warnings encountered while parsing the `pytest`
#                       section of the configuration file raise errors.
#
# https://github.com/tophat/syrupy
# --snapshot-warn-unused    Prints a warning on unused snapshots rather than fail the test suite.
addopts = "--strict-markers --strict-config --durations=5 --snapshot-warn-unused -svv"
# Registering custom markers.
# https://docs.pytest.org/en/7.1.x/example/markers.html#registering-markers
markers = [
    "requires: mark tests as requiring a specific library",
    "scheduled: mark tests to run in scheduled testing",
    "compile: mark placeholder test used to compile integration tests without running them"
]
asyncio_mode = "auto"


# https://python-poetry.org/docs/repositories/
#[[tool.poetry.source]]
#name = "tsinghua"
#url = "https://pypi.tuna.tsinghua.edu.cn/simple/"
#priority = "default"


================================================
FILE: tests/conftest.py
================================================
"""Configuration for unit tests."""

from importlib import util
from pathlib import Path
from typing import Dict, Sequence

import pytest
from pytest import Config, Function, Parser

from zhipuai.core.logs import (
	get_config_dict,
	get_log_file,
	get_timestamp_ms,
)


def pytest_addoption(parser: Parser) -> None:
	"""Add custom command line options to pytest."""
	parser.addoption(
		'--only-extended',
		action='store_true',
		help='Only run extended tests. Does not allow skipping any extended tests.',
	)
	parser.addoption(
		'--only-core',
		action='store_true',
		help='Only run core tests. Never runs any extended tests.',
	)


def pytest_collection_modifyitems(config: Config, items: Sequence[Function]) -> None:
	"""Add implementations for handling custom markers.

	At the moment, this adds support for a custom `requires` marker.

	The `requires` marker is used to denote tests that require one or more packages
	to be installed to run. If the package is not installed, the test is skipped.

	The `requires` marker syntax is:

	.. code-block:: python

	    @pytest.mark.requires('package1', 'package2')
	    def test_something(): ...
	"""
	# Mapping from the name of a package to whether it is installed or not.
	# Used to avoid repeated calls to `util.find_spec`
	required_pkgs_info: Dict[str, bool] = {}

	only_extended = config.getoption('--only-extended') or False
	only_core = config.getoption('--only-core') or False

	if only_extended and only_core:
		raise ValueError('Cannot specify both `--only-extended` and `--only-core`.')

	for item in items:
		requires_marker = item.get_closest_marker('requires')
		if requires_marker is not None:
			if only_core:
				item.add_marker(pytest.mark.skip(reason='Skipping not a core test.'))
				continue

			# Iterate through the list of required packages
			required_pkgs = requires_marker.args
			for pkg in required_pkgs:
				# If we haven't yet checked whether the pkg is installed
				# let's check it and store the result.
				if pkg not in required_pkgs_info:
					try:
						installed = util.find_spec(pkg) is not None
					except Exception:
						installed = False
					required_pkgs_info[pkg] = installed

				if not required_pkgs_info[pkg]:
					if only_extended:
						pytest.fail(
							f'Package `{pkg}` is not installed but is required for '
							f'extended tests. Please install the given package and '
							f'try again.',
						)

					else:
						# If the package is not installed, we immediately break
						# and mark the test as skipped.
						item.add_marker(pytest.mark.skip(reason=f'Requires pkg: `{pkg}`'))
						break
		else:
			if only_extended:
				item.add_marker(pytest.mark.skip(reason='Skipping not an extended test.'))


@pytest.fixture
def logging_conf() -> dict:
	return get_config_dict(
		'info',
		get_log_file(log_path='logs', sub_dir=f'local_{get_timestamp_ms()}'),
		1024 * 1024,
		1024 * 1024 * 1024,
	)


@pytest.fixture
def test_file_path(request) -> Path:
	from pathlib import Path

	# 当前执行目录
	# 获取当前测试文件的路径
	test_file_path = Path(str(request.fspath)).parent
	print('test_file_path:', test_file_path)
	return test_file_path


================================================
FILE: tests/integration_tests/batchinput.jsonl
================================================
{"custom_id": "request-1", "method": "POST", "url": "/v4/chat/completions", "body": {"model": "glm-4", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}
{"custom_id": "request-2", "method": "POST", "url": "/v4/chat/completions", "body": {"model": "glm-4", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}

================================================
FILE: tests/integration_tests/demo.jsonl
================================================
{"messages": [{"role": "system", "content": "你是一位乐于助人,知识渊博的全能AI助手。"},{"role": "user", "content": "请介绍一下AlphaGo的基本原理。"}, {"role": "assistant", "content": "AlphaGo利用深度神经网络与树搜索算法相结合,通过对弈数据进行训练,逐步提升游戏水平,能够对围棋局面进行判断并选择最佳落子位置。"}]}
{"messages": [{"role": "system", "content": "你是一位乐于助人,知识渊博的全能AI助手。"},{"role": "user", "content": "请列举一些健康饮食的重要原则。"}, {"role": "assistant", "content": "健康饮食的重要原则包括:膳食应营养均衡,合理摄入各种营养素;多吃新鲜蔬果,适量饮水;少吃糖、油、盐,忌吃过量快餐;养成规律生活作息习惯,适量运动。"}]}
{"messages": [{"role": "system", "content": "你是一位乐于助人,知识渊博的全能AI助手。"},{"role": "user", "content": "请给出一些改善睡眠质量的建议。"}, {"role": "assistant", "content": "改善睡眠质量的建议包括:保证睡眠时间,避免睡眠不足;睡前放松身心,远离刺激;养成规律作息时间,不要频繁熬夜;适量运动,但不要运动过度;睡前可以喝一杯热牛奶等温和饮料。"}]}

================================================
FILE: tests/integration_tests/test.py
================================================
import time

from zhipuai import ZhipuAI

client = ZhipuAI()  # 填写您自己的APIKey

response = client.videos.generations(
	model='cogvideo',
	prompt='一个年轻的艺术家在一片彩虹上用调色板作画。',
	# prompt="一只卡通狐狸在森林里跳着欢快的爵士舞。"
	# prompt="这是一部汽车广告片,描述了一位30岁的汽车赛车手戴着红色头盔的赛车冒险。背景是蔚蓝的天空和苛刻的沙漠环境,电影风格使用35毫米胶片拍摄,色彩鲜艳夺目。"
)
print(response)
task_id = response.id
task_status = response.task_status
get_cnt = 0

while task_status == 'PROCESSING' and get_cnt <= 40:
	result_response = client.videos.retrieve_videos_result(id=task_id)
	print(result_response)
	task_status = result_response.task_status

	time.sleep(2)
	get_cnt += 1


================================================
FILE: tests/integration_tests/test_agents.py
================================================
import logging
import logging.config
import time

import zhipuai
from zhipuai import ZhipuAI


def test_completions_sync(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.agents.invoke(
			request_id=request_id,
			agent_id='general_translation',
			messages=[{'role': 'user', 'content': 'tell me a joke'}],
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_stream(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.agents.invoke(
			request_id=request_id,
			agent_id='general_translation',
			messages=[{'role': 'user', 'content': 'tell me a joke'}],
			user_id='12345678',
			stream=True,
		)
		for item in response:
			print(item)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)

def test_correction():
	client = ZhipuAI()  # 请替换为实际API密钥

	response = client.agents.invoke(
		agent_id="intelligent_education_correction_agent",
		messages=[
				{
					"role": "user",
					"content": [
						{
							"type": "image_url",
							"image_url": "https://b0.bdstatic.com/e24937f1f6b9c0ff6895e1012c981515.jpg"
						}
					]
				}
			]
		)
	print(response)
 
def test_correction_result(image_id,uuids,trace_id):
	client = ZhipuAI()

	response = client.agents.async_result(
		agent_id="intelligent_education_correction_polling",
		custom_variables={
				"images": [
					{
						"image_id": image_id,
						"uuids": uuids
					}
				],
				"trace_id": trace_id
		}
	)
	print(response)
 
def main():
    test_completions_sync()
    test_completions_stream()
    # test_correction()
	# test_correction_result(image_id,uuids,trace_id)

if __name__ == "__main__":
	main()

================================================
FILE: tests/integration_tests/test_assistant.py
================================================
import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_assistant(logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		generate = client.assistant.conversation(
			assistant_id='659e54b1b8006379b4b2abd6',
			messages=[
				{
					'role': 'user',
					'content': [{'type': 'text', 'text': '帮我搜索下智谱的cogvideox发布时间'}],
				}
			],
			stream=True,
			attachments=None,
			metadata=None,
			request_id='request_1790291013237211136',
			user_id='12345678',
		)
		for assistant in generate:
			print(assistant)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_assistant_query_support(logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.assistant.query_support(
			assistant_id_list=[],
			request_id='request_1790291013237211136',
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_assistant_query_conversation_usage(logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.assistant.query_conversation_usage(
			assistant_id='659e54b1b8006379b4b2abd6',
			request_id='request_1790291013237211136',
			user_id='12345678',
		)
		print(response)
	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_translate_api(logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		translate_response = client.assistant.conversation(
			assistant_id='9996ijk789lmn012o345p999',
			messages=[{'role': 'user', 'content': [{'type': 'text', 'text': '你好呀'}]}],
			stream=True,
			attachments=None,
			metadata=None,
			request_id='request_1790291013237211136',
			user_id='12345678',
			extra_parameters={'translate': {'from': 'zh', 'to': 'en'}},
		)
		for chunk in translate_response:
			print(chunk.choices[0].delta)
		# print(translate_response)
	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_audio.py
================================================
import base64
import json
import logging
import logging.config
from pathlib import Path

import zhipuai
from zhipuai import ZhipuAI


def test_audio_speech(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		speech_file_path = Path(__file__).parent / 'speech.wav'
		response = client.audio.speech(
			model='cogtts',
			input='你好呀,欢迎来到智谱开放平台',
			voice='tongtong',
			stream=False,
			response_format='wav',
		)
		response.stream_to_file(speech_file_path)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)

def test_audio_speech_streaming(logging_conf):
    logging.config.dictConfig(logging_conf)  # type: ignore
    client = ZhipuAI()  # 填写您自己的APIKey
    try:
       response = client.audio.speech(
          model='cogtts',
          input='你好呀,欢迎来到智谱开放平台',
          voice='tongtong',
          stream=True,
          response_format='mp3',
          encode_format='hex'
       )
       with open("output.mp3", "wb") as f:
          for item in response:
             choice = item.choices[0]
             index = choice.index
             finish_reason = choice.finish_reason
             audio_delta = choice.delta.content
             if finish_reason is not None:
                break
             f.write(bytes.fromhex(audio_delta))
             print(f"audio delta: {audio_delta[:64]}..., 长度:{len(audio_delta)}")
    except zhipuai.core._errors.APIRequestFailedError as err:
       print(err)
    except zhipuai.core._errors.APIInternalError as err:
       print(err)
    except zhipuai.core._errors.APIStatusError as err:
       print(err)
    except Exception as e:
       print(e)


def test_audio_customization(logging_conf):
	logging.config.dictConfig(logging_conf)
	client = ZhipuAI()  # 填写您自己的APIKey
	with open(Path(__file__).parent / 'speech.wav', 'rb') as file:
		try:
			speech_file_path = Path(__file__).parent / 'speech.wav'
			response = client.audio.customization(
				model='cogtts',
				input='你好呀,欢迎来到智谱开放平台',
				voice_text='这是一条测试用例',
				voice_data=file,
				response_format='wav',
			)
			response.stream_to_file(speech_file_path)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)


================================================
FILE: tests/integration_tests/test_batches.py
================================================
import logging
import logging.config
import os

import zhipuai
from zhipuai import ZhipuAI


def test_batch_input_file(test_file_path, logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey

	try:
		batch_input_file = client.files.create(
			file=open(os.path.join(test_file_path, 'batchinput.jsonl'), 'rb'),
			purpose='batch',
		)

		print(batch_input_file)

	#   FileObject(id='20240514_ea19d21b-d256-4586-b0df-e80a45e3c286', bytes=490, created_at=1715673494, filename=None, object='file', purpose='batch', status=None, status_details=None, fileName='batchinput.jsonl')

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_batch_create(logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		create = client.batches.create(
			input_file_id='20240514_ea19d21b-d256-4586-b0df-e80a45e3c286',
			endpoint='/v4/chat/completions',
			completion_window='24h',
			metadata={'description': 'job test'},
			auto_delete_input_file=True,
		)
		print(create)
		# Batch(id='batch_1790292763050508288', completion_window='24h', created_at=1715674031399, endpoint='/v4/chat/completions', input_file_id='20240514_ea19d21b-d256-4586-b0df-e80a45e3c286', object='batch', status='validating', cancelled_at=None, cancelling_at=None, completed_at=None, error_file_id=None, errors=None, expired_at=None, expires_at=None, failed_at=None, finalizing_at=None, in_progress_at=None, metadata={'description': 'job test'}, output_file_id=None, request_counts=BatchRequestCounts(completed=None, failed=None, total=None))

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_batch_retrieve(logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		retrieve = client.batches.retrieve('batch_1790291013237211136')
		print(retrieve)

	#   Batch(id='batch_1790291013237211136', completion_window='24h', created_at=1715673614000, endpoint='/v4/chat/completions', input_file_id='20240514_ea19d21b-d256-4586-b0df-e80a45e3c286', object='batch', status='validating', cancelled_at=None, cancelling_at=None, completed_at=None, error_file_id='', errors=None, expired_at=None, expires_at=None, failed_at=None, finalizing_at=None, in_progress_at=None, metadata={'description': 'job test'}, output_file_id='', request_counts=BatchRequestCounts(completed=None, failed=None, total=None))
	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_batch_cancel(logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		cancel = client.batches.cancel('batch_1790291013237211136')
		print(cancel)
		# Batch(id='batch_1790291013237211136', completion_window='24h', created_at=1715673614000, endpoint='/v4/chat/completions', input_file_id='20240514_ea19d21b-d256-4586-b0df-e80a45e3c286', object='batch', status='cancelling', cancelled_at=None, cancelling_at=1715673698775, completed_at=None, error_file_id='', errors=None, expired_at=None, expires_at=None, failed_at=None, finalizing_at=None, in_progress_at=None, metadata={'description': 'job test'}, output_file_id='', request_counts=BatchRequestCounts(completed=None, failed=None, total=None))
	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_batch_list(logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		list = client.batches.list(limit=10)
		print(list)
		if list.has_more:
			print('_________get_next_page___________')
			batch = list.get_next_page()
			print(batch)
			print('_________iter_pages___________')
			for batch in list.iter_pages():
				print(batch)
	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_batch_result(test_file_path, logging_conf) -> None:
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		content = client.files.content('file-QDpVyDIhxj8mcFiduUydNqQN')
		with open(os.path.join(test_file_path, 'content_batchoutput.jsonl'), 'wb') as f:
			f.write(content.content)
		content.write_to_file(os.path.join(test_file_path, 'write_to_file_batchoutput.jsonl'))

		assert (
			content.content == open(os.path.join(test_file_path, 'batchoutput.jsonl'), 'rb').read()
		)
		assert (
			content.content
			== open(os.path.join(test_file_path, 'write_to_file_batchoutput.jsonl'), 'rb').read()
		)
	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_charglm3.py
================================================
# -*- coding: utf-8 -*-

import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_completions_charglm(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		response = client.chat.completions.create(
			model='charglm-3',  # 填写需要调用的模型名称
			messages=[{'role': 'user', 'content': '请问你在做什么'}],
			meta={
				'user_info': '我是陆星辰,是一个男性,是一位知名导演,也是苏梦远的合作导演。我擅长拍摄音乐题材的电影。苏梦远对我的态度是尊敬的,并视我为良师益友。',
				'bot_info': '苏梦远,本名苏远心,是一位当红的国内女歌手及演员。在参加选秀节目后,凭借独特的嗓音及出众的舞台魅力迅速成名,进入娱乐圈。她外表美丽动人,但真正的魅力在于她的才华和勤奋。苏梦远是音乐学院毕业的优秀生,善于创作,拥有多首热门原创歌曲。除了音乐方面的成就,她还热衷于慈善事业,积极参加公益活动,用实际行动传递正能量。在工作中,她对待工作非常敬业,拍戏时总是全身心投入角色,赢得了业内人士的赞誉和粉丝的喜爱。虽然在娱乐圈,但她始终保持低调、谦逊的态度,深得同行尊重。在表达时,苏梦远喜欢使用“我们”和“一起”,强调团队精神。',
				'bot_name': '苏梦远',
				'user_name': '陆星辰',
			},
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_async_completions():
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		response = client.chat.asyncCompletions.create(
			model='charglm',  # 填写需要调用的模型名称
			messages=[{'role': 'user', 'content': '请问你在做什么'}],
			meta={
				'user_info': '我是陆星辰,是一个男性,是一位知名导演,也是苏梦远的合作导演。我擅长拍摄音乐题材的电影。苏梦远对我的态度是尊敬的,并视我为良师益友。',
				'bot_info': '苏梦远,本名苏远心,是一位当红的国内女歌手及演员。在参加选秀节目后,凭借独特的嗓音及出众的舞台魅力迅速成名,进入娱乐圈。她外表美丽动人,但真正的魅力在于她的才华和勤奋。苏梦远是音乐学院毕业的优秀生,善于创作,拥有多首热门原创歌曲。除了音乐方面的成就,她还热衷于慈善事业,积极参加公益活动,用实际行动传递正能量。在工作中,她对待工作非常敬业,拍戏时总是全身心投入角色,赢得了业内人士的赞誉和粉丝的喜爱。虽然在娱乐圈,但她始终保持低调、谦逊的态度,深得同行尊重。在表达时,苏梦远喜欢使用“我们”和“一起”,强调团队精神。',
				'bot_name': '苏梦远',
				'user_name': '陆星辰',
			},
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


# def test_retrieve_completion_result():
#     client = ZhipuAI()  # 请填写您自己的APIKey
#     try:
#         response = client.chat.asyncCompletions.retrieve_completion_result(id="1014908592669352541650991")
#         print(response)
#
#
#     except zhipuai.core._errors.APIRequestFailedError as err:
#         print(err)
#     except zhipuai.core._errors.APIInternalError as err:
#         print(err)

# if __name__ == "__main__":
#     test_retrieve_completion_result()


================================================
FILE: tests/integration_tests/test_chat.py
================================================
import logging
import logging.config
import os.path
import time

import zhipuai
from zhipuai import ZhipuAI


def test_completions_temp0(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',
			messages=[{'role': 'user', 'content': 'tell me a joke'}],
			top_p=0.7,
			temperature=0,
			max_tokens=2000,
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_temp1(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',
			messages=[{'role': 'user', 'content': 'tell me a joke'}],
			top_p=0.7,
			temperature=1,
			max_tokens=2000,
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_top0(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',
			messages=[{'role': 'user', 'content': 'tell me a joke'}],
			top_p=0,
			temperature=0.9,
			max_tokens=2000,
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_top1(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',
			messages=[{'role': 'user', 'content': 'tell me a joke'}],
			top_p=1,
			temperature=0.9,
			max_tokens=2000,
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',  # 填写需要调用的模型名称
			messages=[
				{
					'role': 'user',
					'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
				},
				{
					'role': 'assistant',
					'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
				},
				{'role': 'user', 'content': '智谱AI开放平台'},
				{
					'role': 'assistant',
					'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
				},
				{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
			],
			tools=[
				{
					'type': 'web_search',
					'web_search': {
						'search_query': '帮我看看清华的升学率',
						'search_result': True,
					},
				}
			],
			user_id='12345678',
			extra_body={'temperature': 0.5, 'max_tokens': 50},
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_disenable_web_search(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',  # 填写需要调用的模型名称
			messages=[
				{
					'role': 'user',
					'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
				},
				{
					'role': 'assistant',
					'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
				},
				{'role': 'user', 'content': '智谱AI开放平台'},
				{
					'role': 'assistant',
					'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
				},
				{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
			],
			tools=[
				{
					'type': 'web_search',
					'web_search': {
						'search_query': '帮我看看清华的升学率',
						'search_result': True,
						'enable': False,
					},
				}
			],
			user_id='12345678',
			extra_body={'temperature': 0.5, 'max_tokens': 50},
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_enable_web_search(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',  # 填写需要调用的模型名称
			messages=[
				{
					'role': 'user',
					'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
				},
				{
					'role': 'assistant',
					'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
				},
				{'role': 'user', 'content': '智谱AI开放平台'},
				{
					'role': 'assistant',
					'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
				},
				{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
			],
			tools=[
				{
					'type': 'web_search',
					'web_search': {
						'search_query': '帮我看看清华的升学率',
						'search_result': True,
						'enable': True,
					},
				}
			],
			extra_body={'temperature': 0.5, 'max_tokens': 50},
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_stream(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',  # 填写需要调用的模型名称
			stream=True,
			messages=[
				{
					'role': 'user',
					'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
				},
				{
					'role': 'assistant',
					'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
				},
				{'role': 'user', 'content': '智谱AI开放平台'},
				{
					'role': 'assistant',
					'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
				},
				{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
			],
			extra_body={'temperature': 0.5, 'max_tokens': 50},
			user_id='12345678',
		)
		for item in response:
			print(item)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


# Function to encode the image
def encode_image(image_path):
	import base64

	with open(image_path, 'rb') as image_file:
		return base64.b64encode(image_file.read()).decode('utf-8')


def test_completions_vis(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4v',  # 填写需要调用的模型名称
			extra_body={'temperature': 0.5, 'max_tokens': 50},
			messages=[
				{
					'role': 'user',
					'content': [
						{'type': 'text', 'text': '图里有什么'},
						{
							'type': 'image_url',
							'image_url': {
								'url': 'https://img1.baidu.com/it/u=1369931113,3388870256&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1703696400&t=f3028c7a1dca43a080aeb8239f09cc2f'
							},
						},
					],
				}
			],
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_vis_base64(test_file_path, logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		base64_image = encode_image(os.path.join(test_file_path, 'img/MetaGLM.png'))
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4v',  # 填写需要调用的模型名称
			extra_body={'temperature': 0.5, 'max_tokens': 50},
			messages=[
				{
					'role': 'user',
					'content': [
						{'type': 'text', 'text': '图里有什么'},
						# {
						#     "type": "image_url",
						#     "image_url": {
						#         "url": "https://img1.baidu.com/it/u=1369931113,3388870256&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1703696400&t=f3028c7a1dca43a080aeb8239f09cc2f"
						#     }
						# },
						{
							'type': 'image_url',
							'image_url': {'url': f'data:image/jpeg;base64,{base64_image}'},
						},
					],
				}
			],
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_async_completions(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.asyncCompletions.create(
			request_id=request_id,
			model='glm-4',  # 填写需要调用的模型名称
			messages=[
				{
					'role': 'user',
					'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
				},
				{
					'role': 'assistant',
					'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
				},
				{'role': 'user', 'content': '智谱AI开放平台'},
				{
					'role': 'assistant',
					'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
				},
				{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
			],
			tools=[
				{
					'type': 'web_search',
					'web_search': {
						'search_query': '帮我看看清华的升学率',
						'search_result': True,
					},
				}
			],
			extra_body={'temperature': 0.5, 'max_tokens': 50},
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_retrieve_completion_result(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		response = client.chat.asyncCompletions.retrieve_completion_result(
			id='1014908592669352541651237'
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_sensitive_word_check(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4',
			messages=[{'role': 'user', 'content': 'tell me a joke'}],
			top_p=1,
			temperature=0.9,
			max_tokens=2000,
			sensitive_word_check={'type': 'ALL', 'status': 'DISABLE'},
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_code_geex.py
================================================
import logging
import logging.config
import time

import zhipuai
from zhipuai import ZhipuAI


def test_code_geex(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='codegeex-4',
			messages=[
				{
					'role': 'system',
					'content': """你是一位智能编程助手,你叫CodeGeeX。你会为用户回答关于编程、代码、计算机方面的任何问题,并提供格式规范、可以执行、准确安全的代码,并在必要时提供详细的解释。
                    任务:请为输入代码提供格式规范的注释,包含多行注释和单行注释,请注意不要改动原始代码,只需要添加注释。
                    请用中文回答。""",
				},
				{'role': 'user', 'content': """写一个快速排序函数"""},
			],
			top_p=0.7,
			temperature=0.9,
			max_tokens=2000,
			stop=['<|endoftext|>', '<|user|>', '<|assistant|>', '<|observation|>'],
			extra={
				'target': {
					'path': '11111',
					'language': 'Python',
					'code_prefix': 'EventSource.Factory factory = EventSources.createFactory(OkHttpUtils.getInstance());',
					'code_suffix': 'TaskMonitorLocal taskMonitorLocal = getTaskMonitorLocal(algoMqReq);',
				},
				'contexts': [
					{
						'path': '/1/2',
						'code': 'if(!sensitiveUser){ZpTraceUtils.addAsyncAttribute(algoMqReq.getTaskOrderNo(), ApiTraceProperty.request_params.getCode(), modelSendMap);',
					}
				],
			},
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_code_geex_async(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.asyncCompletions.create(
			request_id=request_id,
			model='codegeex-4',
			messages=[
				{
					'role': 'system',
					'content': """你是一位智能编程助手,你叫CodeGeeX。你会为用户回答关于编程、代码、计算机方面的任何问题,并提供格式规范、可以执行、准确安全的代码,并在必要时提供详细的解释。
                    任务:请为输入代码提供格式规范的注释,包含多行注释和单行注释,请注意不要改动原始代码,只需要添加注释。
                    请用中文回答。""",
				},
				{'role': 'user', 'content': """写一个快速排序函数"""},
			],
			top_p=0.7,
			temperature=0.9,
			max_tokens=2000,
			stop=['<|endoftext|>', '<|user|>', '<|assistant|>', '<|observation|>'],
			extra={
				'target': {
					'path': '11111',
					'language': 'Python',
					'code_prefix': 'EventSource.Factory factory = EventSources.createFactory(OkHttpUtils.getInstance());',
					'code_suffix': 'TaskMonitorLocal taskMonitorLocal = getTaskMonitorLocal(algoMqReq);',
				},
				'contexts': [
					{
						'path': '/1/2',
						'code': 'if(!sensitiveUser){ZpTraceUtils.addAsyncAttribute(algoMqReq.getTaskOrderNo(), ApiTraceProperty.request_params.getCode(), modelSendMap);',
					}
				],
			},
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_geex_result(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		response = client.chat.asyncCompletions.retrieve_completion_result(
			id='1014908807577524653187108'
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_embedding.py
================================================
import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_embeddings(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore

	client = ZhipuAI()
	try:
		response = client.embeddings.create(
			model='embedding-2',  # 填写需要调用的模型名称
			input='你好',
			extra_body={'model_version': 'v1'},
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_embeddings_dimensions(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore

	client = ZhipuAI()
	try:
		response = client.embeddings.create(
			model='embedding-3',  # 填写需要调用的模型名称
			input='你好',
			dimensions=512,
			extra_body={'model_version': 'v1'},
		)
		assert response.data[0].object == 'embedding'
		assert len(response.data[0].embedding) == 512
		print(len(response.data[0].embedding))

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_emohaa.py
================================================
# -*- coding: utf-8 -*-

import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_completions_emohaa(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		response = client.chat.completions.create(
			model='emohaa',  # 填写需要调用的模型名称
			messages=[
				{
					'role': 'assistant',
					'content': '你好,我是Emohaa,很高兴见到你。请问有什么我可以帮忙的吗?',
				},
				{
					'role': 'user',
					'content': '今天我休息,决定去西安保密逛逛,心情很好地喷上了我最爱的烟熏木制香',
				},
				{
					'role': 'assistant',
					'content': '今天我休息,决定去西安保密逛逛,心情很好地喷上了我最爱的烟熏木制香',
				},
			],
			meta={
				'user_info': '30岁的男性软件工程师,兴趣包括阅读、徒步和编程',
				'bot_info': 'Emohaa是一款基于Hill助人理论的情感支持AI,拥有专业的心理咨询话术能力',
				'bot_name': 'Emohaa',
				'user_name': '陆星辰',
			},
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_file.py
================================================
from __future__ import annotations

import logging
import logging.config
import os

import pytest

import zhipuai
from zhipuai import ZhipuAI


@pytest.fixture(scope='class')
def test_server():
	class SharedData:
		client = ZhipuAI()
		file_id1 = None
		file_id2 = None

	return SharedData()


class TestZhipuAIFileServer:
	def test_logs(self, logging_conf):
		logging.config.dictConfig(logging_conf)  # type: ignore

	def test_files(self, test_server, test_file_path):
		try:
			result = test_server.client.files.create(
				file=open(os.path.join(test_file_path, 'demo.jsonl'), 'rb'),
				purpose='fine-tune',
			)
			print(result)
			test_server.file_id1 = result.id

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_files_validation(self, test_server, test_file_path):
		try:
			result = test_server.client.files.create(
				file=open(os.path.join(test_file_path, 'demo.jsonl'), 'rb'),
				purpose='fine-tune',
			)
			print(result)

			test_server.file_id2 = result.id

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_files_list(self, test_server):
		try:
			list = test_server.client.files.list()
			print(list)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_delete_files(self, test_server):
		try:
			delete1 = test_server.client.files.delete(file_id=test_server.file_id1)
			print(delete1)

			delete2 = test_server.client.files.delete(file_id=test_server.file_id2)
			print(delete2)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)


================================================
FILE: tests/integration_tests/test_file_parser.py
================================================
from __future__ import annotations

import logging
import logging.config
import os

import pytest

import zhipuai
from zhipuai import ZhipuAI


def test_file_parser_create(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.file_parser.create(file=open('hitsuyoushorui-cn.pdf', 'rb'), file_type='pdf', tool_type='zhipu_pro')
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)

def test_file_parser_content(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.file_parser.content(task_id="66e8f7ab884448c8b4190f251f6c2982-1", format_type="text")
		print(response.content.decode('utf-8'))

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)



================================================
FILE: tests/integration_tests/test_finetuning.py
================================================
import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_finetuning_create(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		job = client.fine_tuning.jobs.create(
			model='chatglm3-6b',
			training_file='file-20240428021923715-xjng4',  # 请填写已成功上传的文件id
			validation_file='file-20240428021923715-xjng4',  # 请填写已成功上传的文件id
			suffix='demo_test',
		)
		job_id = job.id
		print(job_id)
		fine_tuning_job = client.fine_tuning.jobs.retrieve(fine_tuning_job_id=job_id)
		print(fine_tuning_job)
		#     ftjob-20240418110039323-j8lh2

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_finetuning_retrieve(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		fine_tuning_job = client.fine_tuning.jobs.retrieve(
			fine_tuning_job_id='ftjob-20240429112551154-48vq7'
		)
		print(fine_tuning_job)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_finetuning_job_list(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		job_list = client.fine_tuning.jobs.list()

		print(job_list)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_finetuning_job_cancel(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		cancel = client.fine_tuning.jobs.cancel(fine_tuning_job_id='ftjob-20240429112551154-48vq7')

		print(cancel)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_finetuning_job_delete(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 请填写您自己的APIKey
	try:
		delete = client.fine_tuning.jobs.delete(fine_tuning_job_id='ftjob-20240126113041678-cs6s9')

		print(delete)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_model_check(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.chat.completions.create(
			model='chatglm3-6b-8572905046912426020-demo_test',  # 填写需要调用的模型名称
			messages=[
				{'role': 'user', 'content': '你是一位乐于助人,知识渊博的全能AI助手。'},
				{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
			],
			extra_body={'temperature': 0.5, 'max_tokens': 50},
		)
		print(response.choices[0].message)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_model_delete(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		delete = client.fine_tuning.models.delete(
			fine_tuned_model='chatglm3-6b-8572905046912426020-demo_test'
		)

		print(delete)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


if __name__ == '__main__':
	test_finetuning_create()


================================================
FILE: tests/integration_tests/test_images.py
================================================
import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_images(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.images.generations(
			model='cogview-3',  # 填写需要调用的模型名称
			prompt='一只可爱的小猫咪',
			extra_body={'user_id': '1222212'},
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_images_sensitive_word_check(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.images.generations(
			model='cogview-3',  # 填写需要调用的模型名称
			prompt='一只可爱的小猫咪',
			sensitive_word_check={'type': 'ALL', 'status': 'DISABLE'},
			extra_body={'user_id': '1222212'},
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_knowledge.py
================================================
from __future__ import annotations

import logging
import logging.config
import os

import pytest

import zhipuai
from zhipuai import ZhipuAI


@pytest.fixture(scope='class')
def test_server():
	class SharedData:
		client = ZhipuAI()
		test_knowledge_document_id = None
		test_knowledge_id = None

	return SharedData()


class TestZhipuAIKnowledgeServer:
	def test_logs(self, logging_conf):
		logging.config.dictConfig(logging_conf)  # type: ignore

	def test_knowledge_create(self, test_server):
		try:
			result = test_server.client.knowledge.create(
				embedding_id=1,
				name='test',
				description='测试',
				background='blue',
				icon='question',
			)
			print(result)
			test_server.test_knowledge_id = result.id

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_document_create(self, test_server, test_file_path):
		try:
			result = test_server.client.knowledge.document.create(
				file=open(os.path.join(test_file_path, 'file.xlsx'), 'rb'),
				purpose='retrieval',
				knowledge_id=test_server.test_knowledge_id,
				sentence_size=202,
			)
			print(result)
			test_server.test_knowledge_document_id = result.successInfos[0].documentId

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_modify(self, test_server):
		try:
			result = test_server.client.knowledge.modify(
				knowledge_id=test_server.test_knowledge_id,
				embedding_id=1,
				name='测试1',
				background='red',
				icon='book',
			)
			print(result)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_query(self, test_server):
		try:
			result = test_server.client.knowledge.query()
			print(result)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_used(self, test_server):
		try:
			result = test_server.client.knowledge.used()
			print(result)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_document_retrieve(self, test_server, test_file_path):
		try:
			result = test_server.client.knowledge.document.retrieve(
				test_server.test_knowledge_document_id
			)
			print(result)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_document_edit(self, test_server):
		try:
			result = test_server.client.knowledge.document.edit(
				document_id=test_server.test_knowledge_document_id,
				knowledge_type='1',
				sentence_size=204,
			)
			print(result)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_document_list(self, test_server):
		try:
			result = test_server.client.knowledge.document.list(
				test_server.test_knowledge_id, purpose='retrieval'
			)
			print(result)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_document_delete(self, test_server):
		try:
			file1 = test_server.client.knowledge.document.delete(
				test_server.test_knowledge_document_id
			)
			print(file1)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)

	def test_knowledge_delete(self, test_server):
		try:
			result = test_server.client.knowledge.delete(knowledge_id=test_server.test_knowledge_id)
			print(result)

		except zhipuai.core._errors.APIRequestFailedError as err:
			print(err)
		except zhipuai.core._errors.APIInternalError as err:
			print(err)
		except zhipuai.core._errors.APIStatusError as err:
			print(err)


================================================
FILE: tests/integration_tests/test_moderation.py
================================================
import logging
import logging.config
import time

import zhipuai
from zhipuai import ZhipuAI


def test_completions_temp0(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI(disable_token_cache=False)  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.moderations.create(
			model='moderations', input={'type': 'text', 'text': 'hello world '}
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_tools.py
================================================
import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_tools(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.tools.web_search(
			model='web-search-pro',
			messages=[
				{
					'content': '你好',
					'role': 'user',
				}
			],
			stream=False,
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_tools_stream(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.tools.web_search(
			model='web-search-pro',
			messages=[
				{
					'content': '你好',
					'role': 'user',
				}
			],
			stream=True,
		)
		for item in response:
			print(item)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_transcriptions.py
================================================
import logging
import logging.config
from pathlib import Path

import zhipuai
from zhipuai import ZhipuAI


def test_transcriptions(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		with open(Path(__file__).parent / 'asr1.wav', 'rb') as audio_file:
			transcriptResponse = client.audio.transcriptions.create(
				model='glm-asr', file=audio_file, stream=False
			)
			print(transcriptResponse)
	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_transcriptions_stream(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		with open(Path(__file__).parent / 'asr1.wav', 'rb') as audio_file:
			transcriptResponse = client.audio.transcriptions.create(
				model='glm-asr', file=audio_file, stream=True
			)
			for item in transcriptResponse:
				print(item)
	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_videos.py
================================================
import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_videos(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.videos.generations(
			model='cogvideox', prompt='一个开船的人', user_id='1212222'
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_videos_sensitive_word_check(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.videos.generations(
			model='cogvideo',
			prompt='一个开船的人',
			sensitive_word_check={'type': 'ALL', 'status': 'DISABLE'},
			user_id='1212222',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_videos_image_url(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.videos.generations(
			model='cogvideo',
			image_url='https://cdn.bigmodel.cn/static/platform/images/solutions/car/empowerment/icon-metric.png',
			prompt='一些相信光的人,举着奥特曼',
			user_id='12222211',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_retrieve_videos_result(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.videos.retrieve_videos_result(id='1014908869548405238276203')
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_vlm_thinking.py
================================================
import logging
import logging.config
import time

import zhipuai
from zhipuai import ZhipuAI


def test_completions_vlm_thinking(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4.1v-thinking-flash',  # 填写需要调用的模型名称
			messages=[
				{
					'role': 'user',
					'content': [
						{'type': 'text', 'text': '图里有什么'},
						{
							'type': 'image_url',
							'image_url': {
								'url': 'https://img1.baidu.com/it/u=1369931113,3388870256&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1703696400&t=f3028c7a1dca43a080aeb8239f09cc2f'
							},
						},
					],
				}
			],
			temperature=0.5,
			max_tokens=1024,
			user_id='12345678',
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


def test_completions_vlm_thinking_stream(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		# 生成request_id
		request_id = time.time()
		print(f'request_id:{request_id}')
		response = client.chat.completions.create(
			request_id=request_id,
			model='glm-4.1v-thinking-flash',  # 填写需要调用的模型名称
			messages=[
				{
					'role': 'user',
					'content': [
						{'type': 'text', 'text': '图里有什么'},
						{
							'type': 'image_url',
							'image_url': {
								'url': 'https://img1.baidu.com/it/u=1369931113,3388870256&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1703696400&t=f3028c7a1dca43a080aeb8239f09cc2f'
							},
						},
					],
				}
			],
			temperature=0.5,
			max_tokens=1024,
			user_id='12345678',
			stream=True,
		)
		for item in response:
			print(item)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/integration_tests/test_web_search.py
================================================
import logging
import logging.config

import zhipuai
from zhipuai import ZhipuAI


def test_web_search(logging_conf):
	logging.config.dictConfig(logging_conf)  # type: ignore
	client = ZhipuAI()  # 填写您自己的APIKey
	try:
		response = client.web_search.web_search(
			search_engine='search-std',
			search_query='2025特朗普向中国加征了多少关税',
			count=50,
			search_domain_filter='finance.sina.com.cn',
			search_recency_filter='oneYear',
			content_size='high',
			search_intent=True,
		)
		print(response)

	except zhipuai.core._errors.APIRequestFailedError as err:
		print(err)
	except zhipuai.core._errors.APIInternalError as err:
		print(err)
	except zhipuai.core._errors.APIStatusError as err:
		print(err)


================================================
FILE: tests/unit_tests/batchinput.jsonl
================================================
{"custom_id": "request-1", "method": "POST", "url": "/v4/chat/completions", "body": {"model": "glm-4", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}

================================================
FILE: tests/unit_tests/maybe/test_maybe_transform.py
================================================
# -*- coding: utf-8 -*-
from zhipuai.core import maybe_transform
from zhipuai.types import batch_create_params


def test_response_joblist_model_cast() -> None:
	params = maybe_transform(
		{
			'completion_window': '/v1/chat/completions',
			'endpoint': None,
			'metadata': {'key': 'value'},
		},
		batch_create_params.BatchCreateParams,
	)
	assert isinstance(params, dict)


================================================
FILE: tests/unit_tests/response_model/__init__.py
================================================


================================================
FILE: tests/unit_tests/response_model/test_response.py
================================================
# -*- coding: utf-8 -*-
from typing import Type

import httpx
import pytest

from zhipuai.core import BaseModel, HttpClient
from zhipuai.core._base_type import ResponseT
from zhipuai.core._request_opt import FinalRequestOptions
from zhipuai.core._response import APIResponse
from zhipuai.types.chat.async_chat_completion import (
	AsyncCompletion,
	AsyncTaskStatus,
)
from zhipuai.types.chat.chat_completion import (
	Completion,
)
from zhipuai.types.chat.chat_completion import (
	CompletionChoice as ChatCompletionChoice,
)
from zhipuai.types.chat.chat_completion import (
	CompletionMessageToolCall as ChatCompletionMessageToolCall,
)
from zhipuai.types.chat.chat_completion import (
	CompletionUsage as ChatCompletionUsage,
)
from zhipuai.types.embeddings import Embedding, EmbeddingsResponded
from zhipuai.types.files.file_object import FileObject, ListOfFileObject
from zhipuai.types.fine_tuning import FineTuningJobEvent
from zhipuai.types.fine_tuning.fine_tuning_job import Error, FineTuningJob
from zhipuai.types.fine_tuning.fine_tuning_job import (
	Hyperparameters as FineTuningHyperparameters,
)
from zhipuai.types.fine_tuning.fine_tuning_job_event import JobEvent, Metric
from zhipuai.types.fine_tuning.models import FineTunedModelsStatus
from zhipuai.types.image import GeneratedImage, ImagesResponded


class MockClient:
	_strict_response_validation: bool = False

	def _process_response_data(
		self,
		*,
		data: object,
		cast_type: Type[ResponseT],
		response: httpx.Response,
	) -> ResponseT:
		pass


@pytest.mark.parametrize(
	'R',
	[
		AsyncTaskStatus,
		AsyncCompletion,
		Completion,
	],
)
def test_response_chat_model_cast(R: Type[BaseModel]) -> None:
	MockClient._process_response_data = HttpClient._process_response_data
	response = httpx.Response(
		status_code=200,
		content="""{
    "id": "completion123",
    "request_id": "request456",
    "model": "model-name",
    "task_status": "completed",
    "choices": [
      {
        "index": 0,
        "finish_reason": "normal",
        "message": {
          "content": "This is the completion content.",
          "role": "assistant",
          "tool_calls": [
            {
              "id": "toolcall789",
              "function": {
                "arguments": "arg1, arg2",
                "name": "functionName"
              },
              "type": "function_call"
            }
          ]
        }
      }
    ],
    "usage": {
      "prompt_tokens": 10,
      "completion_tokens": 15,
      "total_tokens": 25
    }
  }""",
	)

	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=response,
		cast_type=R,
		client=MockClient(),
		stream=False,
		stream_cls=None,
		options=opts,
	)
	model = http_response.parse()

	if R == AsyncTaskStatus:
		assert R == model.__class__
		assert isinstance(model, AsyncTaskStatus)
		assert model.id == 'completion123'
		assert model.request_id == 'request456'
		assert model.model == 'model-name'
		assert model.task_status == 'completed'

	elif R == AsyncCompletion:
		assert R == model.__class__
		assert isinstance(model, AsyncCompletion)
		assert model.id == 'completion123'
		assert model.request_id == 'request456'
		assert model.model == 'model-name'
		assert model.task_status == 'completed'
		assert isinstance(model.choices, list)
		assert model.choices[0].index == 0
		assert model.choices[0].finish_reason == 'normal'
		assert (
			model.choices[0].message.content
			== 'This is the completion content.'
		)
		assert model.choices[0].message.role == 'assistant'
		assert isinstance(model.choices[0].message.tool_calls, list)
		assert model.choices[0].message.tool_calls[0].id == 'toolcall789'
		assert (
			model.choices[0].message.tool_calls[0].function.arguments
			== 'arg1, arg2'
		)
		assert (
			model.choices[0].message.tool_calls[0].function.name
			== 'functionName'
		)
		assert model.choices[0].message.tool_calls[0].type == 'function_call'
		assert model.usage.prompt_tokens == 10
		assert model.usage.completion_tokens == 15
		assert model.usage.total_tokens == 25
	elif R == Completion:
		assert R == model.__class__
		assert isinstance(model, Completion)
		assert model.id == 'completion123'
		assert model.request_id == 'request456'
		assert model.model == 'model-name'
		assert model.created == None
		assert isinstance(model.choices, list)
		assert isinstance(model.choices[0], ChatCompletionChoice)
		assert model.choices[0].index == 0
		assert model.choices[0].finish_reason == 'normal'
		assert (
			model.choices[0].message.content
			== 'This is the completion content.'
		)
		assert model.choices[0].message.role == 'assistant'
		assert isinstance(model.choices[0].message.tool_calls, list)
		assert isinstance(
			model.choices[0].message.tool_calls[0],
			ChatCompletionMessageToolCall,
		)
		assert model.choices[0].message.tool_calls[0].id == 'toolcall789'
		assert (
			model.choices[0].message.tool_calls[0].function.arguments
			== 'arg1, arg2'
		)
		assert (
			model.choices[0].message.tool_calls[0].function.name
			== 'functionName'
		)
		assert model.choices[0].message.tool_calls[0].type == 'function_call'
		assert isinstance(model.usage, ChatCompletionUsage)
		assert model.usage.prompt_tokens == 10
		assert model.usage.completion_tokens == 15
		assert model.usage.total_tokens == 25

	else:
		assert False, f'Unexpected model type: {R}'


@pytest.mark.parametrize(
	'R',
	[
		FineTunedModelsStatus,
	],
)
def test_response_finetuned_model_model_cast(R: Type[BaseModel]) -> None:
	MockClient._process_response_data = HttpClient._process_response_data
	response = httpx.Response(
		status_code=200,
		content="""{
    "request_id": "12345",
    "model_name": "my-fine-tuned-model",
    "delete_status": "deleted"
  }""",
	)

	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=response,
		cast_type=R,
		client=MockClient(),
		stream=False,
		stream_cls=None,
		options=opts,
	)
	model = http_response.parse()

	assert R == model.__class__
	assert isinstance(model, FineTunedModelsStatus)
	assert model.request_id == '12345'
	assert model.model_name == 'my-fine-tuned-model'
	assert model.delete_status == 'deleted'


@pytest.mark.parametrize(
	'R',
	[
		FineTuningJob,
	],
)
def test_response_job_model_cast(R: Type[BaseModel]) -> None:
	MockClient._process_response_data = HttpClient._process_response_data
	response = httpx.Response(
		status_code=200,
		content=""" {
    "id": "job123",
    "request_id": "req456",
    "created_at": 1617181723,
    "error": {
      "code": "404",
      "message": "Not Found",
      "param": "model_id"
    },
    "fine_tuned_model": "ft_model_1",
    "finished_at": 1617182000,
    "hyperparameters": {
      "n_epochs": 10
    },
    "model": "base_model",
    "object": "fine_tuning_job",
    "result_files": [
      "result1.txt",
      "result2.json"
    ],
    "status": "completed",
    "trained_tokens": 1000000,
    "training_file": "training_data.csv",
    "validation_file": "validation_data.csv"
  }""",
	)

	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=response,
		cast_type=R,
		client=MockClient(),
		stream=False,
		stream_cls=None,
		options=opts,
	)
	model = http_response.parse()

	assert R == model.__class__
	assert isinstance(model, FineTuningJob)
	assert model.id == 'job123'
	assert model.request_id == 'req456'
	assert model.created_at == 1617181723
	assert isinstance(model.error, Error)
	assert model.error.code == '404'
	assert model.error.message == 'Not Found'
	assert model.error.param == 'model_id'
	assert model.fine_tuned_model == 'ft_model_1'
	assert model.finished_at == 1617182000
	assert isinstance(model.hyperparameters, FineTuningHyperparameters)
	assert model.hyperparameters.n_epochs == 10
	assert model.model == 'base_model'
	assert model.object == 'fine_tuning_job'
	assert model.result_files == ['result1.txt', 'result2.json']
	assert model.status == 'completed'
	assert model.trained_tokens == 1000000
	assert model.training_file == 'training_data.csv'
	assert model.validation_file == 'validation_data.csv'


@pytest.mark.parametrize(
	'R',
	[
		FineTuningJobEvent,
	],
)
def test_response_joblist_model_cast(R: Type[BaseModel]) -> None:
	MockClient._process_response_data = HttpClient._process_response_data
	response = httpx.Response(
		status_code=200,
		content="""{
    "object": "fine_tuning_job",
    "data": [
      {
        "object": "job_event",
        "id": "event123",
        "type": "training",
        "created_at": 1617181723,
        "level": "info",
        "message": "Training has started.",
        "data": {
          "epoch": 1,
          "current_steps": 100,
          "total_steps": 1000,
          "elapsed_time": "00:10:00",
          "remaining_time": "05:20:00",
          "trained_tokens": 500000,
          "loss": 0.05,
          "eval_loss": 0.03,
          "acc": 0.9,
          "eval_acc": 0.95,
          "learning_rate": 0.001
        }
      }
    ],
    "has_more": false
  }""",
	)

	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=response,
		cast_type=R,
		client=MockClient(),
		stream=False,
		stream_cls=None,
		options=opts,
	)
	model = http_response.parse()

	assert R == model.__class__
	assert isinstance(model, FineTuningJobEvent)
	assert isinstance(model.data, list)
	assert isinstance(model.data[0], JobEvent)
	assert model.data[0].object == 'job_event'
	assert model.data[0].id == 'event123'
	assert model.data[0].type == 'training'
	assert model.data[0].created_at == 1617181723
	assert model.data[0].level == 'info'
	assert model.data[0].message == 'Training has started.'
	assert isinstance(model.data[0].data, Metric)
	assert model.data[0].data.epoch == 1
	assert model.data[0].data.current_steps == 100
	assert model.data[0].data.total_steps == 1000
	assert model.data[0].data.elapsed_time == '00:10:00'
	assert model.data[0].data.remaining_time == '05:20:00'
	assert model.data[0].data.trained_tokens == 500000
	assert model.data[0].data.loss == 0.05
	assert model.data[0].data.eval_loss == 0.03
	assert model.data[0].data.acc == 0.9
	assert model.data[0].data.eval_acc == 0.95
	assert model.data[0].data.learning_rate == 0.001
	assert model.has_more == False


@pytest.mark.parametrize(
	'R',
	[EmbeddingsResponded],
)
def test_response_embedding_model_cast(R: Type[BaseModel]) -> None:
	MockClient._process_response_data = HttpClient._process_response_data
	response = httpx.Response(
		status_code=200,
		content="""{
    "object": "embeddings",
    "data": [
      {
        "object": "embedding",
        "index": 1,
        "embedding": [0.1, 0.2] 
      }
    ],
    "model": "some-model-name",
    "usage": {
      "prompt_tokens": 20,
      "completion_tokens": 30,
      "total_tokens": 50
    }
  }""",
	)

	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=response,
		cast_type=R,
		client=MockClient(),
		stream=False,
		stream_cls=None,
		options=opts,
	)
	model = http_response.parse()

	assert R == model.__class__
	assert isinstance(model, EmbeddingsResponded)
	assert isinstance(model.data, list)
	assert isinstance(model.data[0], Embedding)
	assert model.data[0].object == 'embedding'
	assert model.data[0].index == 1
	assert model.data[0].embedding == [0.1, 0.2]
	assert model.object == 'embeddings'
	assert model.model == 'some-model-name'
	assert model.usage.prompt_tokens == 20
	assert model.usage.completion_tokens == 30
	assert model.usage.total_tokens == 50


@pytest.mark.parametrize(
	'R',
	[
		FileObject,
	],
)
def test_response_file_list_model_cast(R: Type[BaseModel]) -> None:
	MockClient._process_response_data = HttpClient._process_response_data
	response = httpx.Response(
		status_code=200,
		content=""" {
        "id": "12345",
        "bytes": 1024,
        "created_at": 1617181723,
        "filename": "example.txt",
        "object": "file",
        "purpose": "example purpose",
        "status": "uploaded",
        "status_details": "File uploaded successfully"
      }""",
	)

	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=response,
		cast_type=R,
		client=MockClient(),
		stream=False,
		stream_cls=None,
		options=opts,
	)
	model = http_response.parse()

	assert R == model.__class__
	assert isinstance(model, FileObject)
	assert model.id == '12345'
	assert model.bytes == 1024
	assert model.created_at == 1617181723
	assert model.filename == 'example.txt'
	assert model.object == 'file'
	assert model.purpose == 'example purpose'
	assert model.status == 'uploaded'
	assert model.status_details == 'File uploaded successfully'


@pytest.mark.parametrize(
	'R',
	[
		ListOfFileObject,
	],
)
def test_response_file_list_model_cast(R: Type[BaseModel]) -> None:
	MockClient._process_response_data = HttpClient._process_response_data
	response = httpx.Response(
		status_code=200,
		content="""{
    "object": "list",
    "data": [
      {
        "id": "12345",
        "bytes": 1024,
        "created_at": 1617181723,
        "filename": "example.txt",
        "object": "file",
        "purpose": "example purpose",
        "status": "uploaded",
        "status_details": "File uploaded successfully"
      }
    ],
    "has_more": true
  }""",
	)

	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=response,
		cast_type=R,
		client=MockClient(),
		stream=False,
		stream_cls=None,
		options=opts,
	)
	model = http_response.parse()

	assert R == model.__class__
	assert isinstance(model.data, list)
	assert isinstance(model.data[0], FileObject)
	assert model.data[0].id == '12345'
	assert model.data[0].bytes == 1024
	assert model.data[0].created_at == 1617181723
	assert model.data[0].filename == 'example.txt'
	assert model.data[0].object == 'file'
	assert model.data[0].purpose == 'example purpose'
	assert model.data[0].status == 'uploaded'
	assert model.data[0].status_details == 'File uploaded successfully'
	assert model.has_more == True


@pytest.mark.parametrize('R', [ImagesResponded])
def test_response_image_model_cast(R: Type[BaseModel]) -> None:
	MockClient._process_response_data = HttpClient._process_response_data
	response = httpx.Response(
		status_code=200,
		content="""{
"created": 1234567890,
"data": [
  {
    "b64_json": "base64_encoded_string",
    "url": "http://example.com/image.png",
    "revised_prompt": "Revised prompt text"
  }
]
}""",
	)

	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=response,
		cast_type=R,
		client=MockClient(),
		stream=False,
		stream_cls=None,
		options=opts,
	)
	model = http_response.parse()

	assert R == model.__class__
	assert isinstance(model.data, list)
	assert isinstance(model.data[0], GeneratedImage)
	assert model.data[0].b64_json == 'base64_encoded_string'


================================================
FILE: tests/unit_tests/sse_client/__init__.py
================================================


================================================
FILE: tests/unit_tests/sse_client/test_stream.py
================================================
# -*- coding: utf-8 -*-
from typing import Iterable, Type, cast

import httpx

from zhipuai.core import HttpClient, StreamResponse, get_args
from zhipuai.core._base_type import ResponseT
from zhipuai.types.chat.chat_completion_chunk import ChatCompletionChunk


class MockClient:
	_strict_response_validation: bool = False

	def _process_response_data(
		self,
		*,
		data: object,
		cast_type: Type[ResponseT],
		response: httpx.Response,
	) -> ResponseT:
		pass


def test_stream_cls_chunk() -> None:
	MockClient._process_response_data = HttpClient._process_response_data

	def body() -> Iterable[bytes]:
		yield b'data: {"id":"8635243129834723621","created":1715329207,"model":\
            "glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"1"}}]}\n\n'
		yield b'data: {"id":"8635243129834723621","created":1715329207,"model":\
            "glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"2"}}]}\n\n'

	_stream_cls = StreamResponse[ChatCompletionChunk]
	http_response = httpx.Response(status_code=200, content=body())

	stream_cls = _stream_cls(
		cast_type=cast(type, get_args(_stream_cls)[0]),
		response=http_response,
		client=MockClient(),
	)
	chat_completion_chunk1 = next(stream_cls)

	assert chat_completion_chunk1.choices[0].delta.content == '1'
	assert chat_completion_chunk1.choices[0].delta.role == 'assistant'
	assert chat_completion_chunk1.choices[0].index == 0
	assert chat_completion_chunk1.model == 'glm-4'
	chat_completion_chunk2 = next(stream_cls)
	assert chat_completion_chunk2.choices[0].delta.content == '2'
	assert chat_completion_chunk2.choices[0].delta.role == 'assistant'
	assert chat_completion_chunk2.choices[0].index == 0
	assert chat_completion_chunk2.model == 'glm-4'


================================================
FILE: tests/unit_tests/test_agents.py
================================================
def test_agents_completion_error_field():
    from zhipuai.types.agents.agents_completion import AgentsCompletion, AgentsError, AgentsCompletionChoice, AgentsCompletionMessage, AgentsCompletionUsage

    # 构造一个 AgentsError
    error = AgentsError(code="404", message="Not Found")

    # 构造一个完整的 AgentsCompletion
    completion = AgentsCompletion(
        agent_id="test_agent",
        conversation_id="conv_1",
        status="failed",
        choices=[
            AgentsCompletionChoice(
                index=0,
                finish_reason="error",
                message=AgentsCompletionMessage(content="error", role="system")
            )
        ],
        request_id="req_1",
        id="id_1",
        usage=AgentsCompletionUsage(prompt_tokens=1, completion_tokens=1, total_tokens=2),
        error=error
    )

    # 检查 error 字段是否为 AgentsError 实例
    assert isinstance(completion.error, AgentsError)
    assert completion.error.code == "404"
    assert completion.error.message == "Not Found"

    # 检查序列化
    as_dict = completion.model_dump()
    assert as_dict["error"]["code"] == "404"
    assert as_dict["error"]["message"] == "Not Found"
    print("test_agents_completion_error_field passed.")

================================================
FILE: tests/unit_tests/test_audio.py
================================================
def test_audio_error_field():
    from zhipuai.types.audio.audio_speech_chunk import AudioSpeechChunk, AudioError, AudioSpeechChoice, AudioSpeechDelta

    # 构造一个 AudioError
    error = AudioError(code="500", message="Internal Error")

    # 构造一个完整的 AudioSpeechChunk
    chunk = AudioSpeechChunk(
        choices=[
            AudioSpeechChoice(
                delta=AudioSpeechDelta(content="audio", role="system"),
                finish_reason="error",
                index=0
            )
        ],
        request_id="req_2",
        created=123456,
        error=error
    )

    # 检查 error 字段是否为 AudioError 实例
    assert isinstance(chunk.error, AudioError)
    assert chunk.error.code == "500"
    assert chunk.error.message == "Internal Error"

    # 检查序列化
    as_dict = chunk.model_dump()
    assert as_dict["error"]["code"] == "500"
    assert as_dict["error"]["message"] == "Internal Error"
    print("test_audio_error_field passed.")


================================================
FILE: tests/unit_tests/test_jwt.py
================================================
import jwt
import pytest

from zhipuai.core._jwt_token import generate_token


def test_token() -> None:
	# 生成token
	token = generate_token('12345678.abcdefg')
	assert token is not None

	# 解析token
	payload = jwt.decode(
		token,
		'abcdefg',
		algorithms='HS256',
		options={'verify_signature': False},
	)
	assert payload is not None
	assert payload.get('api_key') == '12345678'

	apikey = 'invalid_api_key'
	with pytest.raises(Exception):
		generate_token(apikey)


================================================
FILE: tests/unit_tests/test_request_opt.py
================================================
import pytest

from zhipuai.core._request_opt import FinalRequestOptions, NotGiven


# Test Initialization and Default Values
def test_initialization():
	params = FinalRequestOptions.construct(
		method='GET', url='http://example.com'
	)
	assert isinstance(params.max_retries, NotGiven)
	assert isinstance(params.timeout, NotGiven)
	assert isinstance(params.headers, NotGiven)
	assert params.json_data is None


# Test get_max_retries Method
@pytest.mark.parametrize(
	'max_retries_input, expected',
	[
		(NotGiven(), 5),  # Default case
		(3, 3),  # Specific number
	],
)
def test_get_max_retries(max_retries_input, expected):
	params = FinalRequestOptions.construct(
		method='GET', url='http://example.com', max_retries=max_retries_input
	)
	assert params.get_max_retries(5) == expected


# Test construct Method
def test_construct():
	input_data = {
		'max_retries': 3,
		'timeout': 10.0,
		'headers': {'Content-Type': 'application/json'},
	}
	params = FinalRequestOptions.construct(**input_data)
	assert params.max_retries == input_data['max_retries']
	assert params.timeout == input_data['timeout']
	assert params.headers == input_data['headers']


================================================
FILE: tests/unit_tests/test_response.py
================================================
import httpx
from httpx import URL, ByteStream, Headers, Request, Response
from typing_extensions import Dict, Type

from zhipuai.core import StreamResponse
from zhipuai.core._base_type import ResponseT
from zhipuai.core._http_client import HttpClient
from zhipuai.core._request_opt import FinalRequestOptions
from zhipuai.core._response import APIResponse


# Mock objects for HttpClient and StreamResponse if necessary
class MockHttpClient:
	_strict_response_validation: bool = False

	# Implement necessary mock methods or attributes
	def _process_response_data(
		self,
		*,
		data: object,
		cast_type: Type[ResponseT],
		response: httpx.Response,
	) -> ResponseT:
		return data


class MockStreamResponse(StreamResponse[ResponseT]):
	# Implement necessary mock methods or attributes
	def __init__(
		self,
		*,
		cast_type: Type[ResponseT],
		response: httpx.Response,
		client: HttpClient,
	) -> None:
		super().__init__(cast_type=cast_type, response=response, client=client)
		self.response = response
		self._cast_type = cast_type
		# self._data_process_func = client._process_response_data
		# self._strem_chunks = self.__stream__()

	def __iter__(self):
		for item in self.response.iter_lines():
			yield item


# Test Initialization
def test_http_response_initialization():
	raw_response = Response(200)
	opts = FinalRequestOptions.construct(method='get', url='path')
	http_response = APIResponse(
		raw=raw_response,
		cast_type=str,
		client=MockHttpClient(),
		stream=False,
		options=opts,
	)
	assert http_response.http_response == raw_response


# Test parse Method
def test_parse_method():
	raw_response = Response(
		200,
		headers=Headers({'content-type': 'application/json'}),
		content=b'{"key": "value"}',
	)
	opts = FinalRequestOptions.construct(method='get', url='path')

	http_response = APIResponse(
		raw=raw_response,
		cast_type=Dict[str, object],
		client=MockHttpClient(),
		stream=False,
		options=opts,
	)
	parsed_data = http_response.parse()
	assert parsed_data == {'key': 'value'}
	http_response = APIResponse(
		raw=raw_response,
		cast_type=str,
		client=MockHttpClient(),
		stream=False,
		options=opts,
	)
	parsed_data = http_response.parse()
	assert parsed_data == '{"key": "value"}'

	raw_response = Response(
		200,
		content=b'{"key": "value"}',
		stream=ByteStream(b'{"key": "value"}\n"foo"\n"boo"\n'),
	)
	http_response = APIResponse(
		raw=raw_response,
		cast_type=str,
		client=MockHttpClient(),
		stream=True,
		options=opts,
		stream_cls=MockStreamResponse[str],
	)
	parsed_data = http_response.parse()
	excepted_data = ['{"key": "value"}', '"foo"', '"boo"']
	data = [chunk.strip() for chunk in parsed_data]
	assert data == excepted_data


# Test properties
def test_properties():
	opts = FinalRequestOptions.construct(method='get', url='path')
	headers = Headers({'content-type': 'application/json'})
	request = Request(method='GET', url='http://example.com')
	raw_response = Response(200, headers=headers, request=request)
	http_response = APIResponse(
		raw=raw_response,
		cast_type=str,
		client=MockHttpClient(),
		stream=False,
		options=opts,
	)

	assert http_response.headers == headers
	assert http_response.http_request == request
	assert http_response.status_code == 200
	assert http_response.url == URL('http://example.com')
	assert http_response.method == 'GET'


================================================
FILE: tests/unit_tests/test_sdk_import.py
================================================
def test_sdk_import_unit():
	import zhipuai

	print(zhipuai.__version__)


def test_os_import_unit():
	import os

	print(os)


def test_sdk_import():
	from zhipuai import ZhipuAI

	client = ZhipuAI(api_key='empty')  # 请填写您自己的APIKey

	if client is not None:
		print('SDK导入成功')
	else:
		print('SDK导入失败')


================================================
FILE: tests/unit_tests/test_streaming.py
================================================
from typing import Iterator

import pytest

from zhipuai.core._sse_client import SSELineParser


def test_basic() -> None:
	def body() -> Iterator[str]:
		yield 'event: completion'
		yield 'data: {"foo":true}'
		yield ''

	it = SSELineParser().iter_lines(body())
	sse = next(it)
	assert sse.event == 'completion'
	assert sse.json_data() == {'foo': True}

	with pytest.raises(StopIteration):
		next(it)


def test_data_missing_event() -> None:
	def body() -> Iterator[str]:
		yield 'data: {"foo":true}'
		yield ''

	it = SSELineParser().iter_lines(body())
	sse = next(it)
	assert sse.event is None
	assert sse.json_data() == {'foo': True}

	with pytest.raises(StopIteration):
		next(it)


def test_event_missing_data() -> None:
	def body() -> Iterator[str]:
		yield 'event: ping'
		yield ''

	it = SSELineParser().iter_lines(body())
	sse = next(it)
	assert sse.event == 'ping'
	assert sse.data == ''

	with pytest.raises(StopIteration):
		next(it)


def test_multiple_events() -> None:
	def body() -> Iterator[str]:
		yield 'event: ping'
		yield ''
		yield 'event: completion'
		yield ''

	it = SSELineParser().iter_lines(body())

	sse = next(it)
	assert sse.event == 'ping'
	assert sse.data == ''

	sse = next(it)
	assert sse.event == 'completion'
	assert sse.data == ''

	with pytest.raises(StopIteration):
		next(it)


def test_multiple_events_with_data() -> None:
	def body() -> Iterator[str]:
		yield 'event: ping'
		yield 'data: {"foo":true}'
		yield ''
		yield 'event: completion'
		yield 'data: {"bar":false}'
		yield ''

	it = SSELineParser().iter_lines(body())

	sse = next(it)
	assert sse.event == 'ping'
	assert sse.json_data() == {'foo': True}

	sse = next(it)
	assert sse.event == 'completion'
	assert sse.json_data() == {'bar': False}

	with pytest.raises(StopIteration):
		next(it)


================================================
FILE: zhipuai/__init__.py
================================================

from ._client import ZhipuAI

from .core import (
    ZhipuAIError,
    APIStatusError,
    APIRequestFailedError,
    APIAuthenticationError,
    APIReachLimitError,
    APIInternalError,
    APIServerFlowExceedError,
    APIResponseError,
    APIResponseValidationError,
    APIConnectionError,
    APITimeoutError,
)

from .__version__ import __version__


================================================
FILE: zhipuai/__version__.py
================================================
__version__ = 'v2.1.5.20250725'

================================================
FILE: zhipuai/_client.py
================================================
from __future__ import annotations

from typing import Union, Mapping

from typing_extensions import override

from .core import _jwt_token
from .core import ZhipuAIError
from .core import HttpClient, ZHIPUAI_DEFAULT_MAX_RETRIES
from .core import NotGiven, NOT_GIVEN
from . import api_resource
import os
import httpx
from httpx import Timeout


class ZhipuAI(HttpClient):
    chat: api_resource.chat.Chat
    api_key: str
    _disable_token_cache: bool = True
    source_channel: str

    def __init__(
            self,
            *,
            api_key: str | None = None,
            base_url: str | httpx.URL | None = None,
            timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
            max_retries: int = ZHIPUAI_DEFAULT_MAX_RETRIES,
            http_client: httpx.Client | None = None,
            custom_headers: Mapping[str, str] | None = None,
            disable_token_cache: bool = True,
            _strict_response_validation: bool = False,
            source_channel: str | None = None
    ) -> None:
        if api_key is None:
            api_key = os.environ.get("ZHIPUAI_API_KEY")
        if api_key is None:
            raise ZhipuAIError("未提供api_key,请通过参数或环境变量提供")
        self.api_key = api_key
        self.source_channel = source_channel
        self._disable_token_cache = disable_token_cache

        if base_url is None:
            base_url = os.environ.get("ZHIPUAI_BASE_URL")
        if base_url is None:
            base_url = f"https://open.bigmodel.cn/api/paas/v4"
        from .__version__ import __version__
        super().__init__(
            version=__version__,
            base_url=base_url,
            max_retries=max_retries,
            timeout=timeout,
            custom_httpx_client=http_client,
            custom_headers=custom_headers,
            _strict_response_validation=_strict_response_validation,
        )
        self.chat = api_resource.chat.Chat(self)
        self.images = api_resource.images.Images(self)
        self.embeddings = api_resource.embeddings.Embeddings(self)
        self.files = api_resource.files.Files(self)
        self.fine_tuning = api_resource.fine_tuning.FineTuning(self)
        self.batches = api_resource.Batches(self)
        self.knowledge = api_resource.Knowledge(self)
        self.tools = api_resource.Tools(self)
        self.videos = api_resource.Videos(self)
        self.assistant = api_resource.Assistant(self)
        self.web_search = api_resource.WebSearchApi(self)
        self.audio = api_resource.audio.Audio(self)
        self.moderations = api_resource.moderation.Moderations(self)
        self.agents = api_resource.agents.Agents(self)
        self.file_parser = api_resource.file_parser.FileParser(self)

    @property
    @override
    def auth_headers(self) -> dict[str, str]:
        api_key = self.api_key
        source_channel = self.source_channel or "python-sdk"
        if self._disable_token_cache:
            return {"Authorization": f"Bearer {api_key}","x-source-channel": source_channel}
        else:
            return {"Authorization": f"Bearer {_jwt_token.generate_token(api_key)}","x-source-channel": source_channel}

    def __del__(self) -> None:
        if (not hasattr(self, "_has_custom_http_client")
                or not hasattr(self, "close")
                or not hasattr(self, "_client")):
            # if the '__init__' method raised an error, self would not have client attr
            return

        if self._has_custom_http_client:
            return

        self.close()


================================================
FILE: zhipuai/api_resource/__init__.py
================================================
from .chat import (
    AsyncCompletions,
    Chat,
    Completions,
)
from .images import (
    Images
)
from .embeddings import (
    Embeddings
)
from .files import (
    Files,
    FilesWithRawResponse
)
from .fine_tuning import (
    FineTuning
)

from .batches import (
    Batches
)

from .knowledge import (
    Knowledge
)
from .tools import (
    Tools
)
from .videos import (
    Videos,
)
from .assistant import (
    Assistant,
)
from .audio import (
    Audio
)

from .moderation import (
    Moderations
)

from .web_search import (
    WebSearchApi
)

from .agents import (
    Agents
)

from .audio import (
    Audio
)

from .file_parser import (
    FileParser
)

__all__ = [
    'Videos',
    'AsyncCompletions',
    'Chat',
    'Completions',
    'Images',
    'Embeddings',
    'Files',
    'FilesWithRawResponse',
    'FineTuning',
    'Batches',
    'Knowledge',
    'Tools',
    'Assistant',
    'Audio',
    'Moderation',
    'FileParser'
]


================================================
FILE: zhipuai/api_resource/agents/__init__.py
================================================
from zhipuai.api_resource.agents.agents import Agents

__all__= [
    "Agents"
]


================================================
FILE: zhipuai/api_resource/agents/agents.py
================================================
from __future__ import annotations

from typing import Union, List, Optional, TYPE_CHECKING, Dict

import httpx
import logging
from typing_extensions import Literal

from ...core import BaseAPI, deepcopy_minimal
from ...core import NotGiven, NOT_GIVEN, Headers, Query, Body
from ...core import make_request_options
from ...core import StreamResponse
from ...types.agents.agents_completion import AgentsCompletion
from ...types.agents.agents_completion_chunk import AgentsCompletionChunk
from ...types.sensitive_word_check import SensitiveWordCheckRequest

logger = logging.getLogger(__name__)

if TYPE_CHECKING:
    from ..._client import ZhipuAI


class Agents(BaseAPI):

    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def invoke(
            self,
            agent_id: Optional[str] | NotGiven = NOT_GIVEN,
            request_id: Optional[str] | NotGiven = NOT_GIVEN,
            stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
            messages: Union[str, List[str], List[int], object, None] | NotGiven = NOT_GIVEN,
            user_id: Optional[str] | NotGiven = NOT_GIVEN,
            custom_variables: object = NOT_GIVEN,
            sensitive_word_check: Optional[SensitiveWordCheckRequest] | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> AgentsCompletion | StreamResponse[AgentsCompletionChunk]:
        body = deepcopy_minimal({
            "agent_id": agent_id,
            "request_id": request_id,
            "user_id": user_id,
            "messages": messages,
            "sensitive_word_check": sensitive_word_check,
            "stream": stream,
            "custom_variables": custom_variables
        })

        return self._post(
            "/v1/agents",
            body=body,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=AgentsCompletion,
            stream=stream or False,
            stream_cls=StreamResponse[AgentsCompletionChunk],
        )

    def async_result(
            self,
            agent_id: Optional[str] | NotGiven = NOT_GIVEN,
            async_id: Optional[str] | NotGiven = NOT_GIVEN,
            conversation_id: Optional[str] | NotGiven = NOT_GIVEN,
            custom_variables: object = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> AgentsCompletion:
        body = deepcopy_minimal({
            "agent_id": agent_id,
            "async_id": async_id,
            "conversation_id": conversation_id,
            "custom_variables": custom_variables
        })
        return self._post(
            "/v1/agents/async-result",
            body=body,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=AgentsCompletion,
        )


================================================
FILE: zhipuai/api_resource/assistant/__init__.py
================================================


from zhipuai.api_resource.assistant.assistant import Assistant

__all__= [
    "Assistant"
]


================================================
FILE: zhipuai/api_resource/assistant/assistant.py
================================================
from __future__ import annotations

from typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict
from typing_extensions import Literal

from ...types.assistant import AssistantCompletion
from ...types.assistant.assistant_conversation_resp import ConversationUsageList, ConversationUsageListResp
from ...types.assistant.assistant_support_resp import AssistantSupportResp
from ...core import BaseAPI, maybe_transform, StreamResponse
from ...core import NOT_GIVEN, Body, Headers, NotGiven

import httpx

from ...core import (
    make_request_options,
)
from ...core import deepcopy_minimal, extract_files

if TYPE_CHECKING:
    from ..._client import ZhipuAI

from ...types.assistant import assistant_create_params
from ...types.assistant import assistant_conversation_params

__all__ = ["Assistant"]


class Assistant(BaseAPI):

    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def conversation(
            self,
            assistant_id: str,
            messages: List[assistant_create_params.ConversationMessage],
            model: str = None,
            *,
            stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
            conversation_id: Optional[str] = None,
            attachments: Optional[List[assistant_create_params.AssistantAttachments]] = None,
            metadata: dict | None = None,
            request_id: str = None,
            user_id: str = None,
            extra_parameters: Optional[assistant_create_params.ExtraParameters] = None,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> AssistantCompletion | StreamResponse[AssistantCompletion]:
        body = deepcopy_minimal(
            {
                "assistant_id": assistant_id,
                "messages": messages,
                "stream": stream,
                "conversation_id": conversation_id,
                "attachments": attachments,
                "metadata": metadata,
                "request_id": request_id,
                "user_id": user_id,
                "extra_parameters": extra_parameters
            }
        )
        return self._post(
            "/assistant",
            body=maybe_transform(body, assistant_create_params.AssistantParameters),
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=AssistantCompletion,
            stream=stream or False,
            stream_cls=StreamResponse[AssistantCompletion],
        )

    def query_support(
            self,
            *,
            assistant_id_list: List[str] = None,
            request_id: str = None,
            user_id: str = None,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> AssistantSupportResp:
        body = deepcopy_minimal(
            {
                "assistant_id_list": assistant_id_list,
                "request_id": request_id,
                "user_id": user_id,
            }
        )
        return self._post(
            "/assistant/list",
            body=body,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=AssistantSupportResp,
        )

    def query_conversation_usage(
            self,
            assistant_id: str,
            page: int = 1,
            page_size: int = 10,
            *,
            request_id: str = None,
            user_id: str = None,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> ConversationUsageListResp:
        body = deepcopy_minimal(
            {
                "assistant_id": assistant_id,
                "page": page,
                "page_size": page_size,
                "request_id": request_id,
                "user_id": user_id,
            }
        )
        return self._post(
            "/assistant/conversation/list",

            body=maybe_transform(body, assistant_conversation_params.ConversationParameters),
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=ConversationUsageListResp,
        )


================================================
FILE: zhipuai/api_resource/audio/__init__.py
================================================
from .audio import (
    Audio
)

from .transcriptions import (
    Transcriptions
)


__all__ = [
    'Audio',
    'Transcriptions'
]

================================================
FILE: zhipuai/api_resource/audio/audio.py
================================================
from __future__ import annotations

from typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict
from .transcriptions import Transcriptions

from zhipuai.core._utils import extract_files

from zhipuai.types.sensitive_word_check import SensitiveWordCheckRequest
from zhipuai.types.audio import AudioSpeechParams
from ...types.audio import audio_customization_param

from zhipuai.core import BaseAPI, maybe_transform, StreamResponse
from zhipuai.core import NOT_GIVEN, Body, Headers, NotGiven, FileTypes
from zhipuai.core import _legacy_response

import httpx
from ...core import BaseAPI, cached_property

from zhipuai.core import (
    make_request_options,
)
from zhipuai.core import deepcopy_minimal
from ...types.audio.audio_speech_chunk import AudioSpeechChunk

if TYPE_CHECKING:
    from zhipuai._client import ZhipuAI

__all__ = ["Audio"]


class Audio(BaseAPI):

    @cached_property
    def transcriptions(self) -> Transcriptions:
        return Transcriptions(self._client)

    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def speech(
            self,
            *,
            model: str,
            input: str = None,
            voice: str = None,
            response_format: str = None,
            sensitive_word_check: Optional[SensitiveWordCheckRequest] | NotGiven = NOT_GIVEN,
            request_id: str = None,
            user_id: str = None,
            stream: bool = False,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
            encode_format: str,
    ) -> _legacy_response.HttpxBinaryResponseContent | StreamResponse[AudioSpeechChunk]:
        body = deepcopy_minimal(
            {
                "model": model,
                "input": input,
                "voice": voice,
                "stream": stream,
                "response_format": response_format,
                "sensitive_word_check": sensitive_word_check,
                "request_id": request_id,
                "user_id": user_id,
                "encode_format": encode_format
            }
        )
        return self._post(
            "/audio/speech",
            body=body,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=_legacy_response.HttpxBinaryResponseContent,
            stream= stream or False,
            stream_cls=StreamResponse[AudioSpeechChunk]
        )

    def customization(
            self,
            *,
            model: str,
            input: str = None,
            voice_text: str = None,
            voice_data: FileTypes = None,
            response_format: str = None,
            sensitive_word_check: Optional[SensitiveWordCheckRequest] | NotGiven = NOT_GIVEN,
            request_id: str = None,
            user_id: str = None,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> _legacy_response.HttpxBinaryResponseContent:
        body = deepcopy_minimal(
            {
                "model": model,
                "input": input,
                "voice_text": voice_text,
                "voice_data": voice_data,
                "response_format": response_format,
                "sensitive_word_check": sensitive_word_check,
                "request_id": request_id,
                "user_id": user_id
            }
        )
        files = extract_files(cast(Mapping[str, object], body), paths=[["voice_data"]])

        if files:
            extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
        return self._post(
            "/audio/customization",
            body=maybe_transform(body, audio_customization_param.AudioCustomizationParam),
            files=files,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=_legacy_response.HttpxBinaryResponseContent
        )

================================================
FILE: zhipuai/api_resource/audio/transcriptions.py
================================================
from __future__ import annotations

from typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict
from ...types.audio import transcriptions_create_param

import httpx
import logging
from typing_extensions import Literal

from ...core import BaseAPI, deepcopy_minimal, maybe_transform, drop_prefix_image_data
from ...core import make_request_options
from ...core import StreamResponse
from ...types.chat.chat_completion import Completion
from ...types.chat.chat_completion_chunk import ChatCompletionChunk
from ...types.sensitive_word_check import SensitiveWordCheckRequest
from ...core import NOT_GIVEN, Body, Headers, NotGiven, FileTypes
from zhipuai.core._utils import extract_files


logger = logging.getLogger(__name__)

if TYPE_CHECKING:
    from ..._client import ZhipuAI


__all__ = ["Transcriptions"]

class Transcriptions(BaseAPI):
    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def create(
            self,
            *,
            file: FileTypes,
            model: str,
            request_id: Optional[str] | NotGiven = NOT_GIVEN,
            user_id: Optional[str] | NotGiven = NOT_GIVEN,
            stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
            temperature: Optional[float] | NotGiven = NOT_GIVEN,
            sensitive_word_check: Optional[SensitiveWordCheckRequest] | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN
    ) -> Completion | StreamResponse[ChatCompletionChunk]:
        if temperature is not None and temperature != NOT_GIVEN:
            if temperature <= 0:
                temperature = 0.01
            if temperature >= 1:
                temperature = 0.99

        body = deepcopy_minimal({
            "model": model,
            "file": file,
            "request_id": request_id,
            "user_id": user_id,
            "temperature": temperature,
            "sensitive_word_check": sensitive_word_check,
            "stream": stream
        })
        files = extract_files(cast(Mapping[str, object], body), paths=[["file"]])
        if files:
            extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
        return self._post(
            "/audio/transcriptions",
            body=maybe_transform(body, transcriptions_create_param.TranscriptionsParam),
            files=files,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=Completion,
            stream=stream or False,
            stream_cls=StreamResponse[ChatCompletionChunk],
        )


================================================
FILE: zhipuai/api_resource/batches.py
================================================
from __future__ import annotations

import httpx
from typing import TYPE_CHECKING, Literal, Optional, Dict

from ..core import BaseAPI, NotGiven, NOT_GIVEN, Headers, Body, maybe_transform, make_request_options
from ..core.pagination import SyncCursorPage
from ..types import batch_create_params, batch_list_params
from ..types.batch import Batch

if TYPE_CHECKING:
    from .._client import ZhipuAI


class Batches(BaseAPI):

    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def create(
            self,
            *,
            completion_window: str | None = None,
            endpoint: Literal["/v1/chat/completions", "/v1/embeddings"],
            input_file_id: str,
            metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN,
            auto_delete_input_file: bool = True,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> Batch:
        return self._post(
            "/batches",
            body=maybe_transform(
                {
                    "completion_window": completion_window,
                    "endpoint": endpoint,
                    "input_file_id": input_file_id,
                    "metadata": metadata,
                    "auto_delete_input_file":auto_delete_input_file
                },
                batch_create_params.BatchCreateParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=Batch,
        )


    def retrieve(
            self,
            batch_id: str,
            *,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> Batch:
        """
        Retrieves a batch.

        Args:
          extra_headers: Send extra headers

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not batch_id:
            raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
        return self._get(
            f"/batches/{batch_id}",
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=Batch,
        )

    def list(
            self,
            *,
            after: str | NotGiven = NOT_GIVEN,
            limit: int | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> SyncCursorPage[Batch]:
        """List your organization's batches.

        Args:
          after: A cursor for use in pagination.

            `after` is an object ID that defines your place
              in the list. For instance, if you make a list request and receive 100 objects,
              ending with obj_foo, your subsequent call can include after=obj_foo in order to
              fetch the next page of the list.

          limit: A limit on the number of objects to be returned. Limit can range between 1 and
              100, and the default is 20.

          extra_headers: Send extra headers

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._get_api_list(
            "/batches",
            page=SyncCursorPage[Batch],
            options=make_request_options(
                extra_headers=extra_headers,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "after": after,
                        "limit": limit,
                    },
                    batch_list_params.BatchListParams,
                ),
            ),
            model=Batch,
        )

    def cancel(
            self,
            batch_id: str,
            *,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> Batch:
        """
        Cancels an in-progress batch.

        Args:
          batch_id: The ID of the batch to cancel.
          extra_headers: Send extra headers

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds

        """
        if not batch_id:
            raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
        return self._post(
            f"/batches/{batch_id}/cancel",
            options=make_request_options(
                extra_headers=extra_headers,extra_body=extra_body, timeout=timeout
            ),
            cast_type=Batch,
        )



================================================
FILE: zhipuai/api_resource/chat/__init__.py
================================================
from .async_completions import (
    AsyncCompletions
)

from .chat import (
    Chat
)

from .completions import (
    Completions
)

__all__ = [
    'AsyncCompletions'
    'Chat'
    'Completions'
]

================================================
FILE: zhipuai/api_resource/chat/async_completions.py
================================================
from __future__ import annotations

from typing import Union, List, Optional, TYPE_CHECKING, Dict

import httpx
import logging
from typing_extensions import Literal

from ...core import BaseAPI, maybe_transform, drop_prefix_image_data
from ...core import NotGiven, NOT_GIVEN, Headers, Body
from ...core import make_request_options
from ...types.chat.async_chat_completion import AsyncTaskStatus, AsyncCompletion
from ...types.chat.code_geex import code_geex_params
from ...types.sensitive_word_check import SensitiveWordCheckRequest

logger = logging.getLogger(__name__)

if TYPE_CHECKING:
    from ..._client import ZhipuAI


class AsyncCompletions(BaseAPI):
    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def create(
            self,
            *,
            model: str,
            request_id: Optional[str] | NotGiven = NOT_GIVEN,
            user_id: Optional[str] | NotGiven = NOT_GIVEN,
            do_sample: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
            temperature: Optional[float] | NotGiven = NOT_GIVEN,
            top_p: Optional[float] | NotGiven = NOT_GIVEN,
            max_tokens: int | NotGiven = NOT_GIVEN,
            seed: int | NotGiven = NOT_GIVEN,
            messages: Union[str, List[str], List[int], List[List[int]], None],
            stop: Optional[Union[str, List[str], None]] | NotGiven = NOT_GIVEN,
            sensitive_word_check: Optional[SensitiveWordCheckRequest] | NotGiven = NOT_GIVEN,
            tools: Optional[object] | NotGiven = NOT_GIVEN,
            tool_choice: str | NotGiven = NOT_GIVEN,
            meta: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN,
            extra: Optional[code_geex_params.CodeGeexExtra] | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
            response_format: object | None = None,
            thinking: object | None = None,
    ) -> AsyncTaskStatus:
        _cast_type = AsyncTaskStatus
        logger.debug(f"temperature:{temperature}, top_p:{top_p}")
        if temperature is not None and temperature != NOT_GIVEN:

            if temperature <= 0:
                do_sample = False
                temperature = 0.01
                # logger.warning("temperature:取值范围是:(0.0, 1.0) 开区间,do_sample重写为:false(参数top_p temperture不生效)")
            if temperature >= 1:
                temperature = 0.99
                # logger.warning("temperature:取值范围是:(0.0, 1.0) 开区间")
        if top_p is not None and top_p != NOT_GIVEN:

            if top_p >= 1:
                top_p = 0.99
                # logger.warning("top_p:取值范围是:(0.0, 1.0) 开区间,不能等于 0 或 1")
            if top_p <= 0:
                top_p = 0.01
                # logger.warning("top_p:取值范围是:(0.0, 1.0) 开区间,不能等于 0 或 1")

        logger.debug(f"temperature:{temperature}, top_p:{top_p}")
        if isinstance(messages, List):
            for item in messages:
                if item.get('content'):
                    item['content'] = drop_prefix_image_data(item['content'])

        body = {
            "model": model,
            "request_id": request_id,
            "user_id": user_id,
            "temperature": temperature,
            "top_p": top_p,
            "do_sample": do_sample,
            "max_tokens": max_tokens,
            "seed": seed,
            "messages": messages,
            "stop": stop,
            "sensitive_word_check": sensitive_word_check,
            "tools": tools,
            "tool_choice": tool_choice,
            "meta": meta,
            "extra": maybe_transform(extra, code_geex_params.CodeGeexExtra),
            "response_format": response_format,
            "thinking": thinking
        }
        return self._post(
            "/async/chat/completions",

            body=body,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=_cast_type,
            stream=False,
        )

    def retrieve_completion_result(
            self,
            id: str,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> Union[AsyncCompletion, AsyncTaskStatus]:
        _cast_type = Union[AsyncCompletion, AsyncTaskStatus]
        return self._get(
            path=f"/async-result/{id}",
            cast_type=_cast_type,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
        )


================================================
FILE: zhipuai/api_resource/chat/chat.py
================================================
from typing import TYPE_CHECKING
from .completions import Completions
from .async_completions import AsyncCompletions
from ...core import BaseAPI, cached_property

if TYPE_CHECKING:
    from ..._client import ZhipuAI


class Chat(BaseAPI):

    @cached_property
    def completions(self) -> Completions:
        return Completions(self._client)

    @cached_property
    def asyncCompletions(self) -> AsyncCompletions:
        return AsyncCompletions(self._client)

================================================
FILE: zhipuai/api_resource/chat/completions.py
================================================
from __future__ import annotations

from typing import Union, List, Optional, TYPE_CHECKING, Dict

import httpx
import logging
from typing_extensions import Literal

from ...core import BaseAPI, deepcopy_minimal, maybe_transform, drop_prefix_image_data
from ...core import NotGiven, NOT_GIVEN, Headers, Query, Body
from ...core import make_request_options
from ...core import StreamResponse
from ...types.chat.chat_completion import Completion
from ...types.chat.chat_completion_chunk import ChatCompletionChunk
from ...types.chat.code_geex import code_geex_params
from ...types.sensitive_word_check import SensitiveWordCheckRequest

logger = logging.getLogger(__name__)

if TYPE_CHECKING:
    from ..._client import ZhipuAI


class Completions(BaseAPI):
    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def create(
            self,
            *,
            model: str,
            request_id: Optional[str] | NotGiven = NOT_GIVEN,
            user_id: Optional[str] | NotGiven = NOT_GIVEN,
            do_sample: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
            stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
            temperature: Optional[float] | NotGiven = NOT_GIVEN,
            top_p: Optional[float] | NotGiven = NOT_GIVEN,
            max_tokens: int | NotGiven = NOT_GIVEN,
            seed: int | NotGiven = NOT_GIVEN,
            messages: Union[str, List[str], List[int], object, None],
            stop: Optional[Union[str, List[str], None]] | NotGiven = NOT_GIVEN,
            sensitive_word_check: Optional[SensitiveWordCheckRequest] | NotGiven = NOT_GIVEN,
            tools: Optional[object] | NotGiven = NOT_GIVEN,
            tool_choice: str | NotGiven = NOT_GIVEN,
            meta: Optional[Dict[str,str]] | NotGiven = NOT_GIVEN,
            extra: Optional[code_geex_params.CodeGeexExtra] | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
            response_format : object | None = None,
            thinking :  object | None = None,
    ) -> Completion | StreamResponse[ChatCompletionChunk]:
        logger.debug(f"temperature:{temperature}, top_p:{top_p}")
        if temperature is not None and temperature != NOT_GIVEN:

            if temperature <= 0:
                do_sample = False
                temperature = 0.01
                # logger.warning("temperature:取值范围是:(0.0, 1.0) 开区间,do_sample重写为:false(参数top_p temperture不生效)")
            if temperature >= 1:
                temperature = 0.99
                # logger.warning("temperature:取值范围是:(0.0, 1.0) 开区间")
        if top_p is not None and top_p != NOT_GIVEN:

            if top_p >= 1:
                top_p = 0.99
                # logger.warning("top_p:取值范围是:(0.0, 1.0) 开区间,不能等于 0 或 1")
            if top_p <= 0:
                top_p = 0.01
                # logger.warning("top_p:取值范围是:(0.0, 1.0) 开区间,不能等于 0 或 1")

        logger.debug(f"temperature:{temperature}, top_p:{top_p}")
        if isinstance(messages, List):
            for item in messages:
                if item.get('content'):
                    item['content'] = drop_prefix_image_data(item['content'])

        body = deepcopy_minimal({
            "model": model,
            "request_id": request_id,
            "user_id": user_id,
            "temperature": temperature,
            "top_p": top_p,
            "do_sample": do_sample,
            "max_tokens": max_tokens,
            "seed": seed,
            "messages": messages,
            "stop": stop,
            "sensitive_word_check": sensitive_word_check,
            "stream": stream,
            "tools": tools,
            "tool_choice": tool_choice,
            "meta": meta,
            "extra": maybe_transform(extra, code_geex_params.CodeGeexExtra),
            "response_format": response_format,
            "thinking": thinking
        })
        return self._post(
            "/chat/completions",
            body=body,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=Completion,
            stream=stream or False,
            stream_cls=StreamResponse[ChatCompletionChunk],
        )




================================================
FILE: zhipuai/api_resource/embeddings.py
================================================
from __future__ import annotations

from typing import Union, List, Optional, TYPE_CHECKING

import httpx

from ..core import BaseAPI, Body
from ..core import NotGiven, NOT_GIVEN, Headers
from ..core import make_request_options
from ..types.embeddings import EmbeddingsResponded

if TYPE_CHECKING:
    from .._client import ZhipuAI


class Embeddings(BaseAPI):
    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def create(
            self,
            *,
            input: Union[str, List[str], List[int], List[List[int]]],
            model: Union[str],
            dimensions: Union[int]| NotGiven = NOT_GIVEN,
            encoding_format: str | NotGiven = NOT_GIVEN,
            user: str | NotGiven = NOT_GIVEN,
            request_id: Optional[str] | NotGiven = NOT_GIVEN,
            sensitive_word_check: Optional[object] | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            disable_strict_validation: Optional[bool] | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> EmbeddingsResponded:
        _cast_type = EmbeddingsResponded
        if disable_strict_validation:
            _cast_type = object
        return self._post(
            "/embeddings",
            body={
                "input": input,
                "model": model,
                "dimensions": dimensions,
                "encoding_format": encoding_format,
                "user": user,
                "request_id": request_id,
                "sensitive_word_check": sensitive_word_check,
            },
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=_cast_type,
            stream=False,
        )


================================================
FILE: zhipuai/api_resource/file_parser/__init__.py
================================================
from .file_parser import FileParser

__all__ = ['FileParser']

================================================
FILE: zhipuai/api_resource/file_parser/file_parser.py
================================================
from __future__ import annotations

from typing import TYPE_CHECKING, Mapping, cast

import httpx
from typing_extensions import Literal

from ...core import BaseAPI, maybe_transform
from ...core import NOT_GIVEN, Body, Headers, NotGiven, FileTypes
from ...core import _legacy_binary_response
from ...core import _legacy_response
from ...core import deepcopy_minimal, extract_files
from ...core import (
    make_request_options,
)
from ...types.file_parser.file_parser_create_params import FileParserCreateParams
from ...types.file_parser.file_parser_resp import FileParserTaskCreateResp

if TYPE_CHECKING:
    from ..._client import ZhipuAI

__all__ = ["FileParser"]


class FileParser(BaseAPI):

    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def create(
            self,
            *,
            file: FileTypes = None,
            file_type: str = None,
            tool_type: Literal["simple", "doc2x", "tencent", "zhipu-pro"],
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> FileParserTaskCreateResp:

        if not file:
            raise ValueError("At least one `file` must be provided.")
        body = deepcopy_minimal(
            {
                "file": file,
                "file_type": file_type,
                "tool_type": tool_type,
            }
        )

        files = extract_files(cast(Mapping[str, object], body), paths=[["file"]])
        if files:
            # It should be noted that the actual Content-Type header that will be
            # sent to the server will contain a `boundary` parameter, e.g.
            # multipart/form-data; boundary=---abc--
            extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
        return self._post(
            "/files/parser/create",
            body=maybe_transform(body, FileParserCreateParams),
            files=files,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=FileParserTaskCreateResp,
        )

    def content(
            self,
            task_id: str,
            *,
            format_type: Literal["text", "download_link"],
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> _legacy_response.HttpxBinaryResponseContent:
        """
        Returns the contents of the specified file.

        Args:
          extra_headers: Send extra headers

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not task_id:
            raise ValueError(f"Expected a non-empty value for `task_id` but received {task_id!r}")
        extra_headers = {"Accept": "application/binary", **(extra_headers or {})}
        return self._get(
            f"/files/parser/result/{task_id}/{format_type}",
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=_legacy_binary_response.HttpxBinaryResponseContent,
        )


================================================
FILE: zhipuai/api_resource/files.py
================================================
from __future__ import annotations


from typing import TYPE_CHECKING, List, Mapping, cast
from typing_extensions import Literal

from ..core import BaseAPI, maybe_transform
from ..core import NOT_GIVEN, Body, Headers, NotGiven, FileTypes

import httpx

from ..core import (
    make_request_options,
)
from ..core import deepcopy_minimal, extract_files
from ..types.files import FileObject, ListOfFileObject, file_create_params, FileDeleted

from ..types.files import UploadDetail

from ..core import _legacy_binary_response
from ..core import _legacy_response

if TYPE_CHECKING:
    from .._client import ZhipuAI

__all__ = ["Files", "FilesWithRawResponse"]


class Files(BaseAPI):

    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def create(
            self,
            *,
            file: FileTypes = None,
            upload_detail: List[UploadDetail] = None,
            purpose: Literal["fine-tune", "retrieval", "batch"],
            knowledge_id: str = None,
            sentence_size: int = None,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> FileObject:

        if not file and not upload_detail:
            raise ValueError("At least one of `file` and `upload_detail` must be provided.")
        body = deepcopy_minimal(
            {
                "file": file,
                "upload_detail": upload_detail,
                "purpose": purpose,
                "knowledge_id": knowledge_id,
                "sentence_size": sentence_size,
            }
        )
        files = extract_files(cast(Mapping[str, object], body), paths=[["file"]])
        if files:
            # It should be noted that the actual Content-Type header that will be
            # sent to the server will contain a `boundary` parameter, e.g.
            # multipart/form-data; boundary=---abc--
            extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
        return self._post(
            "/files",
            body=maybe_transform(body, file_create_params.FileCreateParams),
            files=files,
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=FileObject,
        )

    # def retrieve(
    #         self,
    #         file_id: str,
    #         *,
    #         extra_headers: Headers | None = None,
    #         extra_body: Body | None = None,
    #         timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    # ) -> FileObject:
    #     """
    #     Returns information about a specific file.
    #
    #     Args:
    #       file_id: The ID of the file to retrieve information about
    #       extra_headers: Send extra headers
    #
    #       extra_body: Add additional JSON properties to the request
    #
    #       timeout: Override the client-level default timeout for this request, in seconds
    #     """
    #     if not file_id:
    #         raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
    #     return self._get(
    #         f"/files/{file_id}",
    #         options=make_request_options(
    #             extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
    #         ),
    #         cast_type=FileObject,
    #     )

    def list(
            self,
            *,
            purpose: str | NotGiven = NOT_GIVEN,
            limit: int | NotGiven = NOT_GIVEN,
            after: str | NotGiven = NOT_GIVEN,
            order: str | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> ListOfFileObject:
        return self._get(
            "/files",
            cast_type=ListOfFileObject,
            options=make_request_options(
                extra_headers=extra_headers,
                extra_body=extra_body,
                timeout=timeout,
                query={
                    "purpose": purpose,
                    "limit": limit,
                    "after": after,
                    "order": order,
                },
            ),
        )

    def delete(
            self,
            file_id: str,
            *,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> FileDeleted:
        """
        Delete a file.

        Args:
          file_id: The ID of the file to delete
          extra_headers: Send extra headers

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not file_id:
            raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
        return self._delete(
            f"/files/{file_id}",
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=FileDeleted,
        )

    def content(
            self,
            file_id: str,
            *,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> _legacy_response.HttpxBinaryResponseContent:
        """
        Returns the contents of the specified file.

        Args:
          extra_headers: Send extra headers

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not file_id:
            raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
        extra_headers = {"Accept": "application/binary", **(extra_headers or {})}
        return self._get(
            f"/files/{file_id}/content",
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=_legacy_binary_response.HttpxBinaryResponseContent,
        )


class FilesWithRawResponse:
    def __init__(self, files: Files) -> None:
        self._files = files

        self.create = _legacy_response.to_raw_response_wrapper(
            files.create,
        )
        self.list = _legacy_response.to_raw_response_wrapper(
            files.list,
        )
        self.content = _legacy_response.to_raw_response_wrapper(
            files.content,
        )

================================================
FILE: zhipuai/api_resource/fine_tuning/__init__.py
================================================
from .jobs import (
    Jobs
)

from .models import (
    FineTunedModels
)

from .fine_tuning import (
    FineTuning
)


__all__ = [
    'Jobs',
    'FineTunedModels',
    'FineTuning'
]

================================================
FILE: zhipuai/api_resource/fine_tuning/fine_tuning.py
================================================
from typing import TYPE_CHECKING
from .jobs import Jobs
from .models import FineTunedModels
from ...core import BaseAPI, cached_property

if TYPE_CHECKING:
    from ..._client import ZhipuAI


class FineTuning(BaseAPI):

    @cached_property
    def jobs(self) -> Jobs:
        return Jobs(self._client)

    @cached_property
    def models(self) -> FineTunedModels:
        return FineTunedModels(self._client)



================================================
FILE: zhipuai/api_resource/fine_tuning/jobs/__init__.py
================================================
from .jobs import Jobs

__all__ = [
    "Jobs"
]

================================================
FILE: zhipuai/api_resource/fine_tuning/jobs/jobs.py
================================================
from __future__ import annotations

from typing import Optional, TYPE_CHECKING

import httpx

from ....core import BaseAPI
from ....core import NOT_GIVEN, Headers, NotGiven, Body
from ....core import (
    make_request_options,
)
from ....types.fine_tuning import (
    FineTuningJob,
    job_create_params,
    ListOfFineTuningJob,
    FineTuningJobEvent,
)

if TYPE_CHECKING:
    from ...._client import ZhipuAI

__all__ = ["Jobs"]


class Jobs(BaseAPI):

    def __init__(self, client: "ZhipuAI") -> None:
        super().__init__(client)

    def create(
            self,
            *,
            model: str,
            training_file: str,
            hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN,
            suffix: Optional[str] | NotGiven = NOT_GIVEN,
            request_id: Optional[str] | NotGiven = NOT_GIVEN,
            validation_file: Optional[str] | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> FineTuningJob:
        return self._post(
            "/fine_tuning/jobs",
            body={
                "model": model,
                "training_file": training_file,
                "hyperparameters": hyperparameters,
                "suffix": suffix,
                "validation_file": validation_file,
                "request_id": request_id,
            },
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=FineTuningJob,
        )

    def retrieve(
            self,
            fine_tuning_job_id: str,
            *,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> FineTuningJob:
        return self._get(
            f"/fine_tuning/jobs/{fine_tuning_job_id}",
            options=make_request_options(
                extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
            ),
            cast_type=FineTuningJob,
        )

    def list(
            self,
            *,
            after: str | NotGiven = NOT_GIVEN,
            limit: int | NotGiven = NOT_GIVEN,
            extra_headers: Headers | None = None,
            extra_body: Body | None = None,
            timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
    ) -> ListOfFineTuningJob:
        return self._get(
            "/fine_tuning/jobs",
            cast_type=ListOfFineTuningJob,
            options=make_request_options(
                extra_headers=extra_headers,
                extra_body=extra_body,
                timeout=timeout,
                query={
                    "
Download .txt
gitextract_z9p34zne/

├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug-report.yml
│   │   └── feature-request.yml
│   ├── PULL_REQUEST_TEMPLATE.md
│   ├── actions/
│   │   └── poetry_setup/
│   │       └── action.yml
│   └── workflows/
│       ├── _integration_test.yml
│       ├── _release.yml
│       ├── _test.yml
│       ├── _test_release.yml
│       └── lint-pr.yaml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── README_CN.md
├── Release-Note.md
├── poetry.toml
├── pyproject.toml
├── tests/
│   ├── conftest.py
│   ├── integration_tests/
│   │   ├── batchinput.jsonl
│   │   ├── demo.jsonl
│   │   ├── file.xlsx
│   │   ├── test.py
│   │   ├── test_agents.py
│   │   ├── test_assistant.py
│   │   ├── test_audio.py
│   │   ├── test_batches.py
│   │   ├── test_charglm3.py
│   │   ├── test_chat.py
│   │   ├── test_code_geex.py
│   │   ├── test_embedding.py
│   │   ├── test_emohaa.py
│   │   ├── test_file.py
│   │   ├── test_file_parser.py
│   │   ├── test_finetuning.py
│   │   ├── test_images.py
│   │   ├── test_knowledge.py
│   │   ├── test_moderation.py
│   │   ├── test_tools.py
│   │   ├── test_transcriptions.py
│   │   ├── test_videos.py
│   │   ├── test_vlm_thinking.py
│   │   └── test_web_search.py
│   └── unit_tests/
│       ├── batchinput.jsonl
│       ├── maybe/
│       │   └── test_maybe_transform.py
│       ├── response_model/
│       │   ├── __init__.py
│       │   └── test_response.py
│       ├── sse_client/
│       │   ├── __init__.py
│       │   └── test_stream.py
│       ├── test_agents.py
│       ├── test_audio.py
│       ├── test_jwt.py
│       ├── test_request_opt.py
│       ├── test_response.py
│       ├── test_sdk_import.py
│       └── test_streaming.py
└── zhipuai/
    ├── __init__.py
    ├── __version__.py
    ├── _client.py
    ├── api_resource/
    │   ├── __init__.py
    │   ├── agents/
    │   │   ├── __init__.py
    │   │   └── agents.py
    │   ├── assistant/
    │   │   ├── __init__.py
    │   │   └── assistant.py
    │   ├── audio/
    │   │   ├── __init__.py
    │   │   ├── audio.py
    │   │   └── transcriptions.py
    │   ├── batches.py
    │   ├── chat/
    │   │   ├── __init__.py
    │   │   ├── async_completions.py
    │   │   ├── chat.py
    │   │   └── completions.py
    │   ├── embeddings.py
    │   ├── file_parser/
    │   │   ├── __init__.py
    │   │   └── file_parser.py
    │   ├── files.py
    │   ├── fine_tuning/
    │   │   ├── __init__.py
    │   │   ├── fine_tuning.py
    │   │   ├── jobs/
    │   │   │   ├── __init__.py
    │   │   │   └── jobs.py
    │   │   └── models/
    │   │       ├── __init__.py
    │   │       └── fine_tuned_models.py
    │   ├── images.py
    │   ├── knowledge/
    │   │   ├── __init__.py
    │   │   ├── document/
    │   │   │   ├── __init__.py
    │   │   │   └── document.py
    │   │   └── knowledge.py
    │   ├── moderation/
    │   │   ├── __init__.py
    │   │   └── moderations.py
    │   ├── tools/
    │   │   ├── __init__.py
    │   │   └── tools.py
    │   ├── videos/
    │   │   ├── __init__.py
    │   │   └── videos.py
    │   └── web_search/
    │       ├── __init__.py
    │       └── web_search.py
    ├── core/
    │   ├── __init__.py
    │   ├── _base_api.py
    │   ├── _base_compat.py
    │   ├── _base_models.py
    │   ├── _base_type.py
    │   ├── _constants.py
    │   ├── _errors.py
    │   ├── _files.py
    │   ├── _http_client.py
    │   ├── _jwt_token.py
    │   ├── _legacy_binary_response.py
    │   ├── _legacy_response.py
    │   ├── _request_opt.py
    │   ├── _response.py
    │   ├── _sse_client.py
    │   ├── _utils/
    │   │   ├── __init__.py
    │   │   ├── _transform.py
    │   │   ├── _typing.py
    │   │   └── _utils.py
    │   ├── logs.py
    │   └── pagination.py
    └── types/
        ├── __init__.py
        ├── agents/
        │   ├── __init__.py
        │   ├── agents_completion.py
        │   ├── agents_completion_chunk.py
        │   └── chat_completions_create_param.py
        ├── assistant/
        │   ├── __init__.py
        │   ├── assistant_completion.py
        │   ├── assistant_conversation_params.py
        │   ├── assistant_conversation_resp.py
        │   ├── assistant_create_params.py
        │   ├── assistant_support_resp.py
        │   └── message/
        │       ├── __init__.py
        │       ├── message_content.py
        │       ├── text_content_block.py
        │       ├── tools/
        │       │   ├── code_interpreter_delta_block.py
        │       │   ├── drawing_tool_delta_block.py
        │       │   ├── function_delta_block.py
        │       │   ├── retrieval_delta_black.py
        │       │   ├── tools_type.py
        │       │   └── web_browser_delta_block.py
        │       └── tools_delta_block.py
        ├── audio/
        │   ├── __init__.py
        │   ├── audio_customization_param.py
        │   ├── audio_speech_chunk.py
        │   ├── audio_speech_params.py
        │   └── transcriptions_create_param.py
        ├── batch.py
        ├── batch_create_params.py
        ├── batch_error.py
        ├── batch_list_params.py
        ├── batch_request_counts.py
        ├── chat/
        │   ├── __init__.py
        │   ├── async_chat_completion.py
        │   ├── chat_completion.py
        │   ├── chat_completion_chunk.py
        │   ├── chat_completions_create_param.py
        │   └── code_geex/
        │       └── code_geex_params.py
        ├── embeddings.py
        ├── file_parser/
        │   ├── __init__.py
        │   ├── file_parser_create_params.py
        │   └── file_parser_resp.py
        ├── files/
        │   ├── __init__.py
        │   ├── file_create_params.py
        │   ├── file_deleted.py
        │   ├── file_object.py
        │   └── upload_detail.py
        ├── fine_tuning/
        │   ├── __init__.py
        │   ├── fine_tuning_job.py
        │   ├── fine_tuning_job_event.py
        │   ├── job_create_params.py
        │   └── models/
        │       ├── __init__.py
        │       └── fine_tuned_models.py
        ├── image.py
        ├── knowledge/
        │   ├── __init__.py
        │   ├── document/
        │   │   ├── __init__.py
        │   │   ├── document.py
        │   │   ├── document_edit_params.py
        │   │   ├── document_list_params.py
        │   │   └── document_list_resp.py
        │   ├── knowledge.py
        │   ├── knowledge_create_params.py
        │   ├── knowledge_list_params.py
        │   ├── knowledge_list_resp.py
        │   └── knowledge_used.py
        ├── moderation/
        │   ├── __init__.py
        │   └── moderation_completion.py
        ├── sensitive_word_check/
        │   ├── __init__.py
        │   └── sensitive_word_check.py
        ├── tools/
        │   ├── __init__.py
        │   ├── tools_web_search_params.py
        │   ├── web_search.py
        │   └── web_search_chunk.py
        ├── video/
        │   ├── __init__.py
        │   ├── video_create_params.py
        │   └── video_object.py
        └── web_search/
            ├── __init__.py
            ├── web_search_create_params.py
            └── web_search_resp.py
Download .txt
SYMBOL INDEX (701 symbols across 130 files)

FILE: tests/conftest.py
  function pytest_addoption (line 17) | def pytest_addoption(parser: Parser) -> None:
  function pytest_collection_modifyitems (line 31) | def pytest_collection_modifyitems(config: Config, items: Sequence[Functi...
  function logging_conf (line 94) | def logging_conf() -> dict:
  function test_file_path (line 104) | def test_file_path(request) -> Path:

FILE: tests/integration_tests/test_agents.py
  function test_completions_sync (line 9) | def test_completions_sync(logging_conf):
  function test_completions_stream (line 32) | def test_completions_stream(logging_conf):
  function test_correction (line 56) | def test_correction():
  function test_correction_result (line 75) | def test_correction_result(image_id,uuids,trace_id):
  function main (line 92) | def main():

FILE: tests/integration_tests/test_assistant.py
  function test_assistant (line 8) | def test_assistant(logging_conf) -> None:
  function test_assistant_query_support (line 37) | def test_assistant_query_support(logging_conf) -> None:
  function test_assistant_query_conversation_usage (line 56) | def test_assistant_query_conversation_usage(logging_conf) -> None:
  function test_translate_api (line 74) | def test_translate_api(logging_conf) -> None:

FILE: tests/integration_tests/test_audio.py
  function test_audio_speech (line 11) | def test_audio_speech(logging_conf):
  function test_audio_speech_streaming (line 32) | def test_audio_speech_streaming(logging_conf):
  function test_audio_customization (line 64) | def test_audio_customization(logging_conf):

FILE: tests/integration_tests/test_batches.py
  function test_batch_input_file (line 9) | def test_batch_input_file(test_file_path, logging_conf) -> None:
  function test_batch_create (line 31) | def test_batch_create(logging_conf) -> None:
  function test_batch_retrieve (line 53) | def test_batch_retrieve(logging_conf) -> None:
  function test_batch_cancel (line 69) | def test_batch_cancel(logging_conf) -> None:
  function test_batch_list (line 84) | def test_batch_list(logging_conf) -> None:
  function test_batch_result (line 105) | def test_batch_result(test_file_path, logging_conf) -> None:

FILE: tests/integration_tests/test_charglm3.py
  function test_completions_charglm (line 10) | def test_completions_charglm(logging_conf):
  function test_async_completions (line 35) | def test_async_completions():

FILE: tests/integration_tests/test_chat.py
  function test_completions_temp0 (line 10) | def test_completions_temp0(logging_conf):
  function test_completions_temp1 (line 36) | def test_completions_temp1(logging_conf):
  function test_completions_top0 (line 62) | def test_completions_top0(logging_conf):
  function test_completions_top1 (line 88) | def test_completions_top1(logging_conf):
  function test_completions (line 114) | def test_completions(logging_conf):
  function test_completions_disenable_web_search (line 162) | def test_completions_disenable_web_search(logging_conf):
  function test_completions_enable_web_search (line 211) | def test_completions_enable_web_search(logging_conf):
  function test_completions_stream (line 260) | def test_completions_stream(logging_conf):
  function encode_image (line 302) | def encode_image(image_path):
  function test_completions_vis (line 309) | def test_completions_vis(logging_conf):
  function test_completions_vis_base64 (line 346) | def test_completions_vis_base64(test_file_path, logging_conf):
  function test_async_completions (line 388) | def test_async_completions(logging_conf):
  function test_retrieve_completion_result (line 436) | def test_retrieve_completion_result(logging_conf):
  function test_completions_sensitive_word_check (line 453) | def test_completions_sensitive_word_check(logging_conf):

FILE: tests/integration_tests/test_code_geex.py
  function test_code_geex (line 9) | def test_code_geex(logging_conf):
  function test_code_geex_async (line 57) | def test_code_geex_async(logging_conf):
  function test_geex_result (line 105) | def test_geex_result(logging_conf):

FILE: tests/integration_tests/test_embedding.py
  function test_embeddings (line 8) | def test_embeddings(logging_conf):
  function test_embeddings_dimensions (line 28) | def test_embeddings_dimensions(logging_conf):

FILE: tests/integration_tests/test_emohaa.py
  function test_completions_emohaa (line 10) | def test_completions_emohaa(logging_conf):

FILE: tests/integration_tests/test_file.py
  function test_server (line 14) | def test_server():
  class TestZhipuAIFileServer (line 23) | class TestZhipuAIFileServer:
    method test_logs (line 24) | def test_logs(self, logging_conf):
    method test_files (line 27) | def test_files(self, test_server, test_file_path):
    method test_files_validation (line 43) | def test_files_validation(self, test_server, test_file_path):
    method test_files_list (line 60) | def test_files_list(self, test_server):
    method test_delete_files (line 72) | def test_delete_files(self, test_server):

FILE: tests/integration_tests/test_file_parser.py
  function test_file_parser_create (line 13) | def test_file_parser_create(logging_conf):
  function test_file_parser_content (line 27) | def test_file_parser_content(logging_conf):

FILE: tests/integration_tests/test_finetuning.py
  function test_finetuning_create (line 8) | def test_finetuning_create(logging_conf):
  function test_finetuning_retrieve (line 32) | def test_finetuning_retrieve(logging_conf):
  function test_finetuning_job_list (line 49) | def test_finetuning_job_list(logging_conf):
  function test_finetuning_job_cancel (line 65) | def test_finetuning_job_cancel(logging_conf):
  function test_finetuning_job_delete (line 81) | def test_finetuning_job_delete(logging_conf):
  function test_model_check (line 97) | def test_model_check(logging_conf):
  function test_model_delete (line 119) | def test_model_delete(logging_conf):

FILE: tests/integration_tests/test_images.py
  function test_images (line 8) | def test_images(logging_conf):
  function test_images_sensitive_word_check (line 28) | def test_images_sensitive_word_check(logging_conf):

FILE: tests/integration_tests/test_knowledge.py
  function test_server (line 14) | def test_server():
  class TestZhipuAIKnowledgeServer (line 23) | class TestZhipuAIKnowledgeServer:
    method test_logs (line 24) | def test_logs(self, logging_conf):
    method test_knowledge_create (line 27) | def test_knowledge_create(self, test_server):
    method test_knowledge_document_create (line 46) | def test_knowledge_document_create(self, test_server, test_file_path):
    method test_knowledge_modify (line 64) | def test_knowledge_modify(self, test_server):
    method test_knowledge_query (line 82) | def test_knowledge_query(self, test_server):
    method test_knowledge_used (line 94) | def test_knowledge_used(self, test_server):
    method test_knowledge_document_retrieve (line 106) | def test_knowledge_document_retrieve(self, test_server, test_file_path):
    method test_knowledge_document_edit (line 120) | def test_knowledge_document_edit(self, test_server):
    method test_knowledge_document_list (line 136) | def test_knowledge_document_list(self, test_server):
    method test_knowledge_document_delete (line 150) | def test_knowledge_document_delete(self, test_server):
    method test_knowledge_delete (line 164) | def test_knowledge_delete(self, test_server):

FILE: tests/integration_tests/test_moderation.py
  function test_completions_temp0 (line 9) | def test_completions_temp0(logging_conf):

FILE: tests/integration_tests/test_tools.py
  function test_tools (line 8) | def test_tools(logging_conf):
  function test_tools_stream (line 32) | def test_tools_stream(logging_conf):

FILE: tests/integration_tests/test_transcriptions.py
  function test_transcriptions (line 9) | def test_transcriptions(logging_conf):
  function test_transcriptions_stream (line 26) | def test_transcriptions_stream(logging_conf):

FILE: tests/integration_tests/test_videos.py
  function test_videos (line 8) | def test_videos(logging_conf):
  function test_videos_sensitive_word_check (line 25) | def test_videos_sensitive_word_check(logging_conf):
  function test_videos_image_url (line 45) | def test_videos_image_url(logging_conf):
  function test_retrieve_videos_result (line 65) | def test_retrieve_videos_result(logging_conf):

FILE: tests/integration_tests/test_vlm_thinking.py
  function test_completions_vlm_thinking (line 9) | def test_completions_vlm_thinking(logging_conf):
  function test_completions_vlm_thinking_stream (line 47) | def test_completions_vlm_thinking_stream(logging_conf):

FILE: tests/integration_tests/test_web_search.py
  function test_web_search (line 8) | def test_web_search(logging_conf):

FILE: tests/unit_tests/maybe/test_maybe_transform.py
  function test_response_joblist_model_cast (line 6) | def test_response_joblist_model_cast() -> None:

FILE: tests/unit_tests/response_model/test_response.py
  class MockClient (line 39) | class MockClient:
    method _process_response_data (line 42) | def _process_response_data(
  function test_response_chat_model_cast (line 60) | def test_response_chat_model_cast(R: Type[BaseModel]) -> None:
  function test_response_finetuned_model_model_cast (line 191) | def test_response_finetuned_model_model_cast(R: Type[BaseModel]) -> None:
  function test_response_job_model_cast (line 226) | def test_response_job_model_cast(R: Type[BaseModel]) -> None:
  function test_response_joblist_model_cast (line 296) | def test_response_joblist_model_cast(R: Type[BaseModel]) -> None:
  function test_response_embedding_model_cast (line 369) | def test_response_embedding_model_cast(R: Type[BaseModel]) -> None:
  function test_response_file_list_model_cast (line 422) | def test_response_file_list_model_cast(R: Type[BaseModel]) -> None:
  function test_response_file_list_model_cast (line 467) | def test_response_file_list_model_cast(R: Type[BaseModel]) -> None:
  function test_response_image_model_cast (line 515) | def test_response_image_model_cast(R: Type[BaseModel]) -> None:

FILE: tests/unit_tests/sse_client/test_stream.py
  class MockClient (line 11) | class MockClient:
    method _process_response_data (line 14) | def _process_response_data(
  function test_stream_cls_chunk (line 24) | def test_stream_cls_chunk() -> None:

FILE: tests/unit_tests/test_agents.py
  function test_agents_completion_error_field (line 1) | def test_agents_completion_error_field():

FILE: tests/unit_tests/test_audio.py
  function test_audio_error_field (line 1) | def test_audio_error_field():

FILE: tests/unit_tests/test_jwt.py
  function test_token (line 7) | def test_token() -> None:

FILE: tests/unit_tests/test_request_opt.py
  function test_initialization (line 7) | def test_initialization():
  function test_get_max_retries (line 25) | def test_get_max_retries(max_retries_input, expected):
  function test_construct (line 33) | def test_construct():

FILE: tests/unit_tests/test_response.py
  class MockHttpClient (line 13) | class MockHttpClient:
    method _process_response_data (line 17) | def _process_response_data(
  class MockStreamResponse (line 27) | class MockStreamResponse(StreamResponse[ResponseT]):
    method __init__ (line 29) | def __init__(
    method __iter__ (line 42) | def __iter__(self):
  function test_http_response_initialization (line 48) | def test_http_response_initialization():
  function test_parse_method (line 62) | def test_parse_method():
  function test_properties (line 109) | def test_properties():

FILE: tests/unit_tests/test_sdk_import.py
  function test_sdk_import_unit (line 1) | def test_sdk_import_unit():
  function test_os_import_unit (line 7) | def test_os_import_unit():
  function test_sdk_import (line 13) | def test_sdk_import():

FILE: tests/unit_tests/test_streaming.py
  function test_basic (line 8) | def test_basic() -> None:
  function test_data_missing_event (line 23) | def test_data_missing_event() -> None:
  function test_event_missing_data (line 37) | def test_event_missing_data() -> None:
  function test_multiple_events (line 51) | def test_multiple_events() -> None:
  function test_multiple_events_with_data (line 72) | def test_multiple_events_with_data() -> None:

FILE: zhipuai/_client.py
  class ZhipuAI (line 17) | class ZhipuAI(HttpClient):
    method __init__ (line 23) | def __init__(
    method auth_headers (line 76) | def auth_headers(self) -> dict[str, str]:
    method __del__ (line 84) | def __del__(self) -> None:

FILE: zhipuai/api_resource/agents/agents.py
  class Agents (line 23) | class Agents(BaseAPI):
    method __init__ (line 25) | def __init__(self, client: "ZhipuAI") -> None:
    method invoke (line 28) | def invoke(
    method async_result (line 62) | def async_result(

FILE: zhipuai/api_resource/assistant/assistant.py
  class Assistant (line 28) | class Assistant(BaseAPI):
    method __init__ (line 30) | def __init__(self, client: "ZhipuAI") -> None:
    method conversation (line 33) | def conversation(
    method query_support (line 74) | def query_support(
    method query_conversation_usage (line 100) | def query_conversation_usage(

FILE: zhipuai/api_resource/audio/audio.py
  class Audio (line 31) | class Audio(BaseAPI):
    method transcriptions (line 34) | def transcriptions(self) -> Transcriptions:
    method __init__ (line 37) | def __init__(self, client: "ZhipuAI") -> None:
    method speech (line 40) | def speech(
    method customization (line 80) | def customization(

FILE: zhipuai/api_resource/audio/transcriptions.py
  class Transcriptions (line 28) | class Transcriptions(BaseAPI):
    method __init__ (line 29) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 32) | def create(

FILE: zhipuai/api_resource/batches.py
  class Batches (line 15) | class Batches(BaseAPI):
    method __init__ (line 17) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 20) | def create(
    method retrieve (line 51) | def retrieve(
    method list (line 79) | def list(
    method cancel (line 125) | def cancel(

FILE: zhipuai/api_resource/chat/async_completions.py
  class AsyncCompletions (line 22) | class AsyncCompletions(BaseAPI):
    method __init__ (line 23) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 26) | def create(
    method retrieve_completion_result (line 106) | def retrieve_completion_result(

FILE: zhipuai/api_resource/chat/chat.py
  class Chat (line 10) | class Chat(BaseAPI):
    method completions (line 13) | def completions(self) -> Completions:
    method asyncCompletions (line 17) | def asyncCompletions(self) -> AsyncCompletions:

FILE: zhipuai/api_resource/chat/completions.py
  class Completions (line 24) | class Completions(BaseAPI):
    method __init__ (line 25) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 28) | def create(

FILE: zhipuai/api_resource/embeddings.py
  class Embeddings (line 16) | class Embeddings(BaseAPI):
    method __init__ (line 17) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 20) | def create(

FILE: zhipuai/api_resource/file_parser/file_parser.py
  class FileParser (line 25) | class FileParser(BaseAPI):
    method __init__ (line 27) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 30) | def create(
    method content (line 67) | def content(

FILE: zhipuai/api_resource/files.py
  class Files (line 29) | class Files(BaseAPI):
    method __init__ (line 31) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 34) | def create(
    method list (line 103) | def list(
    method delete (line 130) | def delete(
    method content (line 159) | def content(
  class FilesWithRawResponse (line 189) | class FilesWithRawResponse:
    method __init__ (line 190) | def __init__(self, files: Files) -> None:

FILE: zhipuai/api_resource/fine_tuning/fine_tuning.py
  class FineTuning (line 10) | class FineTuning(BaseAPI):
    method jobs (line 13) | def jobs(self) -> Jobs:
    method models (line 17) | def models(self) -> FineTunedModels:

FILE: zhipuai/api_resource/fine_tuning/jobs/jobs.py
  class Jobs (line 25) | class Jobs(BaseAPI):
    method __init__ (line 27) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 30) | def create(
    method retrieve (line 59) | def retrieve(
    method list (line 75) | def list(
    method cancel (line 98) | def cancel(
    method list_events (line 119) | def list_events(
    method delete (line 144) | def delete(

FILE: zhipuai/api_resource/fine_tuning/models/fine_tuned_models.py
  class FineTunedModels (line 23) | class FineTunedModels(BaseAPI):
    method __init__ (line 25) | def __init__(self, client: "ZhipuAI") -> None:
    method delete (line 28) | def delete(

FILE: zhipuai/api_resource/images.py
  class Images (line 17) | class Images(BaseAPI):
    method __init__ (line 18) | def __init__(self, client: "ZhipuAI") -> None:
    method generations (line 21) | def generations(

FILE: zhipuai/api_resource/knowledge/document/document.py
  class Document (line 28) | class Document(BaseAPI):
    method __init__ (line 30) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 33) | def create(
    method edit (line 75) | def edit(
    method list (line 136) | def list(
    method delete (line 169) | def delete(
    method retrieve (line 200) | def retrieve(

FILE: zhipuai/api_resource/knowledge/knowledge.py
  class Knowledge (line 26) | class Knowledge(BaseAPI):
    method __init__ (line 28) | def __init__(self, client: "ZhipuAI") -> None:
    method document (line 32) | def document(self) -> Document:
    method create (line 35) | def create(
    method modify (line 70) | def modify(
    method query (line 103) | def query(
    method delete (line 129) | def delete(
    method used (line 159) | def used(

FILE: zhipuai/api_resource/moderation/moderations.py
  class Moderations (line 16) | class Moderations(BaseAPI):
    method __init__ (line 17) | def __init__(self, client: "ZhipuAI") -> None:
    method create (line 20) | def create(

FILE: zhipuai/api_resource/tools/tools.py
  class Tools (line 25) | class Tools(BaseAPI):
    method __init__ (line 27) | def __init__(self, client: "ZhipuAI") -> None:
    method web_search (line 30) | def web_search(

FILE: zhipuai/api_resource/videos/videos.py
  class Videos (line 26) | class Videos(BaseAPI):
    method __init__ (line 28) | def __init__(self, client: "ZhipuAI") -> None:
    method generations (line 31) | def generations(
    method retrieve_videos_result (line 76) | def retrieve_videos_result(

FILE: zhipuai/api_resource/web_search/web_search.py
  class WebSearchApi (line 25) | class WebSearchApi(BaseAPI):
    method __init__ (line 26) | def __init__(self, client: "ZhipuAI") -> None:
    method web_search (line 29) | def web_search(

FILE: zhipuai/core/_base_api.py
  class BaseAPI (line 8) | class BaseAPI:
    method __init__ (line 11) | def __init__(self, client: ZhipuAI) -> None:

FILE: zhipuai/core/_base_compat.py
  function parse_date (line 25) | def parse_date(value: date | StrBytesIntFloat) -> date:  # noqa: ARG001
  function parse_datetime (line 28) | def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime...
  function get_args (line 31) | def get_args(t: type[Any]) -> tuple[Any, ...]:  # noqa: ARG001
  function is_union (line 34) | def is_union(tp: type[Any] | None) -> bool:  # noqa: ARG001
  function get_origin (line 37) | def get_origin(t: type[Any]) -> type[Any] | None:  # noqa: ARG001
  function is_literal_type (line 40) | def is_literal_type(type_: type[Any]) -> bool:  # noqa: ARG001
  function is_typeddict (line 43) | def is_typeddict(type_: type[Any]) -> bool:  # noqa: ARG001
  function parse_obj (line 79) | def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
  function field_is_required (line 86) | def field_is_required(field: FieldInfo) -> bool:
  function field_get_default (line 92) | def field_get_default(field: FieldInfo) -> Any:
  function field_outer_type (line 103) | def field_outer_type(field: FieldInfo) -> Any:
  function get_model_config (line 109) | def get_model_config(model: type[pydantic.BaseModel]) -> Any:
  function get_model_fields (line 115) | def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, Field...
  function model_copy (line 121) | def model_copy(model: _ModelT) -> _ModelT:
  function model_json (line 127) | def model_json(model: pydantic.BaseModel, *, indent: int | None = None) ...
  function model_dump (line 133) | def model_dump(
  function model_parse (line 153) | def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
  class GenericModel (line 162) | class GenericModel(pydantic.BaseModel):
  class GenericModel (line 170) | class GenericModel(pydantic.BaseModel):
  class GenericModel (line 176) | class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel):
  class typed_cached_property (line 192) | class typed_cached_property(Generic[_T]):
    method __init__ (line 196) | def __init__(self, func: Callable[[Any], _T]) -> None:
    method __get__ (line 200) | def __get__(self, instance: None, owner: type[Any] | None = None) -> S...
    method __get__ (line 204) | def __get__(self, instance: object, owner: type[Any] | None = None) ->...
    method __get__ (line 207) | def __get__(self, instance: object, owner: type[Any] | None = None) ->...
    method __set_name__ (line 210) | def __set_name__(self, owner: type[Any], name: str) -> None:
    method __set__ (line 214) | def __set__(self, instance: object, value: _T) -> None:

FILE: zhipuai/core/_base_models.py
  class _ConfigProtocol (line 50) | class _ConfigProtocol(Protocol):
  class BaseModel (line 54) | class BaseModel(pydantic.BaseModel):
    method model_fields_set (line 63) | def model_fields_set(self) -> set[str]:
    class Config (line 67) | class Config(pydantic.BaseConfig):  # pyright: ignore[reportDeprecated]
    method to_dict (line 70) | def to_dict(
    method to_json (line 108) | def to_json(
    method __str__ (line 144) | def __str__(self) -> str:
    method construct (line 152) | def construct(
    method model_dump (line 220) | def model_dump(
    method model_dump_json (line 275) | def model_dump_json(
  function _construct_field (line 327) | def _construct_field(value: object, field: FieldInfo, key: str) -> object:
  function is_basemodel (line 342) | def is_basemodel(type_: type) -> bool:
  function is_basemodel_type (line 354) | def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[G...
  function build (line 359) | def build(
  function construct_type_unchecked (line 382) | def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T:
  function construct_type (line 391) | def construct_type(*, value: object, type_: type) -> object:
  class CachedDiscriminatorType (line 496) | class CachedDiscriminatorType(Protocol):
  class DiscriminatorDetails (line 500) | class DiscriminatorDetails:
    method __init__ (line 529) | def __init__(
  function _build_discriminated_union_meta (line 541) | def _build_discriminated_union_meta(*, union: type, meta_annotations: tu...
  function _extract_field_schema_pv2 (line 601) | def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -...
  function validate_type (line 619) | def validate_type(*, type_: type[_T], value: object) -> _T:
  class GenericModel (line 633) | class GenericModel(BaseGenericModel, BaseModel):
  function _validate_non_model_type (line 640) | def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
  class TypeAdapter (line 645) | class TypeAdapter(Generic[_T]):
    method __init__ (line 656) | def __init__(self, type_: Type[_T]):
    method validate_python (line 659) | def validate_python(self, value: Any) -> _T:
  function _validate_non_model_type (line 665) | def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:

FILE: zhipuai/core/_base_type.py
  class NotGiven (line 38) | class NotGiven:
    method __bool__ (line 54) | def __bool__(self) -> Literal[False]:
    method __repr__ (line 58) | def __repr__(self) -> str:
  class Omit (line 66) | class Omit:
    method __bool__ (line 83) | def __bool__(self) -> Literal[False]:
  class ModelBuilderProtocol (line 88) | class ModelBuilderProtocol(Protocol):
    method build (line 90) | def build(
  class HeadersLikeProtocol (line 102) | class HeadersLikeProtocol(Protocol):
    method get (line 103) | def get(self, __key: str) -> str | None:
  class InheritsGeneric (line 124) | class InheritsGeneric(Protocol):
  class _GenericAlias (line 134) | class _GenericAlias(Protocol):
  class HttpxSendArgs (line 138) | class HttpxSendArgs(TypedDict, total=False):

FILE: zhipuai/core/_errors.py
  class ZhipuAIError (line 20) | class ZhipuAIError(Exception):
    method __init__ (line 21) | def __init__(self, message: str, ) -> None:
  class APIStatusError (line 25) | class APIStatusError(ZhipuAIError):
    method __init__ (line 29) | def __init__(self, message: str, *, response: httpx.Response) -> None:
  class APIRequestFailedError (line 35) | class APIRequestFailedError(APIStatusError):
  class APIAuthenticationError (line 39) | class APIAuthenticationError(APIStatusError):
  class APIReachLimitError (line 43) | class APIReachLimitError(APIStatusError):
  class APIInternalError (line 47) | class APIInternalError(APIStatusError):
  class APIServerFlowExceedError (line 51) | class APIServerFlowExceedError(APIStatusError):
  class APIResponseError (line 55) | class APIResponseError(ZhipuAIError):
    method __init__ (line 60) | def __init__(self, message: str, request: httpx.Request, json_data: ob...
  class APIResponseValidationError (line 67) | class APIResponseValidationError(APIResponseError):
    method __init__ (line 71) | def __init__(
  class APIConnectionError (line 86) | class APIConnectionError(APIResponseError):
    method __init__ (line 87) | def __init__(self, *, message: str = "Connection error.", request: htt...
  class APITimeoutError (line 91) | class APITimeoutError(APIConnectionError):
    method __init__ (line 92) | def __init__(self, request: httpx.Request) -> None:

FILE: zhipuai/core/_files.py
  function is_base64_file_input (line 19) | def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]:
  function is_file_content (line 23) | def is_file_content(obj: object) -> TypeGuard[FileContent]:
  function assert_is_file_content (line 30) | def assert_is_file_content(obj: object, *, key: str | None = None) -> None:
  function to_httpx_files (line 39) | def to_httpx_files(files: None) -> None:
  function to_httpx_files (line 44) | def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles:
  function to_httpx_files (line 48) | def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None:
  function _transform_file (line 62) | def _transform_file(file: FileTypes) -> HttpxFileTypes:
  function _read_file_content (line 76) | def _read_file_content(file: FileContent) -> HttpxFileContent:

FILE: zhipuai/core/_http_client.py
  class PageInfo (line 78) | class PageInfo:
    method __init__ (line 88) | def __init__(
    method __init__ (line 96) | def __init__(
    method __init__ (line 103) | def __init__(
  class BasePage (line 113) | class BasePage(GenericModel, Generic[_T]):
    method has_next_page (line 128) | def has_next_page(self) -> bool:
    method next_page_info (line 134) | def next_page_info(self) -> Optional[PageInfo]:
    method _get_page_items (line 137) | def _get_page_items(self) -> Iterable[_T]:  # type: ignore[empty-body]
    method _params_from_url (line 140) | def _params_from_url(self, url: URL) -> httpx.QueryParams:
    method _info_to_options (line 144) | def _info_to_options(self, info: PageInfo) -> FinalRequestOptions:
  class BaseSyncPage (line 162) | class BaseSyncPage(BasePage[_T], Generic[_T]):
    method _set_private_attributes (line 165) | def _set_private_attributes(
    method __iter__ (line 183) | def __iter__(self) -> Iterator[_T]:  # type: ignore
    method iter_pages (line 188) | def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]:
    method get_next_page (line 197) | def get_next_page(self: SyncPageT) -> SyncPageT:
  class HttpClient (line 208) | class HttpClient:
    method __init__ (line 220) | def __init__(
    method _prepare_url (line 265) | def _prepare_url(self, url: str) -> URL:
    method _default_headers (line 275) | def _default_headers(self):
    method custom_auth (line 288) | def custom_auth(self) -> httpx.Auth | None:
    method auth_headers (line 292) | def auth_headers(self):
    method _prepare_headers (line 295) | def _prepare_headers(self, options: FinalRequestOptions) -> httpx.Head...
    method _remaining_retries (line 303) | def _remaining_retries(
    method _calculate_retry_timeout (line 310) | def _calculate_retry_timeout(
    method _build_request (line 333) | def _build_request(
    method _object_to_formfata (line 371) | def _object_to_formfata(self, key: str, value: Data | Mapping[object, ...
    method _make_multipartform (line 399) | def _make_multipartform(self, data: Mapping[object, object]) -> dict[s...
    method _process_response_data (line 411) | def _process_response_data(
    method _should_stream_response_body (line 436) | def _should_stream_response_body(self, request: httpx.Request) -> bool:
    method _should_retry (line 439) | def _should_retry(self, response: httpx.Response) -> bool:
    method is_closed (line 474) | def is_closed(self) -> bool:
    method close (line 477) | def close(self):
    method __enter__ (line 480) | def __enter__(self):
    method __exit__ (line 483) | def __exit__(self, exc_type, exc_val, exc_tb):
    method request (line 486) | def request(
    method _request (line 503) | def _request(
    method _retry_request (line 599) | def _retry_request(
    method _process_response (line 630) | def _process_response(
    method _request_api_list (line 688) | def _request_api_list(
    method get (line 707) | def get(
    method get (line 718) | def get(
    method get (line 730) | def get(
    method get (line 741) | def get(
    method post (line 754) | def post(
    method post (line 767) | def post(
    method post (line 781) | def post(
    method post (line 794) | def post(
    method patch (line 811) | def patch(
    method put (line 825) | def put(
    method delete (line 841) | def delete(
    method get_api_list (line 855) | def get_api_list(
    method _make_status_error (line 868) | def _make_status_error(self, response) -> APIStatusError:
  function make_request_options (line 886) | def make_request_options(
  function _merge_mappings (line 919) | def _merge_mappings(

FILE: zhipuai/core/_jwt_token.py
  function generate_token (line 15) | def generate_token(apikey: str):

FILE: zhipuai/core/_legacy_binary_response.py
  class HttpxResponseContent (line 8) | class HttpxResponseContent:
    method content (line 11) | def content(self) -> bytes:
    method text (line 15) | def text(self) -> str:
    method encoding (line 19) | def encoding(self) -> str | None:
    method charset_encoding (line 23) | def charset_encoding(self) -> str | None:
    method json (line 26) | def json(self, **kwargs: Any) -> Any:
    method read (line 29) | def read(self) -> bytes:
    method iter_bytes (line 32) | def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
    method iter_text (line 35) | def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
    method iter_lines (line 38) | def iter_lines(self) -> Iterator[str]:
    method iter_raw (line 41) | def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]:
    method write_to_file (line 44) | def write_to_file(
    method stream_to_file (line 50) | def stream_to_file(
    method close (line 58) | def close(self) -> None:
    method aread (line 61) | async def aread(self) -> bytes:
    method aiter_bytes (line 64) | async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIte...
    method aiter_text (line 67) | async def aiter_text(self, chunk_size: int | None = None) -> AsyncIter...
    method aiter_lines (line 70) | async def aiter_lines(self) -> AsyncIterator[str]:
    method aiter_raw (line 73) | async def aiter_raw(self, chunk_size: int | None = None) -> AsyncItera...
    method astream_to_file (line 76) | async def astream_to_file(
    method aclose (line 84) | async def aclose(self) -> None:
  class HttpxBinaryResponseContent (line 88) | class HttpxBinaryResponseContent(HttpxResponseContent):
    method __init__ (line 91) | def __init__(self, response: httpx.Response) -> None:
    method content (line 95) | def content(self) -> bytes:
    method encoding (line 99) | def encoding(self) -> str | None:
    method charset_encoding (line 103) | def charset_encoding(self) -> str | None:
    method read (line 106) | def read(self) -> bytes:
    method text (line 109) | def text(self) -> str:
    method json (line 112) | def json(self, **kwargs: Any) -> Any:
    method iter_text (line 115) | def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
    method iter_lines (line 119) | def iter_lines(self) -> Iterator[str]:
    method aiter_text (line 123) | async def aiter_text(self, chunk_size: int | None = None) -> AsyncIter...
    method aiter_lines (line 126) | async def aiter_lines(self) -> AsyncIterator[str]:
    method iter_bytes (line 129) | def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
    method iter_raw (line 132) | def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]:
    method write_to_file (line 135) | def write_to_file(
    method stream_to_file (line 151) | def stream_to_file(
    method close (line 161) | def close(self) -> None:
    method aread (line 164) | async def aread(self) -> bytes:
    method aiter_bytes (line 167) | async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIte...
    method aiter_raw (line 170) | async def aiter_raw(self, chunk_size: int | None = None) -> AsyncItera...
    method astream_to_file (line 173) | async def astream_to_file(
    method aclose (line 184) | async def aclose(self) -> None:
  class HttpxTextBinaryResponseContent (line 188) | class HttpxTextBinaryResponseContent(HttpxBinaryResponseContent):
    method text (line 192) | def text(self) -> str:
    method json (line 195) | def json(self, **kwargs: Any) -> Any:
    method iter_text (line 198) | def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
    method iter_lines (line 201) | def iter_lines(self) -> Iterator[str]:
    method aiter_text (line 204) | async def aiter_text(self, chunk_size: int | None = None) -> AsyncIter...
    method aiter_lines (line 207) | async def aiter_lines(self) -> AsyncIterator[str]:

FILE: zhipuai/core/_legacy_response.py
  class LegacyAPIResponse (line 35) | class LegacyAPIResponse(Generic[R]):
    method __init__ (line 57) | def __init__(
    method request_id (line 76) | def request_id(self) -> str | None:
    method parse (line 80) | def parse(self, *, to: type[_T]) -> _T:
    method parse (line 84) | def parse(self) -> R:
    method parse (line 87) | def parse(self, *, to: type[_T] | None = None) -> R | _T:
    method headers (line 132) | def headers(self) -> httpx.Headers:
    method http_request (line 136) | def http_request(self) -> httpx.Request:
    method status_code (line 140) | def status_code(self) -> int:
    method url (line 144) | def url(self) -> httpx.URL:
    method method (line 148) | def method(self) -> str:
    method content (line 152) | def content(self) -> bytes:
    method text (line 161) | def text(self) -> str:
    method http_version (line 169) | def http_version(self) -> str:
    method is_closed (line 173) | def is_closed(self) -> bool:
    method elapsed (line 177) | def elapsed(self) -> datetime.timedelta:
    method _parse (line 181) | def _parse(self, *, to: type[_T] | None = None) -> R | _T:
    method __repr__ (line 323) | def __repr__(self) -> str:
  class MissingStreamClassError (line 327) | class MissingStreamClassError(TypeError):
    method __init__ (line 328) | def __init__(self) -> None:
  function to_raw_response_wrapper (line 334) | def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, LegacyA...

FILE: zhipuai/core/_request_opt.py
  class UserRequestInput (line 19) | class UserRequestInput(TypedDict, total=False):
  class FinalRequestOptionsInput (line 27) | class FinalRequestOptionsInput(TypedDict, total=False):
  class FinalRequestOptions (line 40) | class FinalRequestOptions(pydantic.BaseModel):
    class Config (line 60) | class Config(pydantic.BaseConfig):  # pyright: ignore[reportDeprecated]
    method get_max_retries (line 63) | def get_max_retries(self, max_retries: int) -> int:
    method _strip_raw_response_header (line 68) | def _strip_raw_response_header(self) -> None:
    method construct (line 83) | def construct(  # type: ignore

FILE: zhipuai/core/_response.py
  class BaseAPIResponse (line 29) | class BaseAPIResponse(Generic[R]):
    method __init__ (line 38) | def __init__(
    method _parse (line 56) | def _parse(self, *, to: type[_T] | None = None) -> R | _T:
    method headers (line 193) | def headers(self) -> httpx.Headers:
    method http_request (line 197) | def http_request(self) -> httpx.Request:
    method status_code (line 202) | def status_code(self) -> int:
    method url (line 206) | def url(self) -> httpx.URL:
    method method (line 211) | def method(self) -> str:
    method http_version (line 215) | def http_version(self) -> str:
    method elapsed (line 219) | def elapsed(self) -> datetime.timedelta:
    method is_closed (line 224) | def is_closed(self) -> bool:
    method __repr__ (line 234) | def __repr__(self) -> str:
  class APIResponse (line 240) | class APIResponse(BaseAPIResponse[R]):
    method request_id (line 243) | def request_id(self) -> str | None:
    method parse (line 247) | def parse(self, *, to: type[_T]) -> _T:
    method parse (line 251) | def parse(self) -> R:
    method parse (line 254) | def parse(self, *, to: type[_T] | None = None) -> R | _T:
    method read (line 299) | def read(self) -> bytes:
    method text (line 309) | def text(self) -> str:
    method json (line 314) | def json(self) -> object:
    method close (line 319) | def close(self) -> None:
    method iter_bytes (line 326) | def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
    method iter_text (line 335) | def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
    method iter_lines (line 343) | def iter_lines(self) -> Iterator[str]:
  class MissingStreamClassError (line 349) | class MissingStreamClassError(TypeError):
    method __init__ (line 350) | def __init__(self) -> None:
  class StreamAlreadyConsumed (line 356) | class StreamAlreadyConsumed(ZhipuAIError):
    method __init__ (line 377) | def __init__(self) -> None:
  function extract_response_type (line 390) | def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type:

FILE: zhipuai/core/_sse_client.py
  class StreamResponse (line 22) | class StreamResponse(Generic[ResponseT]):
    method __init__ (line 26) | def __init__(
    method __next__ (line 38) | def __next__(self) -> ResponseT:
    method __iter__ (line 41) | def __iter__(self) -> Iterator[ResponseT]:
    method __stream__ (line 45) | def __stream__(self) -> Iterator[ResponseT]:
  class Event (line 114) | class Event(object):
    method __init__ (line 115) | def __init__(
    method __repr__ (line 127) | def __repr__(self):
    method event (line 132) | def event(self):
    method data (line 136) | def data(self):
    method json_data (line 139) | def json_data(self):
    method id (line 143) | def id(self):
    method retry (line 147) | def retry(self):
  class SSELineParser (line 151) | class SSELineParser:
    method __init__ (line 157) | def __init__(self):
    method iter_lines (line 163) | def iter_lines(self, lines: Iterator[str]) -> Iterator[Event]:
    method decode_line (line 188) | def decode_line(self, line: str):
  function is_stream_class_type (line 208) | def is_stream_class_type(typ: type) -> TypeGuard[type[StreamResponse[obj...
  function extract_stream_chunk_type (line 214) | def extract_stream_chunk_type(

FILE: zhipuai/core/_utils/_transform.py
  class PropertyInfo (line 40) | class PropertyInfo:
    method __init__ (line 56) | def __init__(
    method __repr__ (line 70) | def __repr__(self) -> str:
  function maybe_transform (line 74) | def maybe_transform(
  function transform (line 88) | def transform(
  function _get_annotated_type (line 111) | def _get_annotated_type(type_: type) -> type | None:
  function _maybe_transform_key (line 126) | def _maybe_transform_key(key: str, type_: type) -> str:
  function _transform_recursive (line 145) | def _transform_recursive(
  function _format_data (line 204) | def _format_data(data: object, format_: PropertyFormat, format_template:...
  function _transform_typeddict (line 231) | def _transform_typeddict(
  function async_maybe_transform (line 247) | async def async_maybe_transform(
  function async_transform (line 260) | async def async_transform(
  function _async_transform_recursive (line 283) | async def _async_transform_recursive(
  function _async_format_data (line 342) | async def _async_format_data(data: object, format_: PropertyFormat, form...
  function _async_transform_typeddict (line 369) | async def _async_transform_typeddict(

FILE: zhipuai/core/_utils/_typing.py
  function is_annotated_type (line 11) | def is_annotated_type(typ: type) -> bool:
  function is_list_type (line 15) | def is_list_type(typ: type) -> bool:
  function is_iterable_type (line 19) | def is_iterable_type(typ: type) -> bool:
  function is_union_type (line 25) | def is_union_type(typ: type) -> bool:
  function is_required_type (line 29) | def is_required_type(typ: type) -> bool:
  function is_typevar (line 33) | def is_typevar(typ: type) -> bool:
  function strip_annotated_type (line 40) | def strip_annotated_type(typ: type) -> type:
  function extract_type_arg (line 47) | def extract_type_arg(typ: type, index: int) -> type:
  function extract_type_var_from_base (line 55) | def extract_type_var_from_base(

FILE: zhipuai/core/_utils/_utils.py
  function remove_notgiven_indict (line 27) | def remove_notgiven_indict(obj):
  function flatten (line 40) | def flatten(t: Iterable[Iterable[_T]]) -> list[_T]:
  function extract_files (line 44) | def extract_files(
  function _extract_items (line 63) | def _extract_items(
  function is_given (line 128) | def is_given(obj: NotGivenOr[_T]) -> TypeGuard[_T]:
  function is_tuple (line 142) | def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]:
  function is_tuple_t (line 146) | def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]:
  function is_sequence (line 150) | def is_sequence(obj: object) -> TypeGuard[Sequence[object]]:
  function is_sequence_t (line 154) | def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]:
  function is_mapping (line 158) | def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]:
  function is_mapping_t (line 162) | def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]:
  function is_dict (line 166) | def is_dict(obj: object) -> TypeGuard[dict[object, object]]:
  function is_list (line 170) | def is_list(obj: object) -> TypeGuard[list[object]]:
  function is_iterable (line 174) | def is_iterable(obj: object) -> TypeGuard[Iterable[object]]:
  function deepcopy_minimal (line 178) | def deepcopy_minimal(item: _T) -> _T:
  function human_join (line 194) | def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "o...
  function quote (line 208) | def quote(string: str) -> str:
  function required_args (line 213) | def required_args(*variants: Sequence[str]) -> Callable[[CallableT], Cal...
  function strip_not_given (line 294) | def strip_not_given(obj: None) -> None:
  function strip_not_given (line 299) | def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]:
  function strip_not_given (line 304) | def strip_not_given(obj: object) -> object:
  function strip_not_given (line 308) | def strip_not_given(obj: object | None) -> object:
  function coerce_integer (line 319) | def coerce_integer(val: str) -> int:
  function coerce_float (line 323) | def coerce_float(val: str) -> float:
  function coerce_boolean (line 327) | def coerce_boolean(val: str) -> bool:
  function maybe_coerce_integer (line 331) | def maybe_coerce_integer(val: str | None) -> int | None:
  function maybe_coerce_float (line 337) | def maybe_coerce_float(val: str | None) -> float | None:
  function maybe_coerce_boolean (line 343) | def maybe_coerce_boolean(val: str | None) -> bool | None:
  function removeprefix (line 349) | def removeprefix(string: str, prefix: str) -> str:
  function removesuffix (line 359) | def removesuffix(string: str, suffix: str) -> str:
  function file_from_path (line 369) | def file_from_path(path: str) -> FileTypes:
  function get_required_header (line 375) | def get_required_header(headers: HeadersLike, header: str) -> str:
  function get_async_library (line 394) | def get_async_library() -> str:
  function drop_prefix_image_data (line 401) | def drop_prefix_image_data(content: Union[str, List[dict]]) -> Union[str...

FILE: zhipuai/core/logs.py
  class LoggerNameFilter (line 8) | class LoggerNameFilter(logging.Filter):
    method filter (line 9) | def filter(self, record):
  function get_log_file (line 17) | def get_log_file(log_path: str, sub_dir: str):
  function get_config_dict (line 27) | def get_config_dict(
  function get_timestamp_ms (line 86) | def get_timestamp_ms():

FILE: zhipuai/core/pagination.py
  class CursorPageItem (line 14) | class CursorPageItem(Protocol):
  class SyncPage (line 18) | class SyncPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
    method _get_page_items (line 25) | def _get_page_items(self) -> List[_T]:
    method next_page_info (line 32) | def next_page_info(self) -> None:
  class SyncCursorPage (line 40) | class SyncCursorPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
    method _get_page_items (line 44) | def _get_page_items(self) -> List[_T]:
    method next_page_info (line 51) | def next_page_info(self) -> Optional[PageInfo]:

FILE: zhipuai/types/agents/agents_completion.py
  class AgentsCompletionMessage (line 7) | class AgentsCompletionMessage(BaseModel):
  class AgentsCompletionUsage (line 11) | class AgentsCompletionUsage(BaseModel):
  class AgentsCompletionChoice (line 17) | class AgentsCompletionChoice(BaseModel):
  class AgentsError (line 22) | class AgentsError(BaseModel):
  class AgentsCompletion (line 27) | class AgentsCompletion(BaseModel):

FILE: zhipuai/types/agents/agents_completion_chunk.py
  class AgentsChoiceDelta (line 13) | class AgentsChoiceDelta(BaseModel):
  class AgentsChoice (line 18) | class AgentsChoice(BaseModel):
  class AgentsCompletionUsage (line 24) | class AgentsCompletionUsage(BaseModel):
  class AgentsError (line 29) | class AgentsError(BaseModel):
  class AgentsCompletionChunk (line 34) | class AgentsCompletionChunk(BaseModel):

FILE: zhipuai/types/agents/chat_completions_create_param.py
  class Reference (line 6) | class Reference(TypedDict, total=False):

FILE: zhipuai/types/assistant/assistant_completion.py
  class ErrorInfo (line 9) | class ErrorInfo(BaseModel):
  class AssistantChoice (line 14) | class AssistantChoice(BaseModel):
  class CompletionUsage (line 25) | class CompletionUsage(BaseModel):
  class AssistantCompletion (line 31) | class AssistantCompletion(BaseModel):

FILE: zhipuai/types/assistant/assistant_conversation_params.py
  class ConversationParameters (line 4) | class ConversationParameters(TypedDict, total=False):

FILE: zhipuai/types/assistant/assistant_conversation_resp.py
  class Usage (line 9) | class Usage(BaseModel):
  class ConversationUsage (line 15) | class ConversationUsage(BaseModel):
  class ConversationUsageList (line 23) | class ConversationUsageList(BaseModel):
  class ConversationUsageListResp (line 29) | class ConversationUsageListResp(BaseModel):

FILE: zhipuai/types/assistant/assistant_create_params.py
  class AssistantAttachments (line 4) | class AssistantAttachments:
  class MessageTextContent (line 8) | class MessageTextContent:
  class ConversationMessage (line 16) | class ConversationMessage(TypedDict):
  class AssistantParameters (line 22) | class AssistantParameters(TypedDict, total=False):
  class TranslateParameters (line 32) | class TranslateParameters(TypedDict, total=False):
  class ExtraParameters (line 36) | class ExtraParameters(TypedDict, total=False):

FILE: zhipuai/types/assistant/assistant_support_resp.py
  class AssistantSupport (line 11) | class AssistantSupport(BaseModel):
  class AssistantSupportResp (line 23) | class AssistantSupportResp(BaseModel):

FILE: zhipuai/types/assistant/message/text_content_block.py
  class TextContentBlock (line 8) | class TextContentBlock(BaseModel):

FILE: zhipuai/types/assistant/message/tools/code_interpreter_delta_block.py
  class CodeInterpreterToolOutput (line 10) | class CodeInterpreterToolOutput(BaseModel):
  class CodeInterpreter (line 17) | class CodeInterpreter(BaseModel):
  class CodeInterpreterToolBlock (line 23) | class CodeInterpreterToolBlock(BaseModel):

FILE: zhipuai/types/assistant/message/tools/drawing_tool_delta_block.py
  class DrawingToolOutput (line 10) | class DrawingToolOutput(BaseModel):
  class DrawingTool (line 14) | class DrawingTool(BaseModel):
  class DrawingToolBlock (line 19) | class DrawingToolBlock(BaseModel):

FILE: zhipuai/types/assistant/message/tools/function_delta_block.py
  class FunctionToolOutput (line 10) | class FunctionToolOutput(BaseModel):
  class FunctionTool (line 14) | class FunctionTool(BaseModel):
  class FunctionToolBlock (line 20) | class FunctionToolBlock(BaseModel):

FILE: zhipuai/types/assistant/message/tools/retrieval_delta_black.py
  class RetrievalToolOutput (line 8) | class RetrievalToolOutput(BaseModel):
  class RetrievalTool (line 20) | class RetrievalTool(BaseModel):
  class RetrievalToolBlock (line 30) | class RetrievalToolBlock(BaseModel):

FILE: zhipuai/types/assistant/message/tools/web_browser_delta_block.py
  class WebBrowserOutput (line 9) | class WebBrowserOutput(BaseModel):
  class WebBrowser (line 25) | class WebBrowser(BaseModel):
  class WebBrowserToolBlock (line 37) | class WebBrowserToolBlock(BaseModel):

FILE: zhipuai/types/assistant/message/tools_delta_block.py
  class ToolsDeltaBlock (line 10) | class ToolsDeltaBlock(BaseModel):

FILE: zhipuai/types/audio/audio_customization_param.py
  class AudioCustomizationParam (line 10) | class AudioCustomizationParam(TypedDict, total=False):

FILE: zhipuai/types/audio/audio_speech_chunk.py
  class AudioSpeechDelta (line 13) | class AudioSpeechDelta(BaseModel):
  class AudioSpeechChoice (line 18) | class AudioSpeechChoice(BaseModel):
  class AudioError (line 23) | class AudioError(BaseModel):
  class AudioSpeechChunk (line 28) | class AudioSpeechChunk(BaseModel):

FILE: zhipuai/types/audio/audio_speech_params.py
  class AudioSpeechParams (line 12) | class AudioSpeechParams(TypedDict, total=False):

FILE: zhipuai/types/audio/transcriptions_create_param.py
  class TranscriptionsParam (line 10) | class TranscriptionsParam(TypedDict, total=False):

FILE: zhipuai/types/batch.py
  class Errors (line 14) | class Errors(BaseModel):
  class Batch (line 21) | class Batch(BaseModel):

FILE: zhipuai/types/batch_create_params.py
  class BatchCreateParams (line 9) | class BatchCreateParams(TypedDict, total=False):

FILE: zhipuai/types/batch_error.py
  class BatchError (line 10) | class BatchError(BaseModel):

FILE: zhipuai/types/batch_list_params.py
  class BatchListParams (line 8) | class BatchListParams(TypedDict, total=False):

FILE: zhipuai/types/batch_request_counts.py
  class BatchRequestCounts (line 6) | class BatchRequestCounts(BaseModel):

FILE: zhipuai/types/chat/async_chat_completion.py
  class AsyncTaskStatus (line 9) | class AsyncTaskStatus(BaseModel):
  class AsyncCompletion (line 16) | class AsyncCompletion(BaseModel):

FILE: zhipuai/types/chat/chat_completion.py
  class Function (line 8) | class Function(BaseModel):
  class CompletionMessageToolCall (line 13) | class CompletionMessageToolCall(BaseModel):
  class CompletionMessage (line 19) | class CompletionMessage(BaseModel):
  class CompletionUsage (line 26) | class CompletionUsage(BaseModel):
  class CompletionChoice (line 32) | class CompletionChoice(BaseModel):
  class Completion (line 38) | class Completion(BaseModel):

FILE: zhipuai/types/chat/chat_completion_chunk.py
  class ChoiceDeltaFunctionCall (line 17) | class ChoiceDeltaFunctionCall(BaseModel):
  class ChoiceDeltaToolCallFunction (line 22) | class ChoiceDeltaToolCallFunction(BaseModel):
  class ChoiceDeltaToolCall (line 27) | class ChoiceDeltaToolCall(BaseModel):
  class AudioCompletionChunk (line 33) | class AudioCompletionChunk(BaseModel):
  class ChoiceDelta (line 39) | class ChoiceDelta(BaseModel):
  class Choice (line 47) | class Choice(BaseModel):
  class PromptTokensDetails (line 52) | class PromptTokensDetails(BaseModel):
  class CompletionTokensDetails (line 55) | class CompletionTokensDetails(BaseModel):
  class CompletionUsage (line 58) | class CompletionUsage(BaseModel):
  class ChatCompletionChunk (line 65) | class ChatCompletionChunk(BaseModel):

FILE: zhipuai/types/chat/chat_completions_create_param.py
  class Reference (line 6) | class Reference(TypedDict, total=False):

FILE: zhipuai/types/chat/code_geex/code_geex_params.py
  class CodeGeexTarget (line 11) | class CodeGeexTarget(TypedDict, total=False):
  class CodeGeexContext (line 39) | class CodeGeexContext(TypedDict, total=False):
  class CodeGeexExtra (line 47) | class CodeGeexExtra(TypedDict, total=False):

FILE: zhipuai/types/embeddings.py
  class Embedding (line 10) | class Embedding(BaseModel):
  class EmbeddingsResponded (line 16) | class EmbeddingsResponded(BaseModel):

FILE: zhipuai/types/file_parser/file_parser_create_params.py
  class FileParserCreateParams (line 10) | class FileParserCreateParams(TypedDict):
  class FileParserDownloadParams (line 19) | class FileParserDownloadParams(TypedDict):

FILE: zhipuai/types/file_parser/file_parser_resp.py
  class FileParserTaskCreateResp (line 10) | class FileParserTaskCreateResp(BaseModel):

FILE: zhipuai/types/files/file_create_params.py
  class FileCreateParams (line 15) | class FileCreateParams(TypedDict, total=False):

FILE: zhipuai/types/files/file_deleted.py
  class FileDeleted (line 8) | class FileDeleted(BaseModel):

FILE: zhipuai/types/files/file_object.py
  class FileObject (line 8) | class FileObject(BaseModel):
  class ListOfFileObject (line 20) | class ListOfFileObject(BaseModel):

FILE: zhipuai/types/files/upload_detail.py
  class UploadDetail (line 6) | class UploadDetail(BaseModel):

FILE: zhipuai/types/fine_tuning/fine_tuning_job.py
  class Error (line 8) | class Error(BaseModel):
  class Hyperparameters (line 14) | class Hyperparameters(BaseModel):
  class FineTuningJob (line 18) | class FineTuningJob(BaseModel):
  class ListOfFineTuningJob (line 48) | class ListOfFineTuningJob(BaseModel):

FILE: zhipuai/types/fine_tuning/fine_tuning_job_event.py
  class Metric (line 8) | class Metric(BaseModel):
  class JobEvent (line 22) | class JobEvent(BaseModel):
  class FineTuningJobEvent (line 32) | class FineTuningJobEvent(BaseModel):

FILE: zhipuai/types/fine_tuning/job_create_params.py
  class Hyperparameters (line 10) | class Hyperparameters(TypedDict, total=False):

FILE: zhipuai/types/fine_tuning/models/fine_tuned_models.py
  class FineTunedModelsStatus (line 8) | class FineTunedModelsStatus(BaseModel):

FILE: zhipuai/types/image.py
  class GeneratedImage (line 10) | class GeneratedImage(BaseModel):
  class ImagesResponded (line 16) | class ImagesResponded(BaseModel):

FILE: zhipuai/types/knowledge/document/document.py
  class DocumentSuccessinfo (line 8) | class DocumentSuccessinfo(BaseModel):
  class DocumentFailedInfo (line 15) | class DocumentFailedInfo(BaseModel):
  class DocumentObject (line 24) | class DocumentObject(BaseModel):
  class DocumentDataFailInfo (line 33) | class DocumentDataFailInfo(BaseModel):
  class DocumentData (line 40) | class DocumentData(BaseModel):

FILE: zhipuai/types/knowledge/document/document_edit_params.py
  class DocumentEditParams (line 7) | class DocumentEditParams(TypedDict):

FILE: zhipuai/types/knowledge/document/document_list_params.py
  class DocumentListParams (line 7) | class DocumentListParams(TypedDict, total=False):

FILE: zhipuai/types/knowledge/document/document_list_resp.py
  class DocumentPage (line 13) | class DocumentPage(BaseModel):

FILE: zhipuai/types/knowledge/knowledge.py
  class KnowledgeInfo (line 9) | class KnowledgeInfo(BaseModel):

FILE: zhipuai/types/knowledge/knowledge_create_params.py
  class KnowledgeBaseParams (line 9) | class KnowledgeBaseParams(TypedDict):

FILE: zhipuai/types/knowledge/knowledge_list_params.py
  class KnowledgeListParams (line 9) | class KnowledgeListParams(TypedDict, total=False):

FILE: zhipuai/types/knowledge/knowledge_list_resp.py
  class KnowledgePage (line 13) | class KnowledgePage(BaseModel):

FILE: zhipuai/types/knowledge/knowledge_used.py
  class KnowledgeStatistics (line 13) | class KnowledgeStatistics(BaseModel):
  class KnowledgeUsed (line 21) | class KnowledgeUsed(BaseModel):

FILE: zhipuai/types/moderation/moderation_completion.py
  class Completion (line 7) | class Completion(BaseModel):

FILE: zhipuai/types/sensitive_word_check/sensitive_word_check.py
  class SensitiveWordCheckRequest (line 6) | class SensitiveWordCheckRequest(TypedDict, total=False):

FILE: zhipuai/types/tools/tools_web_search_params.py
  class WebSearchParams (line 10) | class WebSearchParams(TypedDict):

FILE: zhipuai/types/tools/web_search.py
  class SearchIntent (line 14) | class SearchIntent(BaseModel):
  class SearchResult (line 25) | class SearchResult(BaseModel):
  class SearchRecommend (line 42) | class SearchRecommend(BaseModel):
  class WebSearchMessageToolCall (line 49) | class WebSearchMessageToolCall(BaseModel):
  class WebSearchMessage (line 57) | class WebSearchMessage(BaseModel):
  class WebSearchChoice (line 62) | class WebSearchChoice(BaseModel):
  class WebSearch (line 68) | class WebSearch(BaseModel):

FILE: zhipuai/types/tools/web_search_chunk.py
  class ChoiceDeltaToolCall (line 11) | class ChoiceDeltaToolCall(BaseModel):
  class ChoiceDelta (line 21) | class ChoiceDelta(BaseModel):
  class Choice (line 26) | class Choice(BaseModel):
  class WebSearchChunk (line 32) | class WebSearchChunk(BaseModel):

FILE: zhipuai/types/video/video_create_params.py
  class VideoCreateParams (line 12) | class VideoCreateParams(TypedDict, total=False):

FILE: zhipuai/types/video/video_object.py
  class VideoResult (line 8) | class VideoResult(BaseModel):
  class VideoObject (line 15) | class VideoObject(BaseModel):

FILE: zhipuai/types/web_search/web_search_create_params.py
  class WebSearchCreatParams (line 12) | class WebSearchCreatParams(TypedDict):

FILE: zhipuai/types/web_search/web_search_resp.py
  class SearchIntentResp (line 11) | class SearchIntentResp(BaseModel):
  class SearchResultResp (line 20) | class SearchResultResp(BaseModel):
  class WebSearchResp (line 36) | class WebSearchResp(BaseModel):
Condensed preview — 195 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (465K chars).
[
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report.yml",
    "chars": 1088,
    "preview": "name: 🐞 Bug Report\ndescription: File a bug report\ntitle: \"[Bug]: \"\ntype: \"Bug\"\nbody:\n  - type: markdown\n    attributes:\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature-request.yml",
    "chars": 1452,
    "preview": "name: 💡 Feature Request\ndescription: Suggest an idea for this repository\ntitle: \"[Feat]: \"\ntype: \"Feature\"\nbody:\n  - typ"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "chars": 520,
    "preview": "# Description\n\nThank you for opening a Pull Request!\nBefore submitting your PR, there are a few things you can do to mak"
  },
  {
    "path": ".github/actions/poetry_setup/action.yml",
    "chars": 3325,
    "preview": "# An action for setting up poetry install with caching.\n# Using a custom action since the default action does not\n# take"
  },
  {
    "path": ".github/workflows/_integration_test.yml",
    "chars": 1944,
    "preview": "name: integration_test\n\non:\n  workflow_dispatch:\n    inputs:\n      working-directory:\n        required: true\n        typ"
  },
  {
    "path": ".github/workflows/_release.yml",
    "chars": 9116,
    "preview": "name: release\nrun-name: Release ${{ inputs.working-directory }} by @${{ github.actor }}\non:\n  workflow_call:\n    inputs:"
  },
  {
    "path": ".github/workflows/_test.yml",
    "chars": 1665,
    "preview": "name: test\n\non:\n  workflow_dispatch:\n    inputs:\n      working-directory:\n        required: true\n        type: string\n  "
  },
  {
    "path": ".github/workflows/_test_release.yml",
    "chars": 3117,
    "preview": "name: test-release\n\non:\n  workflow_call:\n    inputs:\n      working-directory:\n        required: true\n        type: strin"
  },
  {
    "path": ".github/workflows/lint-pr.yaml",
    "chars": 346,
    "preview": "name: \"Lint PR\"\n\non:\n  pull_request_target:\n    types:\n      - opened\n      - edited\n      - reopened\n\njobs:\n  lint-pr:\n"
  },
  {
    "path": ".gitignore",
    "chars": 301,
    "preview": ".vscode\n.idea\n*.pyc\n__pycache__/\n.pytest_cache/\n.DS_Store/\n\n*.swp\n*~\n\nbuild/\ndist/\neggs/\n.eggs/\n*.egg-info/\ntest/\nexampl"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 4391,
    "preview": "# Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1462,
    "preview": "# How to contribute\n\nWe'd love to accept your patches and contributions to this project.\n\n## Contribution process\n\n### C"
  },
  {
    "path": "LICENSE",
    "chars": 1063,
    "preview": "MIT License\n\nCopyright (c) Zhipu, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof "
  },
  {
    "path": "Makefile",
    "chars": 1872,
    "preview": ".PHONY: all format lint test tests test_watch integration_tests docker_tests help extended_tests\n\n# Default target execu"
  },
  {
    "path": "README.md",
    "chars": 8188,
    "preview": "**The [New Python SDK](https://github.com/zai-org/z-ai-sdk-python) for Z.AI and ZhipuAI has released: [z-ai-sdk-python]("
  },
  {
    "path": "README_CN.md",
    "chars": 6513,
    "preview": "Z.AI 和 智谱AI 的 [全新 Python SDK](https://github.com/zai-org/z-ai-sdk-python) 已经发布:[z-ai-sdk-python](https://github.com/zai-"
  },
  {
    "path": "Release-Note.md",
    "chars": 3217,
    "preview": "## Release Notes\n\n### 2024-08-12\n\n**New Features:**\n- Modified video prompt to be optional, added file deletion function"
  },
  {
    "path": "poetry.toml",
    "chars": 73,
    "preview": "[virtualenvs]\nin-project = true\n\n[installer]\nmodern-installation = false\n"
  },
  {
    "path": "pyproject.toml",
    "chars": 2894,
    "preview": "[tool.poetry]\nname = \"zhipuai\"\nversion = \"2.1.5.20250825\"\ndescription = \"A SDK library for accessing big model apis from"
  },
  {
    "path": "tests/conftest.py",
    "chars": 3134,
    "preview": "\"\"\"Configuration for unit tests.\"\"\"\n\nfrom importlib import util\nfrom pathlib import Path\nfrom typing import Dict, Sequen"
  },
  {
    "path": "tests/integration_tests/batchinput.jsonl",
    "chars": 490,
    "preview": "{\"custom_id\": \"request-1\", \"method\": \"POST\", \"url\": \"/v4/chat/completions\", \"body\": {\"model\": \"glm-4\", \"messages\": [{\"ro"
  },
  {
    "path": "tests/integration_tests/demo.jsonl",
    "chars": 692,
    "preview": "{\"messages\": [{\"role\": \"system\", \"content\": \"你是一位乐于助人,知识渊博的全能AI助手。\"},{\"role\": \"user\", \"content\": \"请介绍一下AlphaGo的基本原理。\"}, "
  },
  {
    "path": "tests/integration_tests/test.py",
    "chars": 594,
    "preview": "import time\n\nfrom zhipuai import ZhipuAI\n\nclient = ZhipuAI()  # 填写您自己的APIKey\n\nresponse = client.videos.generations(\n\tmod"
  },
  {
    "path": "tests/integration_tests/test_agents.py",
    "chars": 2270,
    "preview": "import logging\nimport logging.config\nimport time\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_completions_sync"
  },
  {
    "path": "tests/integration_tests/test_assistant.py",
    "chars": 2714,
    "preview": "import logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_assistant(logging_conf) -> N"
  },
  {
    "path": "tests/integration_tests/test_audio.py",
    "chars": 2493,
    "preview": "import base64\nimport json\nimport logging\nimport logging.config\nfrom pathlib import Path\n\nimport zhipuai\nfrom zhipuai imp"
  },
  {
    "path": "tests/integration_tests/test_batches.py",
    "chars": 5415,
    "preview": "import logging\nimport logging.config\nimport os\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_batch_input_file(t"
  },
  {
    "path": "tests/integration_tests/test_charglm3.py",
    "chars": 2405,
    "preview": "# -*- coding: utf-8 -*-\n\nimport logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_com"
  },
  {
    "path": "tests/integration_tests/test_chat.py",
    "chars": 12203,
    "preview": "import logging\nimport logging.config\nimport os.path\nimport time\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_c"
  },
  {
    "path": "tests/integration_tests/test_code_geex.py",
    "chars": 3531,
    "preview": "import logging\nimport logging.config\nimport time\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_code_geex(loggin"
  },
  {
    "path": "tests/integration_tests/test_embedding.py",
    "chars": 1190,
    "preview": "import logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_embeddings(logging_conf):\n\tl"
  },
  {
    "path": "tests/integration_tests/test_emohaa.py",
    "chars": 1018,
    "preview": "# -*- coding: utf-8 -*-\n\nimport logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_com"
  },
  {
    "path": "tests/integration_tests/test_file.py",
    "chars": 2123,
    "preview": "from __future__ import annotations\n\nimport logging\nimport logging.config\nimport os\n\nimport pytest\n\nimport zhipuai\nfrom z"
  },
  {
    "path": "tests/integration_tests/test_file_parser.py",
    "chars": 1128,
    "preview": "from __future__ import annotations\n\nimport logging\nimport logging.config\nimport os\n\nimport pytest\n\nimport zhipuai\nfrom z"
  },
  {
    "path": "tests/integration_tests/test_finetuning.py",
    "chars": 3874,
    "preview": "import logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_finetuning_create(logging_co"
  },
  {
    "path": "tests/integration_tests/test_images.py",
    "chars": 1202,
    "preview": "import logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_images(logging_conf):\n\tloggi"
  },
  {
    "path": "tests/integration_tests/test_knowledge.py",
    "chars": 4712,
    "preview": "from __future__ import annotations\n\nimport logging\nimport logging.config\nimport os\n\nimport pytest\n\nimport zhipuai\nfrom z"
  },
  {
    "path": "tests/integration_tests/test_moderation.py",
    "chars": 679,
    "preview": "import logging\nimport logging.config\nimport time\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_completions_temp"
  },
  {
    "path": "tests/integration_tests/test_tools.py",
    "chars": 1138,
    "preview": "import logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_tools(logging_conf):\n\tloggin"
  },
  {
    "path": "tests/integration_tests/test_transcriptions.py",
    "chars": 1250,
    "preview": "import logging\nimport logging.config\nfrom pathlib import Path\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_tra"
  },
  {
    "path": "tests/integration_tests/test_videos.py",
    "chars": 2120,
    "preview": "import logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_videos(logging_conf):\n\tloggi"
  },
  {
    "path": "tests/integration_tests/test_vlm_thinking.py",
    "chars": 2139,
    "preview": "import logging\nimport logging.config\nimport time\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_completions_vlm_"
  },
  {
    "path": "tests/integration_tests/test_web_search.py",
    "chars": 698,
    "preview": "import logging\nimport logging.config\n\nimport zhipuai\nfrom zhipuai import ZhipuAI\n\n\ndef test_web_search(logging_conf):\n\tl"
  },
  {
    "path": "tests/unit_tests/batchinput.jsonl",
    "chars": 243,
    "preview": "{\"custom_id\": \"request-1\", \"method\": \"POST\", \"url\": \"/v4/chat/completions\", \"body\": {\"model\": \"glm-4\", \"messages\": [{\"ro"
  },
  {
    "path": "tests/unit_tests/maybe/test_maybe_transform.py",
    "chars": 376,
    "preview": "# -*- coding: utf-8 -*-\nfrom zhipuai.core import maybe_transform\nfrom zhipuai.types import batch_create_params\n\n\ndef tes"
  },
  {
    "path": "tests/unit_tests/response_model/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "tests/unit_tests/response_model/test_response.py",
    "chars": 14912,
    "preview": "# -*- coding: utf-8 -*-\nfrom typing import Type\n\nimport httpx\nimport pytest\n\nfrom zhipuai.core import BaseModel, HttpCli"
  },
  {
    "path": "tests/unit_tests/sse_client/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "tests/unit_tests/sse_client/test_stream.py",
    "chars": 1741,
    "preview": "# -*- coding: utf-8 -*-\nfrom typing import Iterable, Type, cast\n\nimport httpx\n\nfrom zhipuai.core import HttpClient, Stre"
  },
  {
    "path": "tests/unit_tests/test_agents.py",
    "chars": 1212,
    "preview": "def test_agents_completion_error_field():\n    from zhipuai.types.agents.agents_completion import AgentsCompletion, Agent"
  },
  {
    "path": "tests/unit_tests/test_audio.py",
    "chars": 949,
    "preview": "def test_audio_error_field():\n    from zhipuai.types.audio.audio_speech_chunk import AudioSpeechChunk, AudioError, Audio"
  },
  {
    "path": "tests/unit_tests/test_jwt.py",
    "chars": 466,
    "preview": "import jwt\nimport pytest\n\nfrom zhipuai.core._jwt_token import generate_token\n\n\ndef test_token() -> None:\n\t# 生成token\n\ttok"
  },
  {
    "path": "tests/unit_tests/test_request_opt.py",
    "chars": 1153,
    "preview": "import pytest\n\nfrom zhipuai.core._request_opt import FinalRequestOptions, NotGiven\n\n\n# Test Initialization and Default V"
  },
  {
    "path": "tests/unit_tests/test_response.py",
    "chars": 3327,
    "preview": "import httpx\nfrom httpx import URL, ByteStream, Headers, Request, Response\nfrom typing_extensions import Dict, Type\n\nfro"
  },
  {
    "path": "tests/unit_tests/test_sdk_import.py",
    "chars": 302,
    "preview": "def test_sdk_import_unit():\n\timport zhipuai\n\n\tprint(zhipuai.__version__)\n\n\ndef test_os_import_unit():\n\timport os\n\n\tprint"
  },
  {
    "path": "tests/unit_tests/test_streaming.py",
    "chars": 1797,
    "preview": "from typing import Iterator\n\nimport pytest\n\nfrom zhipuai.core._sse_client import SSELineParser\n\n\ndef test_basic() -> Non"
  },
  {
    "path": "zhipuai/__init__.py",
    "chars": 359,
    "preview": "\nfrom ._client import ZhipuAI\n\nfrom .core import (\n    ZhipuAIError,\n    APIStatusError,\n    APIRequestFailedError,\n    "
  },
  {
    "path": "zhipuai/__version__.py",
    "chars": 31,
    "preview": "__version__ = 'v2.1.5.20250725'"
  },
  {
    "path": "zhipuai/_client.py",
    "chars": 3541,
    "preview": "from __future__ import annotations\n\nfrom typing import Union, Mapping\n\nfrom typing_extensions import override\n\nfrom .cor"
  },
  {
    "path": "zhipuai/api_resource/__init__.py",
    "chars": 967,
    "preview": "from .chat import (\n    AsyncCompletions,\n    Chat,\n    Completions,\n)\nfrom .images import (\n    Images\n)\nfrom .embeddin"
  },
  {
    "path": "zhipuai/api_resource/agents/__init__.py",
    "chars": 81,
    "preview": "from zhipuai.api_resource.agents.agents import Agents\n\n__all__= [\n    \"Agents\"\n]\n"
  },
  {
    "path": "zhipuai/api_resource/agents/agents.py",
    "chars": 3179,
    "preview": "from __future__ import annotations\n\nfrom typing import Union, List, Optional, TYPE_CHECKING, Dict\n\nimport httpx\nimport l"
  },
  {
    "path": "zhipuai/api_resource/assistant/__init__.py",
    "chars": 95,
    "preview": "\n\nfrom zhipuai.api_resource.assistant.assistant import Assistant\n\n__all__= [\n    \"Assistant\"\n]\n"
  },
  {
    "path": "zhipuai/api_resource/assistant/assistant.py",
    "chars": 4577,
    "preview": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict\nfrom typing_ex"
  },
  {
    "path": "zhipuai/api_resource/audio/__init__.py",
    "chars": 134,
    "preview": "from .audio import (\n    Audio\n)\n\nfrom .transcriptions import (\n    Transcriptions\n)\n\n\n__all__ = [\n    'Audio',\n    'Tra"
  },
  {
    "path": "zhipuai/api_resource/audio/audio.py",
    "chars": 4190,
    "preview": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict\nfrom .transcri"
  },
  {
    "path": "zhipuai/api_resource/audio/transcriptions.py",
    "chars": 2777,
    "preview": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict\nfrom ...types."
  },
  {
    "path": "zhipuai/api_resource/batches.py",
    "chars": 5175,
    "preview": "from __future__ import annotations\n\nimport httpx\nfrom typing import TYPE_CHECKING, Literal, Optional, Dict\n\nfrom ..core "
  },
  {
    "path": "zhipuai/api_resource/chat/__init__.py",
    "chars": 200,
    "preview": "from .async_completions import (\n    AsyncCompletions\n)\n\nfrom .chat import (\n    Chat\n)\n\nfrom .completions import (\n    "
  },
  {
    "path": "zhipuai/api_resource/chat/async_completions.py",
    "chars": 4717,
    "preview": "from __future__ import annotations\n\nfrom typing import Union, List, Optional, TYPE_CHECKING, Dict\n\nimport httpx\nimport l"
  },
  {
    "path": "zhipuai/api_resource/chat/chat.py",
    "chars": 464,
    "preview": "from typing import TYPE_CHECKING\nfrom .completions import Completions\nfrom .async_completions import AsyncCompletions\nfr"
  },
  {
    "path": "zhipuai/api_resource/chat/completions.py",
    "chars": 4393,
    "preview": "from __future__ import annotations\n\nfrom typing import Union, List, Optional, TYPE_CHECKING, Dict\n\nimport httpx\nimport l"
  },
  {
    "path": "zhipuai/api_resource/embeddings.py",
    "chars": 1863,
    "preview": "from __future__ import annotations\n\nfrom typing import Union, List, Optional, TYPE_CHECKING\n\nimport httpx\n\nfrom ..core i"
  },
  {
    "path": "zhipuai/api_resource/file_parser/__init__.py",
    "chars": 61,
    "preview": "from .file_parser import FileParser\n\n__all__ = ['FileParser']"
  },
  {
    "path": "zhipuai/api_resource/file_parser/file_parser.py",
    "chars": 3379,
    "preview": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Mapping, cast\n\nimport httpx\nfrom typing_extensions"
  },
  {
    "path": "zhipuai/api_resource/files.py",
    "chars": 6796,
    "preview": "from __future__ import annotations\n\n\nfrom typing import TYPE_CHECKING, List, Mapping, cast\nfrom typing_extensions import"
  },
  {
    "path": "zhipuai/api_resource/fine_tuning/__init__.py",
    "chars": 188,
    "preview": "from .jobs import (\n    Jobs\n)\n\nfrom .models import (\n    FineTunedModels\n)\n\nfrom .fine_tuning import (\n    FineTuning\n)"
  },
  {
    "path": "zhipuai/api_resource/fine_tuning/fine_tuning.py",
    "chars": 413,
    "preview": "from typing import TYPE_CHECKING\nfrom .jobs import Jobs\nfrom .models import FineTunedModels\nfrom ...core import BaseAPI,"
  },
  {
    "path": "zhipuai/api_resource/fine_tuning/jobs/__init__.py",
    "chars": 48,
    "preview": "from .jobs import Jobs\n\n__all__ = [\n    \"Jobs\"\n]"
  },
  {
    "path": "zhipuai/api_resource/fine_tuning/jobs/jobs.py",
    "chars": 5395,
    "preview": "from __future__ import annotations\n\nfrom typing import Optional, TYPE_CHECKING\n\nimport httpx\n\nfrom ....core import BaseA"
  },
  {
    "path": "zhipuai/api_resource/fine_tuning/models/__init__.py",
    "chars": 77,
    "preview": "from .fine_tuned_models import FineTunedModels\n\n__all__ = ['FineTunedModels']"
  },
  {
    "path": "zhipuai/api_resource/fine_tuning/models/fine_tuned_models.py",
    "chars": 1232,
    "preview": "from __future__ import annotations\n\nfrom typing import Optional, TYPE_CHECKING\n\nimport httpx\n\nfrom ....core import BaseA"
  },
  {
    "path": "zhipuai/api_resource/images.py",
    "chars": 2266,
    "preview": "from __future__ import annotations\n\nfrom typing import Union, List, Optional, TYPE_CHECKING\n\nimport httpx\n\nfrom ..core i"
  },
  {
    "path": "zhipuai/api_resource/knowledge/__init__.py",
    "chars": 57,
    "preview": "from .knowledge import Knowledge\n\n__all__ = ['Knowledge']"
  },
  {
    "path": "zhipuai/api_resource/knowledge/document/__init__.py",
    "chars": 55,
    "preview": "from .document import Document\n\n\n__all__ = ['Document']"
  },
  {
    "path": "zhipuai/api_resource/knowledge/document/document.py",
    "chars": 7702,
    "preview": "from __future__ import annotations\n\n\nfrom typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict\nfrom typing_e"
  },
  {
    "path": "zhipuai/api_resource/knowledge/knowledge.py",
    "chars": 6021,
    "preview": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, List, Mapping, cast, Optional\nfrom typing_extensio"
  },
  {
    "path": "zhipuai/api_resource/moderation/__init__.py",
    "chars": 77,
    "preview": "from .moderations import (\n    Moderations\n)\n\n__all__ = [\n    'Moderations'\n]"
  },
  {
    "path": "zhipuai/api_resource/moderation/moderations.py",
    "chars": 814,
    "preview": "from __future__ import annotations\n\nfrom typing import Union, List, TYPE_CHECKING, Dict\n\nimport logging\nfrom ...core imp"
  },
  {
    "path": "zhipuai/api_resource/tools/__init__.py",
    "chars": 45,
    "preview": "from .tools import Tools\n\n__all__ = ['Tools']"
  },
  {
    "path": "zhipuai/api_resource/tools/tools.py",
    "chars": 2058,
    "preview": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, List, Union, Dict, Optional\nfrom typing_extensions"
  },
  {
    "path": "zhipuai/api_resource/videos/__init__.py",
    "chars": 64,
    "preview": "from .videos import (\n    Videos,\n)\n__all__ = [\n    'Videos',\n\n]"
  },
  {
    "path": "zhipuai/api_resource/videos/videos.py",
    "chars": 2924,
    "preview": "from __future__ import annotations\n\n\nfrom typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict\nfrom typing_e"
  },
  {
    "path": "zhipuai/api_resource/web_search/__init__.py",
    "chars": 64,
    "preview": "from .web_search import WebSearchApi\n\n__all__ = ['WebSearchApi']"
  },
  {
    "path": "zhipuai/api_resource/web_search/web_search.py",
    "chars": 2612,
    "preview": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, List, Union, Dict, Optional\nfrom ...types.sensitiv"
  },
  {
    "path": "zhipuai/core/__init__.py",
    "chars": 2258,
    "preview": "from ._base_models import (\n    BaseModel,\n    construct_type\n)\nfrom ._base_api import BaseAPI\nfrom ._base_type import ("
  },
  {
    "path": "zhipuai/core/_base_api.py",
    "chars": 455,
    "preview": "from __future__ import annotations\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from .._client import ZhipuAI"
  },
  {
    "path": "zhipuai/core/_base_compat.py",
    "chars": 6405,
    "preview": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, over"
  },
  {
    "path": "zhipuai/core/_base_models.py",
    "chars": 25037,
    "preview": "from __future__ import annotations\n\nimport inspect\nimport os\nfrom typing import TYPE_CHECKING, Any, Type, Generic, TypeV"
  },
  {
    "path": "zhipuai/core/_base_type.py",
    "chars": 4901,
    "preview": "from __future__ import annotations\n\nfrom os import PathLike\nfrom typing import (\n    IO,\n    TYPE_CHECKING,\n    Any,\n   "
  },
  {
    "path": "zhipuai/core/_constants.py",
    "chars": 485,
    "preview": "import httpx\n\nRAW_RESPONSE_HEADER = \"X-Stainless-Raw-Response\"\n# 通过 `Timeout` 控制接口`connect` 和 `read` 超时时间,默认为`timeout=30"
  },
  {
    "path": "zhipuai/core/_errors.py",
    "chars": 2256,
    "preview": "from __future__ import annotations\n\nimport httpx\n\n__all__ = [\n    \"ZhipuAIError\",\n    \"APIStatusError\",\n    \"APIRequestF"
  },
  {
    "path": "zhipuai/core/_files.py",
    "chars": 2453,
    "preview": "from __future__ import annotations\n\nimport io\nimport os\nimport pathlib\nfrom typing import Mapping, Sequence, overload\nfr"
  },
  {
    "path": "zhipuai/core/_http_client.py",
    "chars": 30562,
    "preview": "# -*- coding:utf-8 -*-\nfrom __future__ import annotations\n\nimport inspect\nimport warnings\nfrom typing import (\n    Any,\n"
  },
  {
    "path": "zhipuai/core/_jwt_token.py",
    "chars": 742,
    "preview": "# -*- coding:utf-8 -*-\nimport time\n\nimport cachetools.func\nimport jwt\n\n# 缓存时间 3分钟\nCACHE_TTL_SECONDS = 3 * 60\n\n# token 有效"
  },
  {
    "path": "zhipuai/core/_legacy_binary_response.py",
    "chars": 7279,
    "preview": "from __future__ import annotations\n\nimport httpx\nimport os\nfrom typing import Iterator, AsyncIterator, Any\n\n\nclass Httpx"
  },
  {
    "path": "zhipuai/core/_legacy_response.py",
    "chars": 12172,
    "preview": "from __future__ import annotations\n\nimport os\nimport inspect\nimport logging\nimport datetime\nimport functools\nfrom collec"
  },
  {
    "path": "zhipuai/core/_request_opt.py",
    "chars": 3443,
    "preview": "from __future__ import annotations\n\nfrom typing import Union, Any, cast, TYPE_CHECKING\n\nfrom ._constants import RAW_RESP"
  },
  {
    "path": "zhipuai/core/_response.py",
    "chars": 14044,
    "preview": "from __future__ import annotations\n\nimport datetime\nimport inspect\nfrom typing import TypeVar, Generic, cast, Any, TYPE_"
  },
  {
    "path": "zhipuai/core/_sse_client.py",
    "chars": 5467,
    "preview": "# -*- coding:utf-8 -*-\nfrom __future__ import annotations\n\nimport inspect\nimport json\nfrom typing import TYPE_CHECKING, "
  },
  {
    "path": "zhipuai/core/_utils/__init__.py",
    "chars": 1729,
    "preview": "\nfrom ._utils import (\n    remove_notgiven_indict as remove_notgiven_indict,\n    flatten as flatten,\n    is_dict as is_d"
  },
  {
    "path": "zhipuai/core/_utils/_transform.py",
    "chars": 13099,
    "preview": "from __future__ import annotations\n\nimport io\nimport base64\nimport pathlib\nfrom typing import Any, Mapping, TypeVar, cas"
  },
  {
    "path": "zhipuai/core/_utils/_typing.py",
    "chars": 3858,
    "preview": "from __future__ import annotations\n\nfrom typing import Any, TypeVar, Iterable, cast\nfrom collections import abc as _c_ab"
  },
  {
    "path": "zhipuai/core/_utils/_utils.py",
    "chars": 11909,
    "preview": "from __future__ import annotations\n\nimport os\nimport re\nimport inspect\nimport functools\nfrom typing import (\n    Any,\n  "
  },
  {
    "path": "zhipuai/core/logs.py",
    "chars": 2618,
    "preview": "import logging\nimport os\nimport time\n\nlogger = logging.getLogger(__name__)\n\n\nclass LoggerNameFilter(logging.Filter):\n   "
  },
  {
    "path": "zhipuai/core/pagination.py",
    "chars": 1562,
    "preview": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom typing import Any, List, Gen"
  },
  {
    "path": "zhipuai/types/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "zhipuai/types/agents/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "zhipuai/types/agents/agents_completion.py",
    "chars": 889,
    "preview": "from typing import List, Optional\n\nfrom ...core import BaseModel\n\n__all__ = [\"AgentsCompletion\", \"AgentsCompletionUsage\""
  },
  {
    "path": "zhipuai/types/agents/agents_completion_chunk.py",
    "chars": 895,
    "preview": "from typing import List, Optional, Dict, Any\n\nfrom ...core import BaseModel\n\n__all__ = [\n    \"AgentsCompletionUsage\",\n  "
  },
  {
    "path": "zhipuai/types/agents/chat_completions_create_param.py",
    "chars": 171,
    "preview": "from typing import Optional\n\nfrom typing_extensions import TypedDict\n\n\nclass Reference(TypedDict, total=False):\n    enab"
  },
  {
    "path": "zhipuai/types/assistant/__init__.py",
    "chars": 98,
    "preview": "\n\nfrom .assistant_completion import AssistantCompletion\n\n__all__ = [\n    'AssistantCompletion',\n]\n"
  },
  {
    "path": "zhipuai/types/assistant/assistant_completion.py",
    "chars": 1131,
    "preview": "from typing import List, Optional, Dict, Any\n\nfrom .message import MessageContent\nfrom ...core import BaseModel\n\n__all__"
  },
  {
    "path": "zhipuai/types/assistant/assistant_conversation_params.py",
    "chars": 189,
    "preview": "from typing import TypedDict, List, Optional, Union\n\n\nclass ConversationParameters(TypedDict, total=False):\n    assistan"
  },
  {
    "path": "zhipuai/types/assistant/assistant_conversation_resp.py",
    "chars": 729,
    "preview": "from typing import List, Optional, Dict, Any\n\nfrom ...core import BaseModel\n\n__all__ = [\n    \"ConversationUsageListResp\""
  },
  {
    "path": "zhipuai/types/assistant/assistant_create_params.py",
    "chars": 941,
    "preview": "from typing import TypedDict, List, Optional, Union\n\n\nclass AssistantAttachments:\n    file_id: str\n\n\nclass MessageTextCo"
  },
  {
    "path": "zhipuai/types/assistant/assistant_support_resp.py",
    "chars": 608,
    "preview": "from typing import List, Optional, Dict, Any\n\nfrom .message import MessageContent\nfrom ...core import BaseModel\n\n__all__"
  },
  {
    "path": "zhipuai/types/assistant/message/__init__.py",
    "chars": 81,
    "preview": "\nfrom .message_content import MessageContent\n\n__all__ = [\n    \"MessageContent\"\n]\n"
  },
  {
    "path": "zhipuai/types/assistant/message/message_content.py",
    "chars": 373,
    "preview": "\nfrom typing import Union\nfrom typing_extensions import Annotated, TypeAlias\n\nfrom ....core._utils import PropertyInfo\nf"
  },
  {
    "path": "zhipuai/types/assistant/message/text_content_block.py",
    "chars": 255,
    "preview": "from typing_extensions import Literal\n\nfrom ....core import BaseModel\n\n__all__ = [\"TextContentBlock\"]\n\n\nclass TextConten"
  },
  {
    "path": "zhipuai/types/assistant/message/tools/code_interpreter_delta_block.py",
    "chars": 616,
    "preview": "from typing import List\n\nfrom typing_extensions import Literal\n\n__all__ = [\"CodeInterpreterToolBlock\"]\n\nfrom .....core i"
  },
  {
    "path": "zhipuai/types/assistant/message/tools/drawing_tool_delta_block.py",
    "chars": 400,
    "preview": "from typing import List\n\nfrom typing_extensions import Literal\n\nfrom .....core import BaseModel\n\n__all__ = [\"DrawingTool"
  },
  {
    "path": "zhipuai/types/assistant/message/tools/function_delta_block.py",
    "chars": 436,
    "preview": "from typing import List, Union\n\nfrom typing_extensions import Literal\n\n__all__ = [\"FunctionToolBlock\"]\n\nfrom .....core i"
  },
  {
    "path": "zhipuai/types/assistant/message/tools/retrieval_delta_black.py",
    "chars": 1193,
    "preview": "from typing import List\n\nfrom typing_extensions import Literal\n\nfrom .....core import BaseModel\n\n\nclass RetrievalToolOut"
  },
  {
    "path": "zhipuai/types/assistant/message/tools/tools_type.py",
    "chars": 622,
    "preview": "\nfrom typing import Union\nfrom typing_extensions import Annotated, TypeAlias\n\nfrom .code_interpreter_delta_block import "
  },
  {
    "path": "zhipuai/types/assistant/message/tools/web_browser_delta_block.py",
    "chars": 1368,
    "preview": "from typing import List\n\nfrom typing_extensions import Literal\n\nfrom .....core import BaseModel\n__all__ = [\"WebBrowserTo"
  },
  {
    "path": "zhipuai/types/assistant/message/tools_delta_block.py",
    "chars": 402,
    "preview": "from typing import Optional, List\nfrom typing_extensions import Literal\n\nfrom .tools.tools_type import ToolsType\nfrom .."
  },
  {
    "path": "zhipuai/types/audio/__init__.py",
    "chars": 278,
    "preview": "from .audio_speech_params import(\n    AudioSpeechParams\n)\n\nfrom .audio_customization_param import(\n    AudioCustomizatio"
  },
  {
    "path": "zhipuai/types/audio/audio_customization_param.py",
    "chars": 607,
    "preview": "from __future__ import annotations\n\nfrom typing import List, Optional\n\nfrom typing_extensions import Literal, Required, "
  },
  {
    "path": "zhipuai/types/audio/audio_speech_chunk.py",
    "chars": 682,
    "preview": "from typing import List, Optional, Dict, Any\n\nfrom ...core import BaseModel\n\n__all__ = [\n    \"AudioSpeechChunk\",\n    \"Au"
  },
  {
    "path": "zhipuai/types/audio/audio_speech_params.py",
    "chars": 590,
    "preview": "from __future__ import annotations\n\nfrom typing import List, Optional\n\nfrom typing_extensions import Literal, Required, "
  },
  {
    "path": "zhipuai/types/audio/transcriptions_create_param.py",
    "chars": 545,
    "preview": "from __future__ import annotations\n\nfrom typing import List, Optional\n\nfrom typing_extensions import Literal, Required, "
  },
  {
    "path": "zhipuai/types/batch.py",
    "chars": 2019,
    "preview": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport builtins\nfrom typing impor"
  },
  {
    "path": "zhipuai/types/batch_create_params.py",
    "chars": 1129,
    "preview": "from __future__ import annotations\n\nfrom typing import Dict, Optional\nfrom typing_extensions import Literal, Required, T"
  },
  {
    "path": "zhipuai/types/batch_error.py",
    "chars": 414,
    "preview": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom typing import Optional\n\nfrom"
  },
  {
    "path": "zhipuai/types/batch_list_params.py",
    "chars": 356,
    "preview": "from __future__ import annotations\n\nfrom typing_extensions import TypedDict\n\n__all__ = [\"BatchListParams\"]\n\n\nclass Batch"
  },
  {
    "path": "zhipuai/types/batch_request_counts.py",
    "chars": 224,
    "preview": "from ..core import BaseModel\n\n__all__ = [\"BatchRequestCounts\"]\n\n\nclass BatchRequestCounts(BaseModel):\n    completed: int"
  },
  {
    "path": "zhipuai/types/chat/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "zhipuai/types/chat/async_chat_completion.py",
    "chars": 568,
    "preview": "from typing import List, Optional\n\nfrom ...core import BaseModel\nfrom .chat_completion import CompletionChoice, Completi"
  },
  {
    "path": "zhipuai/types/chat/chat_completion.py",
    "chars": 903,
    "preview": "from typing import List, Optional\n\nfrom ...core import BaseModel\n\n__all__ = [\"Completion\", \"CompletionUsage\"]\n\n\nclass Fu"
  },
  {
    "path": "zhipuai/types/chat/chat_completion_chunk.py",
    "chars": 1794,
    "preview": "from typing import List, Optional, Dict, Any\n\nfrom ...core import BaseModel\n\n__all__ = [\n    \"CompletionUsage\",\n    \"Cha"
  },
  {
    "path": "zhipuai/types/chat/chat_completions_create_param.py",
    "chars": 171,
    "preview": "from typing import Optional\n\nfrom typing_extensions import TypedDict\n\n\nclass Reference(TypedDict, total=False):\n    enab"
  },
  {
    "path": "zhipuai/types/chat/code_geex/code_geex_params.py",
    "chars": 1970,
    "preview": "from typing import List, Optional\nfrom typing_extensions import Literal, Required, TypedDict\n\n__all__ = [\n    \"CodeGeexT"
  },
  {
    "path": "zhipuai/types/embeddings.py",
    "chars": 426,
    "preview": "from __future__ import annotations\n\nfrom typing import Optional, List\n\nfrom ..core import BaseModel\nfrom .chat.chat_comp"
  },
  {
    "path": "zhipuai/types/file_parser/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "zhipuai/types/file_parser/file_parser_create_params.py",
    "chars": 569,
    "preview": "from __future__ import annotations\n\nfrom typing_extensions import Literal, Required, TypedDict\nfrom ...core import NOT_G"
  },
  {
    "path": "zhipuai/types/file_parser/file_parser_resp.py",
    "chars": 251,
    "preview": "from typing import List, Optional\n\nfrom zhipuai.core import BaseModel\n\n__all__ = [\n    \"FileParserTaskCreateResp\"\n]\n\n\ncl"
  },
  {
    "path": "zhipuai/types/files/__init__.py",
    "chars": 227,
    "preview": "from .file_object import FileObject, ListOfFileObject\nfrom .upload_detail import UploadDetail\nfrom .file_deleted import "
  },
  {
    "path": "zhipuai/types/files/file_create_params.py",
    "chars": 950,
    "preview": "\nfrom __future__ import annotations\n\nfrom typing import List, Optional\n\nfrom typing_extensions import Literal, Required,"
  },
  {
    "path": "zhipuai/types/files/file_deleted.py",
    "chars": 188,
    "preview": "\nfrom typing_extensions import Literal\n\nfrom ...core import BaseModel\n__all__ = [\"FileDeleted\"]\n\n\nclass FileDeleted(Base"
  },
  {
    "path": "zhipuai/types/files/file_object.py",
    "chars": 551,
    "preview": "from typing import Optional, List\n\nfrom ...core import BaseModel\n\n__all__ = [\"FileObject\", \"ListOfFileObject\"]\n\n\nclass F"
  },
  {
    "path": "zhipuai/types/files/upload_detail.py",
    "chars": 357,
    "preview": "from typing import Optional, List, Dict\n\nfrom ...core import BaseModel\n\n\nclass UploadDetail(BaseModel):\n    url: str\n   "
  },
  {
    "path": "zhipuai/types/fine_tuning/__init__.py",
    "chars": 244,
    "preview": "from __future__ import annotations\n\nfrom .fine_tuning_job import FineTuningJob as FineTuningJob\nfrom .fine_tuning_job im"
  },
  {
    "path": "zhipuai/types/fine_tuning/fine_tuning_job.py",
    "chars": 1005,
    "preview": "from typing import List, Union, Optional, Dict, Any\n\nfrom ...core import BaseModel\n\n__all__ = [\"FineTuningJob\", \"Error\","
  },
  {
    "path": "zhipuai/types/fine_tuning/fine_tuning_job_event.py",
    "chars": 1064,
    "preview": "from typing import List, Union, Optional\n\nfrom ...core import BaseModel\n\n__all__ = [\"FineTuningJobEvent\", \"Metric\", \"Job"
  },
  {
    "path": "zhipuai/types/fine_tuning/job_create_params.py",
    "chars": 339,
    "preview": "from __future__ import annotations\n\nfrom typing import Union\n\nfrom typing_extensions import Literal, TypedDict\n\n__all__ "
  },
  {
    "path": "zhipuai/types/fine_tuning/models/__init__.py",
    "chars": 53,
    "preview": "\nfrom .fine_tuned_models import FineTunedModelsStatus"
  },
  {
    "path": "zhipuai/types/fine_tuning/models/fine_tuned_models.py",
    "chars": 416,
    "preview": "from typing import List, Union, Optional, ClassVar\n\nfrom ....core import BaseModel, PYDANTIC_V2, ConfigDict\n\n__all__ = ["
  },
  {
    "path": "zhipuai/types/image.py",
    "chars": 374,
    "preview": "from __future__ import annotations\n\nfrom typing import Optional, List\n\nfrom ..core import BaseModel\n\n__all__ = [\"Generat"
  },
  {
    "path": "zhipuai/types/knowledge/__init__.py",
    "chars": 184,
    "preview": "\nfrom .knowledge import KnowledgeInfo\nfrom .knowledge_used import KnowledgeStatistics, KnowledgeUsed\n__all__ = [\n    'Kn"
  },
  {
    "path": "zhipuai/types/knowledge/document/__init__.py",
    "chars": 203,
    "preview": "\nfrom .document import DocumentData, DocumentObject, DocumentSuccessinfo, DocumentFailedInfo\n\n\n__all__ = [\n    \"Document"
  },
  {
    "path": "zhipuai/types/knowledge/document/document.py",
    "chars": 1373,
    "preview": "from typing import Optional, List\n\nfrom ....core import BaseModel\n\n__all__ = [\"DocumentData\", \"DocumentObject\", \"Documen"
  },
  {
    "path": "zhipuai/types/knowledge/document/document_edit_params.py",
    "chars": 937,
    "preview": "from typing import Optional, List, Literal, TypedDict, Dict\n\n\n__all__ = [\"DocumentEditParams\"]\n\n\nclass DocumentEditParam"
  },
  {
    "path": "zhipuai/types/knowledge/document/document_list_params.py",
    "chars": 756,
    "preview": "from __future__ import annotations\n\nfrom typing import Dict, Optional\nfrom typing_extensions import Literal, Required, T"
  },
  {
    "path": "zhipuai/types/knowledge/document/document_list_resp.py",
    "chars": 247,
    "preview": "from __future__ import annotations\n\nfrom typing import Dict, Optional, List\n\nfrom . import DocumentData\nfrom ....core im"
  },
  {
    "path": "zhipuai/types/knowledge/knowledge.py",
    "chars": 754,
    "preview": "\nfrom typing import Optional\n\nfrom ...core import BaseModel\n\n__all__ = [\"KnowledgeInfo\"]\n\n\nclass KnowledgeInfo(BaseModel"
  },
  {
    "path": "zhipuai/types/knowledge/knowledge_create_params.py",
    "chars": 982,
    "preview": "from __future__ import annotations\n\nfrom typing import Dict, Optional\nfrom typing_extensions import Literal, Required, T"
  },
  {
    "path": "zhipuai/types/knowledge/knowledge_list_params.py",
    "chars": 308,
    "preview": "from __future__ import annotations\n\nfrom typing import Dict, Optional\nfrom typing_extensions import Literal, Required, T"
  },
  {
    "path": "zhipuai/types/knowledge/knowledge_list_resp.py",
    "chars": 250,
    "preview": "from __future__ import annotations\n\nfrom typing import Dict, Optional, List\n\nfrom . import KnowledgeInfo\nfrom ...core im"
  },
  {
    "path": "zhipuai/types/knowledge/knowledge_used.py",
    "chars": 418,
    "preview": "\n\nfrom typing import Optional\n\nfrom ...core import BaseModel\n\n__all__ = [\n    \"KnowledgeStatistics\",\n    \"KnowledgeUsed\""
  },
  {
    "path": "zhipuai/types/moderation/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "zhipuai/types/moderation/moderation_completion.py",
    "chars": 239,
    "preview": "from typing import List, Optional, Union, Dict\n\nfrom ...core import BaseModel\n\n__all__ = [\"Completion\"]\n\nclass Completio"
  },
  {
    "path": "zhipuai/types/sensitive_word_check/__init__.py",
    "chars": 110,
    "preview": "\n\nfrom .sensitive_word_check import SensitiveWordCheckRequest\n\n\n__all__ = [\n    \"SensitiveWordCheckRequest\"\n]\n"
  },
  {
    "path": "zhipuai/types/sensitive_word_check/sensitive_word_check.py",
    "chars": 319,
    "preview": "from typing import Optional\n\nfrom typing_extensions import TypedDict\n\n\nclass SensitiveWordCheckRequest(TypedDict, total="
  },
  {
    "path": "zhipuai/types/tools/__init__.py",
    "chars": 269,
    "preview": "from .web_search import (\n    WebSearch,\n    SearchIntent,\n    SearchResult,\n    SearchRecommend,\n)\n\nfrom .web_search_ch"
  },
  {
    "path": "zhipuai/types/tools/tools_web_search_params.py",
    "chars": 1104,
    "preview": "\nfrom __future__ import annotations\n\nfrom typing import Union, Optional, List\nfrom typing_extensions import Literal, Req"
  },
  {
    "path": "zhipuai/types/tools/web_search.py",
    "chars": 1266,
    "preview": "from typing import List, Optional\n\nfrom ..chat.chat_completion import Function\nfrom ...core import BaseModel\n\n__all__ = "
  },
  {
    "path": "zhipuai/types/tools/web_search_chunk.py",
    "chars": 800,
    "preview": "from typing import List, Optional, Dict, Any\n\nfrom .web_search import SearchIntent, SearchResult, SearchRecommend\nfrom ."
  },
  {
    "path": "zhipuai/types/video/__init__.py",
    "chars": 106,
    "preview": "\nfrom .video_object import (\n    VideoObject,\n    VideoResult\n)\n\n__all__ = [\"VideoObject\", \"VideoResult\"]\n"
  },
  {
    "path": "zhipuai/types/video/video_create_params.py",
    "chars": 621,
    "preview": "from __future__ import annotations\n\nfrom typing import List, Optional\n\nfrom typing_extensions import Literal, Required, "
  },
  {
    "path": "zhipuai/types/video/video_object.py",
    "chars": 553,
    "preview": "from typing import Optional, List\n\nfrom ...core import BaseModel\n\n__all__ = [\"VideoObject\", \"VideoResult\"]\n\n\nclass Video"
  },
  {
    "path": "zhipuai/types/web_search/__init__.py",
    "chars": 104,
    "preview": "\nfrom .web_search_create_params import (\n    WebSearchCreatParams\n)\n\n__all__ = [\"WebSearchCreatParams\"]\n"
  },
  {
    "path": "zhipuai/types/web_search/web_search_create_params.py",
    "chars": 535,
    "preview": "\nfrom __future__ import annotations\n\nfrom typing import Union, Optional, List\nfrom typing_extensions import Literal, Req"
  },
  {
    "path": "zhipuai/types/web_search/web_search_resp.py",
    "chars": 710,
    "preview": "from typing import List, Optional\n\nfrom ...core import BaseModel\n\n__all__ = [\n    \"SearchIntentResp\",\n    \"SearchResultR"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the MetaGLM/zhipuai-sdk-python-v4 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 195 files (404.2 KB), approximately 108.4k tokens, and a symbol index with 701 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!