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 specification.
- [ ] Ensure the tests pass (Run `mvn clean test` from the repository root)
- [ ] Appropriate docs were updated (if necessary)
Fixes #
================================================
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= - 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
[](https://pypi.org/project/zhipuai/)
[](https://opensource.org/licenses/MIT)
[](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
[](https://pypi.org/project/zhipuai/)
[](LICENSE)
[](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={
"after": after,
"limit": limit,
},
),
)
def cancel(
self,
fine_tuning_job_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> FineTuningJob:
if not fine_tuning_job_id:
raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}")
return self._post(
f"/fine_tuning/jobs/{fine_tuning_job_id}/cancel",
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=FineTuningJob,
)
def list_events(
self,
fine_tuning_job_id: str,
*,
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,
) -> FineTuningJobEvent:
return self._get(
f"/fine_tuning/jobs/{fine_tuning_job_id}/events",
cast_type=FineTuningJobEvent,
options=make_request_options(
extra_headers=extra_headers,
extra_body=extra_body,
timeout=timeout,
query={
"after": after,
"limit": limit,
},
),
)
def delete(
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:
if not fine_tuning_job_id:
raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}")
return self._delete(
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,
)
================================================
FILE: zhipuai/api_resource/fine_tuning/models/__init__.py
================================================
from .fine_tuned_models import FineTunedModels
__all__ = ['FineTunedModels']
================================================
FILE: zhipuai/api_resource/fine_tuning/models/fine_tuned_models.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.models import (
FineTunedModelsStatus
)
if TYPE_CHECKING:
from ...._client import ZhipuAI
__all__ = ["FineTunedModels"]
class FineTunedModels(BaseAPI):
def __init__(self, client: "ZhipuAI") -> None:
super().__init__(client)
def delete(
self,
fine_tuned_model: str,
*,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> FineTunedModelsStatus:
if not fine_tuned_model:
raise ValueError(f"Expected a non-empty value for `fine_tuned_model` but received {fine_tuned_model!r}")
return self._delete(
f"fine_tuning/fine_tuned_models/{fine_tuned_model}",
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=FineTunedModelsStatus,
)
================================================
FILE: zhipuai/api_resource/images.py
================================================
from __future__ import annotations
from typing import Union, List, Optional, TYPE_CHECKING
import httpx
from ..core import BaseAPI
from ..core import NotGiven, NOT_GIVEN, Headers, Body
from ..core import make_request_options
from ..types.image import ImagesResponded
from ..types.sensitive_word_check import SensitiveWordCheckRequest
if TYPE_CHECKING:
from .._client import ZhipuAI
class Images(BaseAPI):
def __init__(self, client: "ZhipuAI") -> None:
super().__init__(client)
def generations(
self,
*,
prompt: str,
model: str | NotGiven = NOT_GIVEN,
n: Optional[int] | NotGiven = NOT_GIVEN,
quality: Optional[str] | NotGiven = NOT_GIVEN,
response_format: Optional[str] | NotGiven = NOT_GIVEN,
size: Optional[str] | NotGiven = NOT_GIVEN,
style: Optional[str] | NotGiven = NOT_GIVEN,
sensitive_word_check: Optional[SensitiveWordCheckRequest] | NotGiven = NOT_GIVEN,
user: str | NotGiven = NOT_GIVEN,
request_id: Optional[str] | NotGiven = NOT_GIVEN,
user_id: Optional[str] | 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,
) -> ImagesResponded:
_cast_type = ImagesResponded
if disable_strict_validation:
_cast_type = object
return self._post(
"/images/generations",
body={
"prompt": prompt,
"model": model,
"n": n,
"quality": quality,
"response_format": response_format,
"sensitive_word_check": sensitive_word_check,
"size": size,
"style": style,
"user": user,
"user_id": user_id,
"request_id": request_id,
},
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=_cast_type,
stream=False,
)
================================================
FILE: zhipuai/api_resource/knowledge/__init__.py
================================================
from .knowledge import Knowledge
__all__ = ['Knowledge']
================================================
FILE: zhipuai/api_resource/knowledge/document/__init__.py
================================================
from .document import Document
__all__ = ['Document']
================================================
FILE: zhipuai/api_resource/knowledge/document/document.py
================================================
from __future__ import annotations
from typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict
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.knowledge.document import DocumentData, DocumentObject, document_edit_params, document_list_params
from ....types.files import UploadDetail, file_create_params
from ....types.knowledge.document.document_list_resp import DocumentPage
if TYPE_CHECKING:
from ...._client import ZhipuAI
__all__ = ["Document"]
class Document(BaseAPI):
def __init__(self, client: "ZhipuAI") -> None:
super().__init__(client)
def create(
self,
*,
file: FileTypes = None,
custom_separator: Optional[List[str]] = None,
upload_detail: List[UploadDetail] = None,
purpose: Literal["retrieval"],
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,
) -> DocumentObject:
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,
"custom_separator": custom_separator,
"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=DocumentObject,
)
def edit(
self,
document_id: str,
knowledge_type: str,
*,
custom_separator: Optional[List[str]] = None,
sentence_size: Optional[int] = None,
callback_url: Optional[str] = None,
callback_header: Optional[Dict[str, str]] = None,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> httpx.Response:
"""
Args:
document_id: 知识id
knowledge_type: 知识类型:
1:文章知识: 支持pdf,url,docx
2.问答知识-文档: 支持pdf,url,docx
3.问答知识-表格: 支持xlsx
4.商品库-表格: 支持xlsx
5.自定义: 支持pdf,url,docx
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
:param knowledge_type:
:param document_id:
:param timeout:
:param extra_body:
:param callback_header:
:param sentence_size:
:param extra_headers:
:param callback_url:
:param custom_separator:
"""
if not document_id:
raise ValueError(f"Expected a non-empty value for `document_id` but received {document_id!r}")
body = deepcopy_minimal(
{
"id": document_id,
"knowledge_type": knowledge_type,
"custom_separator": custom_separator,
"sentence_size": sentence_size,
"callback_url": callback_url,
"callback_header": callback_header,
}
)
return self._put(
f"/document/{document_id}",
body=maybe_transform(body, document_edit_params.DocumentEditParams),
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=httpx.Response,
)
def list(
self,
knowledge_id: str,
*,
purpose: str | NotGiven = NOT_GIVEN,
page: str | NotGiven = NOT_GIVEN,
limit: str | NotGiven = NOT_GIVEN,
order: Literal["desc", "asc"] | NotGiven = NOT_GIVEN,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> DocumentPage:
return self._get(
"/files",
options=make_request_options(
extra_headers=extra_headers,
extra_body=extra_body,
timeout=timeout,
query=maybe_transform(
{
"knowledge_id": knowledge_id,
"purpose": purpose,
"page": page,
"limit": limit,
"order": order,
},
document_list_params.DocumentListParams,
),
),
cast_type=DocumentPage,
)
def delete(
self,
document_id: str,
*,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> httpx.Response:
"""
Delete a file.
Args:
document_id: 知识id
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 document_id:
raise ValueError(f"Expected a non-empty value for `document_id` but received {document_id!r}")
return self._delete(
f"/document/{document_id}",
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=httpx.Response,
)
def retrieve(
self,
document_id: str,
*,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> DocumentData:
"""
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 document_id:
raise ValueError(f"Expected a non-empty value for `document_id` but received {document_id!r}")
return self._get(
f"/document/{document_id}",
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=DocumentData,
)
================================================
FILE: zhipuai/api_resource/knowledge/knowledge.py
================================================
from __future__ import annotations
from typing import TYPE_CHECKING, List, Mapping, cast, Optional
from typing_extensions import Literal
from ...core import NOT_GIVEN, Body, Headers, NotGiven, FileTypes, BaseAPI, maybe_transform
import httpx
from ...core import (
make_request_options,
)
from ...core import deepcopy_minimal, cached_property
from ...types.knowledge import knowledge_create_params, knowledge_list_params
from ...types.knowledge import KnowledgeInfo, KnowledgeUsed
from ...core.pagination import SyncCursorPage
from .document import Document
from ...types.knowledge.knowledge_list_resp import KnowledgePage
if TYPE_CHECKING:
from ..._client import ZhipuAI
__all__ = ["Knowledge"]
class Knowledge(BaseAPI):
def __init__(self, client: "ZhipuAI") -> None:
super().__init__(client)
@cached_property
def document(self) -> Document:
return Document(self._client)
def create(
self,
embedding_id: int,
name: str,
*,
customer_identifier: Optional[str] = None,
description: Optional[str] = None,
background: Optional[Literal['blue', 'red', 'orange', 'purple', 'sky']] = None,
icon: Optional[Literal['question', 'book', 'seal', 'wrench', 'tag', 'horn', 'house']] = None,
bucket_id: Optional[str] = None,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> KnowledgeInfo:
body = deepcopy_minimal(
{
"embedding_id": embedding_id,
"name": name,
"customer_identifier": customer_identifier,
"description": description,
"background": background,
"icon": icon,
"bucket_id": bucket_id,
}
)
return self._post(
"/knowledge",
body=maybe_transform(body, knowledge_create_params.KnowledgeBaseParams),
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=KnowledgeInfo,
)
def modify(
self,
knowledge_id: str,
embedding_id: int,
*,
name: str,
description: Optional[str] = None,
background: Optional[Literal['blue', 'red', 'orange', 'purple', 'sky']] = None,
icon: Optional[Literal['question', 'book', 'seal', 'wrench', 'tag', 'horn', 'house']] = None,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> httpx.Response:
body = deepcopy_minimal(
{
"id": knowledge_id,
"embedding_id": embedding_id,
"name": name,
"description": description,
"background": background,
"icon": icon,
}
)
return self._put(
f"/knowledge/{knowledge_id}",
body=maybe_transform(body, knowledge_create_params.KnowledgeBaseParams),
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=httpx.Response,
)
def query(
self,
*,
page: int | NotGiven = 1,
size: int | NotGiven = 10,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> KnowledgePage:
return self._get(
"/knowledge",
options=make_request_options(
extra_headers=extra_headers,
extra_body=extra_body,
timeout=timeout,
query=maybe_transform(
{
"page": page,
"size": size,
},
knowledge_list_params.KnowledgeListParams,
),
),
cast_type=KnowledgePage,
)
def delete(
self,
knowledge_id: str,
*,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> httpx.Response:
"""
Delete a file.
Args:
knowledge_id: 知识库ID
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 knowledge_id:
raise ValueError(f"Expected a non-empty value for `knowledge_id`")
return self._delete(
f"/knowledge/{knowledge_id}",
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=httpx.Response,
)
def used(
self,
*,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> KnowledgeUsed:
"""
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
"""
return self._get(
f"/knowledge/capacity",
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=KnowledgeUsed,
)
================================================
FILE: zhipuai/api_resource/moderation/__init__.py
================================================
from .moderations import (
Moderations
)
__all__ = [
'Moderations'
]
================================================
FILE: zhipuai/api_resource/moderation/moderations.py
================================================
from __future__ import annotations
from typing import Union, List, TYPE_CHECKING, Dict
import logging
from ...core import BaseAPI, deepcopy_minimal
from ...types.moderation.moderation_completion import Completion
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from ..._client import ZhipuAI
__all__ = ["Moderations"]
class Moderations(BaseAPI):
def __init__(self, client: "ZhipuAI") -> None:
super().__init__(client)
def create(
self,
*,
model: str,
input: Union[str, List[str], Dict],
) -> Completion:
body = deepcopy_minimal({
"model": model,
"input": input
})
return self._post(
"/moderations",
body=body,
cast_type=Completion
)
================================================
FILE: zhipuai/api_resource/tools/__init__.py
================================================
from .tools import Tools
__all__ = ['Tools']
================================================
FILE: zhipuai/api_resource/tools/tools.py
================================================
from __future__ import annotations
from typing import TYPE_CHECKING, List, Union, Dict, Optional
from typing_extensions import Literal
from ...core import NOT_GIVEN, Body, Headers, NotGiven, BaseAPI, maybe_transform, StreamResponse, deepcopy_minimal
import httpx
from ...core import (
make_request_options,
)
import logging
from ...types.tools import tools_web_search_params, WebSearch, WebSearchChunk
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from ..._client import ZhipuAI
__all__ = ["Tools"]
class Tools(BaseAPI):
def __init__(self, client: "ZhipuAI") -> None:
super().__init__(client)
def web_search(
self,
*,
model: str,
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],
scope: Optional[str] | NotGiven = NOT_GIVEN,
location: Optional[str] | NotGiven = NOT_GIVEN,
recent_days: Optional[int] | NotGiven = NOT_GIVEN,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> WebSearch | StreamResponse[WebSearchChunk]:
body = deepcopy_minimal(
{
"model": model,
"request_id": request_id,
"messages": messages,
"stream": stream,
"scope": scope,
"location": location,
"recent_days": recent_days,
})
return self._post(
"/tools",
body= maybe_transform(body, tools_web_search_params.WebSearchParams),
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=WebSearch,
stream=stream or False,
stream_cls=StreamResponse[WebSearchChunk],
)
================================================
FILE: zhipuai/api_resource/videos/__init__.py
================================================
from .videos import (
Videos,
)
__all__ = [
'Videos',
]
================================================
FILE: zhipuai/api_resource/videos/videos.py
================================================
from __future__ import annotations
from typing import TYPE_CHECKING, List, Mapping, cast, Optional, Dict
from typing_extensions import Literal
from ...types.sensitive_word_check import SensitiveWordCheckRequest
from ...types.video import video_create_params
from ...types.video import VideoObject
from ...core import BaseAPI, maybe_transform
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
__all__ = ["Videos"]
class Videos(BaseAPI):
def __init__(self, client: "ZhipuAI") -> None:
super().__init__(client)
def generations(
self,
model: str,
*,
prompt: str = None,
image_url: object = None,
quality: str = None,
with_audio: bool = None,
size: str = None,
duration: int = None,
fps: int = 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,
) -> VideoObject:
if not model and not model:
raise ValueError("At least one of `model` and `prompt` must be provided.")
body = deepcopy_minimal(
{
"model": model,
"prompt": prompt,
"image_url": image_url,
"sensitive_word_check": sensitive_word_check,
"request_id": request_id,
"user_id": user_id,
"quality": quality,
"with_audio": with_audio,
"size": size,
"duration": duration,
"fps": fps
}
)
return self._post(
"/videos/generations",
body=maybe_transform(body, video_create_params.VideoCreateParams),
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=VideoObject,
)
def retrieve_videos_result(
self,
id: str,
*,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> VideoObject:
if not id:
raise ValueError("At least one of `id` must be provided.")
return self._get(
f"/async-result/{id}",
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=VideoObject,
)
================================================
FILE: zhipuai/api_resource/web_search/__init__.py
================================================
from .web_search import WebSearchApi
__all__ = ['WebSearchApi']
================================================
FILE: zhipuai/api_resource/web_search/web_search.py
================================================
from __future__ import annotations
from typing import TYPE_CHECKING, List, Union, Dict, Optional
from ...types.sensitive_word_check import SensitiveWordCheckRequest
from ...core import NOT_GIVEN, Body, Headers, NotGiven, BaseAPI, maybe_transform, StreamResponse, deepcopy_minimal
import httpx
from ...core import (
make_request_options,
)
import logging
from ...types.web_search import web_search_create_params
from ...types.web_search.web_search_resp import WebSearchResp
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from ..._client import ZhipuAI
__all__ = ["WebSearchApi"]
class WebSearchApi(BaseAPI):
def __init__(self, client: "ZhipuAI") -> None:
super().__init__(client)
def web_search(
self,
*,
request_id: Optional[str] | NotGiven = NOT_GIVEN,
search_engine: Optional[str] | NotGiven = NOT_GIVEN,
search_query: Optional[str] | NotGiven = NOT_GIVEN,
user_id: Optional[str] | NotGiven = NOT_GIVEN,
sensitive_word_check: Optional[SensitiveWordCheckRequest] | NotGiven = NOT_GIVEN,
count: Optional[int] | NotGiven = NOT_GIVEN,
search_domain_filter: Optional[str] | NotGiven = NOT_GIVEN,
search_recency_filter: Optional[str] | NotGiven = NOT_GIVEN,
content_size: Optional[str] | NotGiven = NOT_GIVEN,
search_intent: Optional[bool] | NotGiven = NOT_GIVEN,
location: Optional[str] | NotGiven = NOT_GIVEN,
extra_headers: Headers | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> WebSearchResp:
body = deepcopy_minimal(
{
"request_id": request_id,
"search_engine": search_engine,
"search_query": search_query,
"user_id": user_id,
"sensitive_word_check": sensitive_word_check,
"count":count,
"search_domain_filter": search_domain_filter,
"search_recency_filter": search_recency_filter,
"content_size": content_size,
"search_intent": search_intent,
"location": location
})
return self._post(
"/web_search",
body= maybe_transform(body, web_search_create_params.WebSearchCreatParams),
options=make_request_options(
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
),
cast_type=WebSearchResp
)
================================================
FILE: zhipuai/core/__init__.py
================================================
from ._base_models import (
BaseModel,
construct_type
)
from ._base_api import BaseAPI
from ._base_type import (
NOT_GIVEN,
Headers,
NotGiven,
Body,
IncEx,
ModelT,
Query,
FileTypes,
)
from ._base_compat import (
PYDANTIC_V2,
ConfigDict,
GenericModel,
get_args,
is_union,
parse_obj,
get_origin,
is_literal_type,
get_model_config,
get_model_fields,
field_get_default,
cached_property,
)
from ._files import (
is_file_content
)
from ._errors import (
ZhipuAIError,
APIStatusError,
APIRequestFailedError,
APIAuthenticationError,
APIReachLimitError,
APIInternalError,
APIServerFlowExceedError,
APIResponseError,
APIResponseValidationError,
APIConnectionError,
APITimeoutError,
)
from ._http_client import (
make_request_options,
HttpClient
)
from ._utils import (
is_list,
is_mapping,
parse_date,
parse_datetime,
is_given,
maybe_transform,
deepcopy_minimal,
extract_files,
drop_prefix_image_data,
)
from ._sse_client import StreamResponse
from ._constants import (
ZHIPUAI_DEFAULT_TIMEOUT,
ZHIPUAI_DEFAULT_MAX_RETRIES,
ZHIPUAI_DEFAULT_LIMITS,
)
__all__ = [
"BaseModel",
"construct_type",
"BaseAPI",
"NOT_GIVEN",
"Headers",
"NotGiven",
"Body",
"IncEx",
"ModelT",
"Query",
"FileTypes",
"PYDANTIC_V2",
"ConfigDict",
"GenericModel",
"get_args",
"is_union",
"parse_obj",
"get_origin",
"is_literal_type",
"get_model_config",
"get_model_fields",
"field_get_default",
"is_file_content",
"ZhipuAIError",
"APIStatusError",
"APIRequestFailedError",
"APIAuthenticationError",
"APIReachLimitError",
"APIInternalError",
"APIServerFlowExceedError",
"APIResponseError",
"APIResponseValidationError",
"APITimeoutError",
"make_request_options",
"HttpClient",
"ZHIPUAI_DEFAULT_TIMEOUT",
"ZHIPUAI_DEFAULT_MAX_RETRIES",
"ZHIPUAI_DEFAULT_LIMITS",
"is_list",
"is_mapping",
"parse_date",
"parse_datetime",
"is_given",
"maybe_transform",
"deepcopy_minimal",
"extract_files",
"StreamResponse",
]
================================================
FILE: zhipuai/core/_base_api.py
================================================
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .._client import ZhipuAI
class BaseAPI:
_client: ZhipuAI
def __init__(self, client: ZhipuAI) -> None:
self._client = client
self._delete = client.delete
self._get = client.get
self._post = client.post
self._put = client.put
self._patch = client.patch
self._get_api_list = client.get_api_list
================================================
FILE: zhipuai/core/_base_compat.py
================================================
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
from datetime import date, datetime
from typing_extensions import Self
import pydantic
from pydantic.fields import FieldInfo
from zhipuai.core._base_type import StrBytesIntFloat
_T = TypeVar("_T")
_ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
# --------------- Pydantic v2 compatibility ---------------
# Pyright incorrectly reports some of our functions as overriding a method when they don't
# pyright: reportIncompatibleMethodOverride=false
PYDANTIC_V2 = pydantic.VERSION.startswith("2.")
# v1 re-exports
if TYPE_CHECKING:
def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001
...
def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001
...
def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001
...
def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001
...
def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001
...
def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001
...
def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001
...
else:
if PYDANTIC_V2:
from pydantic.v1.typing import (
get_args as get_args,
is_union as is_union,
get_origin as get_origin,
is_typeddict as is_typeddict,
is_literal_type as is_literal_type,
)
from pydantic.v1.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
else:
from pydantic.typing import (
get_args as get_args,
is_union as is_union,
get_origin as get_origin,
is_typeddict as is_typeddict,
is_literal_type as is_literal_type,
)
from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
# refactored config
if TYPE_CHECKING:
from pydantic import ConfigDict as ConfigDict
else:
if PYDANTIC_V2:
from pydantic import ConfigDict
else:
# TODO: provide an error message here?
ConfigDict = None
# renamed methods / properties
def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
if PYDANTIC_V2:
return model.model_validate(value)
else:
return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
def field_is_required(field: FieldInfo) -> bool:
if PYDANTIC_V2:
return field.is_required()
return field.required # type: ignore
def field_get_default(field: FieldInfo) -> Any:
value = field.get_default()
if PYDANTIC_V2:
from pydantic_core import PydanticUndefined
if value == PydanticUndefined:
return None
return value
return value
def field_outer_type(field: FieldInfo) -> Any:
if PYDANTIC_V2:
return field.annotation
return field.outer_type_ # type: ignore
def get_model_config(model: type[pydantic.BaseModel]) -> Any:
if PYDANTIC_V2:
return model.model_config
return model.__config__ # type: ignore
def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]:
if PYDANTIC_V2:
return model.model_fields
return model.__fields__ # type: ignore
def model_copy(model: _ModelT) -> _ModelT:
if PYDANTIC_V2:
return model.model_copy()
return model.copy() # type: ignore
def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
if PYDANTIC_V2:
return model.model_dump_json(indent=indent)
return model.json(indent=indent) # type: ignore
def model_dump(
model: pydantic.BaseModel,
*,
exclude_unset: bool = False,
exclude_defaults: bool = False,
) -> dict[str, Any]:
if PYDANTIC_V2:
return model.model_dump(
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
)
return cast(
"dict[str, Any]",
model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
),
)
def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
if PYDANTIC_V2:
return model.model_validate(data)
return model.parse_obj(data) # pyright: ignore[reportDeprecated]
# generic models
if TYPE_CHECKING:
class GenericModel(pydantic.BaseModel):
...
else:
if PYDANTIC_V2:
# there no longer needs to be a distinction in v2 but
# we still have to create our own subclass to avoid
# inconsistent MRO ordering errors
class GenericModel(pydantic.BaseModel):
...
else:
import pydantic.generics
class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel):
...
# cached properties
if TYPE_CHECKING:
cached_property = property
# we define a separate type (copied from typeshed)
# that represents that `cached_property` is `set`able
# at runtime, which differs from `@property`.
#
# this is a separate type as editors likely special case
# `@property` and we don't want to cause issues just to have
# more helpful internal types.
class typed_cached_property(Generic[_T]):
func: Callable[[Any], _T]
attrname: str | None
def __init__(self, func: Callable[[Any], _T]) -> None:
...
@overload
def __get__(self, instance: None, owner: type[Any] | None = None) -> Self:
...
@overload
def __get__(self, instance: object, owner: type[Any] | None = None) -> _T:
...
def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self:
raise NotImplementedError()
def __set_name__(self, owner: type[Any], name: str) -> None:
...
# __set__ is not defined at runtime, but @cached_property is designed to be settable
def __set__(self, instance: object, value: _T) -> None:
...
else:
try:
from functools import cached_property as cached_property
except ImportError:
from cached_property import cached_property as cached_property
typed_cached_property = cached_property
================================================
FILE: zhipuai/core/_base_models.py
================================================
from __future__ import annotations
import inspect
import os
from typing import TYPE_CHECKING, Any, Type, Generic, TypeVar, cast, Dict, Callable
from datetime import date, datetime
from typing_extensions import (
Literal,
ClassVar,
Protocol,
override,
runtime_checkable, TypeGuard, ParamSpec,
)
import pydantic
import pydantic.generics
from pydantic.fields import FieldInfo
from pydantic import root_validator
from ._base_type import (
IncEx,
ModelT,
)
from ._utils import is_list, is_mapping, parse_date, parse_datetime, is_annotated_type, extract_type_arg, \
strip_annotated_type, PropertyInfo, coerce_boolean
from ._base_compat import (
PYDANTIC_V2,
ConfigDict,
GenericModel as BaseGenericModel,
get_args,
is_union,
parse_obj,
get_origin,
is_literal_type,
get_model_config,
get_model_fields,
field_get_default,
)
if TYPE_CHECKING:
from pydantic_core.core_schema import ModelField, LiteralSchema, ModelFieldsSchema
__all__ = ["BaseModel", "GenericModel"]
_BaseModelT = TypeVar("_BaseModelT", bound="BaseModel")
_T = TypeVar("_T")
P = ParamSpec("P")
@runtime_checkable
class _ConfigProtocol(Protocol):
allow_population_by_field_name: bool
class BaseModel(pydantic.BaseModel):
if PYDANTIC_V2:
model_config: ClassVar[ConfigDict] = ConfigDict(
extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
)
else:
@property
@override
def model_fields_set(self) -> set[str]:
# a forwards-compat shim for pydantic v2
return self.__fields_set__ # type: ignore
class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
extra: Any = pydantic.Extra.allow # type: ignore
def to_dict(
self,
*,
mode: Literal["json", "python"] = "python",
use_api_names: bool = True,
exclude_unset: bool = True,
exclude_defaults: bool = False,
exclude_none: bool = False,
warnings: bool = True,
) -> dict[str, object]:
"""Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
By default, fields that were not set by the API will not be included,
and keys will match the API response, *not* the property names from the model.
For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
Args:
mode:
If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
exclude_unset: Whether to exclude fields that have not been explicitly set.
exclude_defaults: Whether to exclude fields that are set to their default value from the output.
exclude_none: Whether to exclude fields that have a value of `None` from the output.
warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
"""
return self.model_dump(
mode=mode,
by_alias=use_api_names,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
warnings=warnings,
)
def to_json(
self,
*,
indent: int | None = 2,
use_api_names: bool = True,
exclude_unset: bool = True,
exclude_defaults: bool = False,
exclude_none: bool = False,
warnings: bool = True,
) -> str:
"""Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
By default, fields that were not set by the API will not be included,
and keys will match the API response, *not* the property names from the model.
For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
Args:
indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
exclude_unset: Whether to exclude fields that have not been explicitly set.
exclude_defaults: Whether to exclude fields that have the default value.
exclude_none: Whether to exclude fields that have a value of `None`.
warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
"""
return self.model_dump_json(
indent=indent,
by_alias=use_api_names,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
warnings=warnings,
)
@override
def __str__(self) -> str:
# mypy complains about an invalid self arg
return f'{self.__repr_name__()}({self.__repr_str__(", ")})' # type: ignore[misc]
# Override the 'construct' method in a way that supports recursive parsing without validation.
# Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
@classmethod
@override
def construct(
cls: Type[ModelT],
_fields_set: set[str] | None = None,
**values: object,
) -> ModelT:
m = cls.__new__(cls)
fields_values: dict[str, object] = {}
config = get_model_config(cls)
populate_by_name = (
config.allow_population_by_field_name
if isinstance(config, _ConfigProtocol)
else config.get("populate_by_name")
)
if _fields_set is None:
_fields_set = set()
model_fields = get_model_fields(cls)
for name, field in model_fields.items():
key = field.alias
if key is None or (key not in values and populate_by_name):
key = name
if key in values:
fields_values[name] = _construct_field(value=values[key], field=field, key=key)
_fields_set.add(name)
else:
fields_values[name] = field_get_default(field)
_extra = {}
for key, value in values.items():
if key not in model_fields:
if PYDANTIC_V2:
_extra[key] = value
else:
_fields_set.add(key)
fields_values[key] = value
object.__setattr__(m, "__dict__", fields_values)
if PYDANTIC_V2:
# these properties are copied from Pydantic's `model_construct()` method
object.__setattr__(m, "__pydantic_private__", None)
object.__setattr__(m, "__pydantic_extra__", _extra)
object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
else:
# init_private_attributes() does not exist in v2
m._init_private_attributes() # type: ignore
# copied from Pydantic v1's `construct()` method
object.__setattr__(m, "__fields_set__", _fields_set)
return m
if not TYPE_CHECKING:
# type checkers incorrectly complain about this assignment
# because the type signatures are technically different
# although not in practice
model_construct = construct
if not PYDANTIC_V2:
# we define aliases for some of the new pydantic v2 methods so
# that we can just document these methods without having to specify
# a specific pydantic version as some users may not know which
# pydantic version they are currently using
@override
def model_dump(
self,
*,
mode: Literal["json", "python"] | str = "python",
include: IncEx = None,
exclude: IncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool | Literal["none", "warn", "error"] = True,
context: dict[str, Any] | None = None,
serialize_as_any: bool = False,
) -> dict[str, Any]:
"""Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Args:
mode: The mode in which `to_python` should run.
If mode is 'json', the dictionary will only contain JSON serializable types.
If mode is 'python', the dictionary may contain any Python objects.
include: A list of fields to include in the output.
exclude: A list of fields to exclude from the output.
by_alias: Whether to use the field's alias in the dictionary key if defined.
exclude_unset: Whether to exclude fields that are unset or None from the output.
exclude_defaults: Whether to exclude fields that are set to their default value from the output.
exclude_none: Whether to exclude fields that have a value of `None` from the output.
round_trip: Whether to enable serialization and deserialization round-trip support.
warnings: Whether to log warnings when invalid fields are encountered.
Returns:
A dictionary representation of the model.
"""
if mode != "python":
raise ValueError("mode is only supported in Pydantic v2")
if round_trip != False:
raise ValueError("round_trip is only supported in Pydantic v2")
if warnings != True:
raise ValueError("warnings is only supported in Pydantic v2")
if context is not None:
raise ValueError("context is only supported in Pydantic v2")
if serialize_as_any != False:
raise ValueError("serialize_as_any is only supported in Pydantic v2")
return super().dict( # pyright: ignore[reportDeprecated]
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
)
@override
def model_dump_json(
self,
*,
indent: int | None = None,
include: IncEx = None,
exclude: IncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool | Literal["none", "warn", "error"] = True,
context: dict[str, Any] | None = None,
serialize_as_any: bool = False,
) -> str:
"""Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
Generates a JSON representation of the model using Pydantic's `to_json` method.
Args:
indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
include: Field(s) to include in the JSON output. Can take either a string or set of strings.
exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings.
by_alias: Whether to serialize using field aliases.
exclude_unset: Whether to exclude fields that have not been explicitly set.
exclude_defaults: Whether to exclude fields that have the default value.
exclude_none: Whether to exclude fields that have a value of `None`.
round_trip: Whether to use serialization/deserialization between JSON and class instance.
warnings: Whether to show any warnings that occurred during serialization.
Returns:
A JSON string representation of the model.
"""
if round_trip != False:
raise ValueError("round_trip is only supported in Pydantic v2")
if warnings != True:
raise ValueError("warnings is only supported in Pydantic v2")
if context is not None:
raise ValueError("context is only supported in Pydantic v2")
if serialize_as_any != False:
raise ValueError("serialize_as_any is only supported in Pydantic v2")
return super().json( # type: ignore[reportDeprecated]
indent=indent,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
)
def _construct_field(value: object, field: FieldInfo, key: str) -> object:
if value is None:
return field_get_default(field)
if PYDANTIC_V2:
type_ = field.annotation
else:
type_ = cast(type, field.outer_type_) # type: ignore
if type_ is None:
raise RuntimeError(f"Unexpected field type is None for {key}")
return construct_type(value=value, type_=type_)
def is_basemodel(type_: type) -> bool:
"""Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
if is_union(type_):
for variant in get_args(type_):
if is_basemodel(variant):
return True
return False
return is_basemodel_type(type_)
def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]:
origin = get_origin(type_) or type_
return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
def build(
base_model_cls: Callable[P, _BaseModelT],
*args: P.args,
**kwargs: P.kwargs,
) -> _BaseModelT:
"""Construct a BaseModel class without validation.
This is useful for cases where you need to instantiate a `BaseModel`
from an API response as this provides type-safe params which isn't supported
by helpers like `construct_type()`.
```py
build(MyModel, my_field_a="foo", my_field_b=123)
```
"""
if args:
raise TypeError(
"Received positional arguments which are not supported; Keyword arguments must be used instead",
)
return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs))
def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T:
"""Loose coercion to the expected type with construction of nested values.
Note: the returned value from this function is not guaranteed to match the
given type.
"""
return cast(_T, construct_type(value=value, type_=type_))
def construct_type(*, value: object, type_: type) -> object:
"""Loose coercion to the expected type with construction of nested values.
If the given value does not match the expected type then it is returned as-is.
"""
# we allow `object` as the input type because otherwise, passing things like
# `Literal['value']` will be reported as a type error by type checkers
type_ = cast("type[object]", type_)
# unwrap `Annotated[T, ...]` -> `T`
if is_annotated_type(type_):
meta: tuple[Any, ...] = get_args(type_)[1:]
type_ = extract_type_arg(type_, 0)
else:
meta = tuple()
# we need to use the origin class for any types that are subscripted generics
# e.g. Dict[str, object]
origin = get_origin(type_) or type_
args = get_args(type_)
if is_union(origin):
try:
return validate_type(type_=cast("type[object]", type_), value=value)
except Exception:
pass
# if the type is a discriminated union then we want to construct the right variant
# in the union, even if the data doesn't match exactly, otherwise we'd break code
# that relies on the constructed class types, e.g.
#
# class FooType:
# kind: Literal['foo']
# value: str
#
# class BarType:
# kind: Literal['bar']
# value: int
#
# without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then
# we'd end up constructing `FooType` when it should be `BarType`.
discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta)
if discriminator and is_mapping(value):
variant_value = value.get(discriminator.field_alias_from or discriminator.field_name)
if variant_value and isinstance(variant_value, str):
variant_type = discriminator.mapping.get(variant_value)
if variant_type:
return construct_type(type_=variant_type, value=value)
# if the data is not valid, use the first variant that doesn't fail while deserializing
for variant in args:
try:
return construct_type(value=value, type_=variant)
except Exception:
continue
raise RuntimeError(f"Could not convert data into a valid instance of {type_}")
if origin == dict:
if not is_mapping(value):
return value
_, items_type = get_args(type_) # Dict[_, items_type]
return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}
if not is_literal_type(type_) and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)):
if is_list(value):
return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value]
if is_mapping(value):
if issubclass(type_, BaseModel):
return type_.construct(**value) # type: ignore[arg-type]
return cast(Any, type_).construct(**value)
if origin == list:
if not is_list(value):
return value
inner_type = args[0] # List[inner_type]
return [construct_type(value=entry, type_=inner_type) for entry in value]
if origin == float:
if isinstance(value, int):
coerced = float(value)
if coerced != value:
return value
return coerced
return value
if type_ == datetime:
try:
return parse_datetime(value) # type: ignore
except Exception:
return value
if type_ == date:
try:
return parse_date(value) # type: ignore
except Exception:
return value
return value
@runtime_checkable
class CachedDiscriminatorType(Protocol):
__discriminator__: DiscriminatorDetails
class DiscriminatorDetails:
field_name: str
"""The name of the discriminator field in the variant class, e.g.
```py
class Foo(BaseModel):
type: Literal['foo']
```
Will result in field_name='type'
"""
field_alias_from: str | None
"""The name of the discriminator field in the API response, e.g.
```py
class Foo(BaseModel):
type: Literal['foo'] = Field(alias='type_from_api')
```
Will result in field_alias_from='type_from_api'
"""
mapping: dict[str, type]
"""Mapping of discriminator value to variant type, e.g.
{'foo': FooVariant, 'bar': BarVariant}
"""
def __init__(
self,
*,
mapping: dict[str, type],
discriminator_field: str,
discriminator_alias: str | None,
) -> None:
self.mapping = mapping
self.field_name = discriminator_field
self.field_alias_from = discriminator_alias
def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
if isinstance(union, CachedDiscriminatorType):
return union.__discriminator__
discriminator_field_name: str | None = None
for annotation in meta_annotations:
if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None:
discriminator_field_name = annotation.discriminator
break
if not discriminator_field_name:
return None
mapping: dict[str, type] = {}
discriminator_alias: str | None = None
for variant in get_args(union):
variant = strip_annotated_type(variant)
if is_basemodel_type(variant):
if PYDANTIC_V2:
field = _extract_field_schema_pv2(variant, discriminator_field_name)
if not field:
continue
# Note: if one variant defines an alias then they all should
discriminator_alias = field.get("serialization_alias")
field_schema = field["schema"]
if field_schema["type"] == "literal":
for entry in cast("LiteralSchema", field_schema)["expected"]:
if isinstance(entry, str):
mapping[entry] = variant
else:
field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(
discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
if not field_info:
continue
# Note: if one variant defines an alias then they all should
discriminator_alias = field_info.alias
if field_info.annotation and is_literal_type(field_info.annotation):
for entry in get_args(field_info.annotation):
if isinstance(entry, str):
mapping[entry] = variant
if not mapping:
return None
details = DiscriminatorDetails(
mapping=mapping,
discriminator_field=discriminator_field_name,
discriminator_alias=discriminator_alias,
)
cast(CachedDiscriminatorType, union).__discriminator__ = details
return details
def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None:
schema = model.__pydantic_core_schema__
if schema["type"] != "model":
return None
fields_schema = schema["schema"]
if fields_schema["type"] != "model-fields":
return None
fields_schema = cast("ModelFieldsSchema", fields_schema)
field = fields_schema["fields"].get(field_name)
if not field:
return None
return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast]
def validate_type(*, type_: type[_T], value: object) -> _T:
"""Strict validation that the given value matches the expected type"""
if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
return cast(_T, parse_obj(type_, value))
return cast(_T, _validate_non_model_type(type_=type_, value=value))
# our use of subclasssing here causes weirdness for type checkers,
# so we just pretend that we don't subclass
if TYPE_CHECKING:
GenericModel = BaseModel
else:
class GenericModel(BaseGenericModel, BaseModel):
pass
if PYDANTIC_V2:
from pydantic import TypeAdapter
def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
return TypeAdapter(type_).validate_python(value)
elif not TYPE_CHECKING:
class TypeAdapter(Generic[_T]):
"""Used as a placeholder to easily convert runtime types to a Pydantic format
to provide validation.
For example:
```py
validated = RootModel[int](__root__="5").__root__
# validated: 5
```
"""
def __init__(self, type_: Type[_T]):
self.type_ = type_
def validate_python(self, value: Any) -> _T:
if not isinstance(value, self.type_):
raise ValueError(f"Invalid type: {value} is not of type {self.type_}")
return value
def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
return TypeAdapter(type_).validate_python(value)
================================================
FILE: zhipuai/core/_base_type.py
================================================
from __future__ import annotations
from os import PathLike
from typing import (
IO,
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Mapping,
TypeVar,
Callable,
Optional,
Sequence,
)
import pydantic
from httpx import Response
from typing_extensions import Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable
Query = Mapping[str, object]
Body = object
AnyMapping = Mapping[str, object]
PrimitiveData = Union[str, int, float, bool, None]
Data = Union[PrimitiveData, List[Any], Tuple[Any], "Mapping[str, Any]"]
ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
_T = TypeVar("_T")
if TYPE_CHECKING:
NoneType: Type[None]
else:
NoneType = type(None)
# Sentinel class used until PEP 0661 is accepted
class NotGiven:
"""
A sentinel singleton class used to distinguish omitted keyword arguments
from those passed in with the value None (which may have different behavior).
For example:
```py
def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ...
get(timeout=1) # 1s timeout
get(timeout=None) # No timeout
get() # Default timeout behavior, which may not be statically known at the method definition.
```
"""
def __bool__(self) -> Literal[False]:
return False
@override
def __repr__(self) -> str:
return "NOT_GIVEN"
NotGivenOr = Union[_T, NotGiven]
NOT_GIVEN = NotGiven()
class Omit:
"""In certain situations you need to be able to represent a case where a default value has
to be explicitly removed and `None` is not an appropriate substitute, for example:
```py
# as the default `Content-Type` header is `application/json` that will be sent
client.post('/upload/files', files={'file': b'my raw file content'})
# you can't explicitly override the header as it has to be dynamically generated
# to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
client.post(..., headers={'Content-Type': 'multipart/form-data'})
# instead you can remove the default `application/json` header by passing Omit
client.post(..., headers={'Content-Type': Omit()})
```
"""
def __bool__(self) -> Literal[False]:
return False
@runtime_checkable
class ModelBuilderProtocol(Protocol):
@classmethod
def build(
cls: type[_T],
*,
response: Response,
data: object,
) -> _T:
...
Headers = Mapping[str, Union[str, Omit]]
class HeadersLikeProtocol(Protocol):
def get(self, __key: str) -> str | None:
...
HeadersLike = Union[Headers, HeadersLikeProtocol]
ResponseT = TypeVar(
"ResponseT",
bound="Union[str, None, BaseModel, List[Any], Dict[str, Any], Response, UnknownResponse, ModelBuilderProtocol, BinaryResponseContent]",
)
StrBytesIntFloat = Union[str, bytes, int, float]
# Note: copied from Pydantic
# https://github.com/pydantic/pydantic/blob/32ea570bf96e84234d2992e1ddf40ab8a565925a/pydantic/main.py#L49
IncEx: TypeAlias = "set[int] | set[str] | dict[int, Any] | dict[str, Any] | None"
PostParser = Callable[[Any], Any]
@runtime_checkable
class InheritsGeneric(Protocol):
"""Represents a type that has inherited from `Generic`
The `__orig_bases__` property can be used to determine the resolved
type variable for a given base class.
"""
__orig_bases__: tuple[_GenericAlias]
class _GenericAlias(Protocol):
__origin__: type[object]
class HttpxSendArgs(TypedDict, total=False):
auth: httpx.Auth
# for user input files
if TYPE_CHECKING:
Base64FileInput = Union[IO[bytes], PathLike[str]]
FileContent = Union[IO[bytes], bytes, PathLike[str]]
else:
Base64FileInput = Union[IO[bytes], PathLike]
FileContent = Union[IO[bytes], bytes, PathLike]
FileTypes = Union[
# file (or bytes)
FileContent,
# (filename, file (or bytes))
Tuple[Optional[str], FileContent],
# (filename, file (or bytes), content_type)
Tuple[Optional[str], FileContent, Optional[str]],
# (filename, file (or bytes), content_type, headers)
Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
]
RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
# duplicate of the above but without our custom file support
HttpxFileContent = Union[bytes, IO[bytes]]
HttpxFileTypes = Union[
# file (or bytes)
HttpxFileContent,
# (filename, file (or bytes))
Tuple[Optional[str], HttpxFileContent],
# (filename, file (or bytes), content_type)
Tuple[Optional[str], HttpxFileContent, Optional[str]],
# (filename, file (or bytes), content_type, headers)
Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]],
]
HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]]
================================================
FILE: zhipuai/core/_constants.py
================================================
import httpx
RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response"
# 通过 `Timeout` 控制接口`connect` 和 `read` 超时时间,默认为`timeout=300.0, connect=8.0`
ZHIPUAI_DEFAULT_TIMEOUT = httpx.Timeout(timeout=300.0, connect=8.0)
# 通过 `retry` 参数控制重试次数,默认为3次
ZHIPUAI_DEFAULT_MAX_RETRIES = 3
# 通过 `Limits` 控制最大连接数和保持连接数,默认为`max_connections=50, max_keepalive_connections=10`
ZHIPUAI_DEFAULT_LIMITS = httpx.Limits(max_connections=50, max_keepalive_connections=10)
INITIAL_RETRY_DELAY = 0.5
MAX_RETRY_DELAY = 8.0
================================================
FILE: zhipuai/core/_errors.py
================================================
from __future__ import annotations
import httpx
__all__ = [
"ZhipuAIError",
"APIStatusError",
"APIRequestFailedError",
"APIAuthenticationError",
"APIReachLimitError",
"APIInternalError",
"APIServerFlowExceedError",
"APIResponseError",
"APIResponseValidationError",
"APITimeoutError",
"APIConnectionError",
]
class ZhipuAIError(Exception):
def __init__(self, message: str, ) -> None:
super().__init__(message)
class APIStatusError(ZhipuAIError):
response: httpx.Response
status_code: int
def __init__(self, message: str, *, response: httpx.Response) -> None:
super().__init__(message)
self.response = response
self.status_code = response.status_code
class APIRequestFailedError(APIStatusError):
...
class APIAuthenticationError(APIStatusError):
...
class APIReachLimitError(APIStatusError):
...
class APIInternalError(APIStatusError):
...
class APIServerFlowExceedError(APIStatusError):
...
class APIResponseError(ZhipuAIError):
message: str
request: httpx.Request
json_data: object
def __init__(self, message: str, request: httpx.Request, json_data: object):
self.message = message
self.request = request
self.json_data = json_data
super().__init__(message)
class APIResponseValidationError(APIResponseError):
status_code: int
response: httpx.Response
def __init__(
self,
response: httpx.Response,
json_data: object | None, *,
message: str | None = None
) -> None:
super().__init__(
message=message or "Data returned by API invalid for expected schema.",
request=response.request,
json_data=json_data
)
self.response = response
self.status_code = response.status_code
class APIConnectionError(APIResponseError):
def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None:
super().__init__(message, request, json_data=None)
class APITimeoutError(APIConnectionError):
def __init__(self, request: httpx.Request) -> None:
super().__init__(message="Request timed out.", request=request)
================================================
FILE: zhipuai/core/_files.py
================================================
from __future__ import annotations
import io
import os
import pathlib
from typing import Mapping, Sequence, overload
from typing_extensions import TypeGuard
from ._base_type import (
FileTypes,
HttpxFileTypes,
HttpxRequestFiles,
RequestFiles,
Base64FileInput, FileContent, HttpxFileContent,
)
from ._utils import is_tuple_t, is_mapping_t, is_sequence_t
def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]:
return isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike)
def is_file_content(obj: object) -> TypeGuard[FileContent]:
return (
isinstance(obj, bytes) or isinstance(obj, tuple) or isinstance(obj, io.IOBase) or isinstance(obj,
os.PathLike)
)
def assert_is_file_content(obj: object, *, key: str | None = None) -> None:
if not is_file_content(obj):
prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`"
raise RuntimeError(
f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/openai/openai-python/tree/main#file-uploads"
) from None
@overload
def to_httpx_files(files: None) -> None:
...
@overload
def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles:
...
def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None:
if files is None:
return None
if is_mapping_t(files):
files = {key: _transform_file(file) for key, file in files.items()}
elif is_sequence_t(files):
files = [(key, _transform_file(file)) for key, file in files]
else:
raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence")
return files
def _transform_file(file: FileTypes) -> HttpxFileTypes:
if is_file_content(file):
if isinstance(file, os.PathLike):
path = pathlib.Path(file)
return (path.name, path.read_bytes())
return file
if is_tuple_t(file):
return (file[0], _read_file_content(file[1]), *file[2:])
raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
def _read_file_content(file: FileContent) -> HttpxFileContent:
if isinstance(file, os.PathLike):
return pathlib.Path(file).read_bytes()
return file
================================================
FILE: zhipuai/core/_http_client.py
================================================
# -*- coding:utf-8 -*-
from __future__ import annotations
import inspect
import warnings
from typing import (
Any,
Type,
Union,
cast,
Mapping,
TypeVar,
Dict,
overload, Optional, Literal, Generic, Iterator, TYPE_CHECKING
)
from random import random
import time
import httpx
import pydantic
from httpx import URL, Timeout
from . import _errors, get_origin
from ._base_compat import model_copy
from ._base_type import (
NotGiven,
ResponseT,
Body,
Headers,
NOT_GIVEN,
RequestFiles,
Query,
Data,
Omit,
AnyMapping,
ModelBuilderProtocol,
HttpxSendArgs, PostParser,
)
from ._constants import ZHIPUAI_DEFAULT_MAX_RETRIES, ZHIPUAI_DEFAULT_LIMITS, ZHIPUAI_DEFAULT_TIMEOUT, \
INITIAL_RETRY_DELAY, MAX_RETRY_DELAY, RAW_RESPONSE_HEADER
from ._errors import APIResponseValidationError, APIStatusError, APITimeoutError, APIConnectionError
from ._files import to_httpx_files
from ._legacy_response import LegacyAPIResponse
from ._request_opt import FinalRequestOptions, UserRequestInput
from ._response import BaseAPIResponse, APIResponse, extract_response_type
from ._sse_client import StreamResponse
from ._utils import flatten, is_mapping, is_given
from ._base_models import construct_type, GenericModel, validate_type
import logging
log: logging.Logger = logging.getLogger(__name__)
# TODO: make base page type vars covariant
SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]")
# AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]")
_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)
if TYPE_CHECKING:
from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT
else:
try:
from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT
except ImportError:
# taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366
HTTPX_DEFAULT_TIMEOUT = Timeout(5.0)
headers = {
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8",
}
class PageInfo:
"""Stores the necessary information to build the request to retrieve the next page.
Either `url` or `params` must be set.
"""
url: URL | NotGiven
params: Query | NotGiven
@overload
def __init__(
self,
*,
url: URL,
) -> None:
...
@overload
def __init__(
self,
*,
params: Query,
) -> None:
...
def __init__(
self,
*,
url: URL | NotGiven = NOT_GIVEN,
params: Query | NotGiven = NOT_GIVEN,
) -> None:
self.url = url
self.params = params
class BasePage(GenericModel, Generic[_T]):
"""
Defines the core interface for pagination.
Type Args:
ModelT: The pydantic model that represents an item in the response.
Methods:
has_next_page(): Check if there is another page available
next_page_info(): Get the necessary information to make a request for the next page
"""
_options: FinalRequestOptions = pydantic.PrivateAttr()
_model: Type[_T] = pydantic.PrivateAttr()
def has_next_page(self) -> bool:
items = self._get_page_items()
if not items:
return False
return self.next_page_info() is not None
def next_page_info(self) -> Optional[PageInfo]:
...
def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body]
...
def _params_from_url(self, url: URL) -> httpx.QueryParams:
# TODO: do we have to preprocess params here?
return httpx.QueryParams(cast(Any, self._options.params)).merge(url.params)
def _info_to_options(self, info: PageInfo) -> FinalRequestOptions:
options = model_copy(self._options)
options._strip_raw_response_header()
if not isinstance(info.params, NotGiven):
options.params = {**options.params, **info.params}
return options
if not isinstance(info.url, NotGiven):
params = self._params_from_url(info.url)
url = info.url.copy_with(params=params)
options.params = dict(url.params)
options.url = str(url)
return options
raise ValueError("Unexpected PageInfo state")
class BaseSyncPage(BasePage[_T], Generic[_T]):
_client: HttpClient = pydantic.PrivateAttr()
def _set_private_attributes(
self,
client: HttpClient,
model: Type[_T],
options: FinalRequestOptions,
) -> None:
self._model = model
self._client = client
self._options = options
# Pydantic uses a custom `__iter__` method to support casting BaseModels
# to dictionaries. e.g. dict(model).
# As we want to support `for item in page`, this is inherently incompatible
# with the default pydantic behaviour. It is not possible to support both
# use cases at once. Fortunately, this is not a big deal as all other pydantic
# methods should continue to work as expected as there is an alternative method
# to cast a model to a dictionary, model.dict(), which is used internally
# by pydantic.
def __iter__(self) -> Iterator[_T]: # type: ignore
for page in self.iter_pages():
for item in page._get_page_items():
yield item
def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]:
page = self
while True:
yield page
if page.has_next_page():
page = page.get_next_page()
else:
return
def get_next_page(self: SyncPageT) -> SyncPageT:
info = self.next_page_info()
if not info:
raise RuntimeError(
"No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
)
options = self._info_to_options(info)
return self._client._request_api_list(self._model, page=self.__class__, options=options)
class HttpClient:
_client: httpx.Client
_version: str
_base_url: URL
max_retries: int
timeout: Union[float, Timeout, None]
_limits: httpx.Limits
_has_custom_http_client: bool
_default_stream_cls: Type[StreamResponse[Any]] | None = None
_strict_response_validation: bool
def __init__(
self,
*,
version: str,
base_url: URL,
_strict_response_validation: bool,
max_retries: int = ZHIPUAI_DEFAULT_MAX_RETRIES,
timeout: Union[float, Timeout, None],
limits: httpx.Limits | None = None,
custom_httpx_client: httpx.Client | None = None,
custom_headers: Mapping[str, str] | None = None,
) -> None:
if limits is not None:
warnings.warn(
"The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead",
category=DeprecationWarning,
stacklevel=3,
)
if custom_httpx_client is not None:
raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`")
else:
limits = ZHIPUAI_DEFAULT_LIMITS
if not is_given(timeout):
if custom_httpx_client and custom_httpx_client.timeout != HTTPX_DEFAULT_TIMEOUT:
timeout = custom_httpx_client.timeout
else:
timeout = ZHIPUAI_DEFAULT_TIMEOUT
self.max_retries = max_retries
self.timeout = timeout
self._limits = limits
self._has_custom_http_client = bool(custom_httpx_client)
self._client = custom_httpx_client or httpx.Client(
base_url=base_url,
timeout=self.timeout,
limits=limits,
)
self._version = version
url = URL(url=base_url)
if not url.raw_path.endswith(b"/"):
url = url.copy_with(raw_path=url.raw_path + b"/")
self._base_url = url
self._custom_headers = custom_headers or {}
self._strict_response_validation = _strict_response_validation
def _prepare_url(self, url: str) -> URL:
sub_url = URL(url)
if sub_url.is_relative_url:
request_raw_url = self._base_url.raw_path + sub_url.raw_path.lstrip(b"/")
return self._base_url.copy_with(raw_path=request_raw_url)
return sub_url
@property
def _default_headers(self):
return \
{
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8",
"ZhipuAI-SDK-Ver": self._version,
"source_type": "zhipu-sdk-python",
"x-request-sdk": "zhipu-sdk-python",
**self.auth_headers,
**self._custom_headers,
}
@property
def custom_auth(self) -> httpx.Auth | None:
return None
@property
def auth_headers(self):
return {}
def _prepare_headers(self, options: FinalRequestOptions) -> httpx.Headers:
custom_headers = options.headers or {}
headers_dict = _merge_mappings(self._default_headers, custom_headers)
httpx_headers = httpx.Headers(headers_dict)
return httpx_headers
def _remaining_retries(
self,
remaining_retries: Optional[int],
options: FinalRequestOptions,
) -> int:
return remaining_retries if remaining_retries is not None else options.get_max_retries(self.max_retries)
def _calculate_retry_timeout(
self,
remaining_retries: int,
options: FinalRequestOptions,
response_headers: Optional[httpx.Headers] = None,
) -> float:
max_retries = options.get_max_retries(self.max_retries)
# If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says.
# retry_after = self._parse_retry_after_header(response_headers)
# if retry_after is not None and 0 < retry_after <= 60:
# return retry_after
nb_retries = max_retries - remaining_retries
# Apply exponential backoff, but not more than the max.
sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY)
# Apply some jitter, plus-or-minus half a second.
jitter = 1 - 0.25 * random()
timeout = sleep_seconds * jitter
return timeout if timeout >= 0 else 0
def _build_request(
self,
options: FinalRequestOptions
) -> httpx.Request:
kwargs: dict[str, Any] = {}
headers = self._prepare_headers(options)
url = self._prepare_url(options.url)
json_data = options.json_data
if options.extra_json is not None:
if json_data is None:
json_data = cast(Body, options.extra_json)
elif is_mapping(json_data):
json_data = _merge_mappings(json_data, options.extra_json)
else:
raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`")
content_type = headers.get("Content-Type")
# multipart/form-data; boundary=---abc--
if headers.get("Content-Type") == "multipart/form-data":
if "boundary" not in content_type:
# only remove the header if the boundary hasn't been explicitly set
# as the caller doesn't want httpx to come up with their own boundary
headers.pop("Content-Type")
if json_data:
kwargs["data"] = self._make_multipartform(json_data)
return self._client.build_request(
headers=headers,
timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout,
method=options.method,
url=url,
json=json_data,
files=options.files,
params=options.params,
**kwargs,
)
def _object_to_formfata(self, key: str, value: Data | Mapping[object, object]) -> list[tuple[str, str]]:
items = []
if isinstance(value, Mapping):
for k, v in value.items():
items.extend(self._object_to_formfata(f"{key}[{k}]", v))
return items
if isinstance(value, (list, tuple)):
for v in value:
items.extend(self._object_to_formfata(key + "[]", v))
return items
def _primitive_value_to_str(val) -> str:
# copied from httpx
if val is True:
return "true"
elif val is False:
return "false"
elif val is None:
return ""
return str(val)
str_data = _primitive_value_to_str(value)
if not str_data:
return []
return [(key, str_data)]
def _make_multipartform(self, data: Mapping[object, object]) -> dict[str, object]:
items = flatten([self._object_to_formfata(k, v) for k, v in data.items()])
serialized: dict[str, object] = {}
for key, value in items:
if key in serialized:
raise ValueError(f"存在重复的键: {key};")
serialized[key] = value
return serialized
def _process_response_data(
self,
*,
data: object,
cast_type: Type[ResponseT],
response: httpx.Response,
) -> ResponseT:
if data is None:
return cast(ResponseT, None)
if cast_type is object:
return cast(ResponseT, data)
try:
if inspect.isclass(cast_type) and issubclass(cast_type, ModelBuilderProtocol):
return cast(ResponseT, cast_type.build(response=response, data=data))
if self._strict_response_validation:
return cast(ResponseT, validate_type(type_=cast_type, value=data))
return cast(ResponseT, construct_type(type_=cast_type, value=data))
except pydantic.ValidationError as err:
raise APIResponseValidationError(response=response, json_data=data) from err
def _should_stream_response_body(self, request: httpx.Request) -> bool:
return request.headers.get(RAW_RESPONSE_HEADER) == "stream" # type: ignore[no-any-return]
def _should_retry(self, response: httpx.Response) -> bool:
# Note: this is not a standard header
should_retry_header = response.headers.get("x-should-retry")
# If the server explicitly says whether or not to retry, obey.
if should_retry_header == "true":
log.debug("Retrying as header `x-should-retry` is set to `true`")
return True
if should_retry_header == "false":
log.debug("Not retrying as header `x-should-retry` is set to `false`")
return False
# Retry on request timeouts.
if response.status_code == 408:
log.debug("Retrying due to status code %i", response.status_code)
return True
# Retry on lock timeouts.
if response.status_code == 409:
log.debug("Retrying due to status code %i", response.status_code)
return True
# Retry on rate limits.
if response.status_code == 429:
log.debug("Retrying due to status code %i", response.status_code)
return True
# Retry internal errors.
if response.status_code >= 500:
log.debug("Retrying due to status code %i", response.status_code)
return True
log.debug("Not retrying")
return False
def is_closed(self) -> bool:
return self._client.is_closed
def close(self):
self._client.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def request(
self,
cast_type: Type[ResponseT],
options: FinalRequestOptions,
remaining_retries: Optional[int] = None,
*,
stream: bool = False,
stream_cls: Type[StreamResponse] | None = None,
) -> ResponseT | StreamResponse:
return self._request(
cast_type=cast_type,
options=options,
stream=stream,
stream_cls=stream_cls,
remaining_retries=remaining_retries,
)
def _request(
self,
*,
cast_type: Type[ResponseT],
options: FinalRequestOptions,
remaining_retries: int | None,
stream: bool,
stream_cls: Type[StreamResponse] | None,
) -> ResponseT | StreamResponse:
retries = self._remaining_retries(remaining_retries, options)
request = self._build_request(options)
kwargs: HttpxSendArgs = {}
if self.custom_auth is not None:
kwargs["auth"] = self.custom_auth
try:
response = self._client.send(
request,
stream=stream or self._should_stream_response_body(request=request),
**kwargs,
)
except httpx.TimeoutException as err:
log.debug("Encountered httpx.TimeoutException", exc_info=True)
if retries > 0:
return self._retry_request(
options,
cast_type,
retries,
stream=stream,
stream_cls=stream_cls,
response_headers=None,
)
log.debug("Raising timeout error")
raise APITimeoutError(request=request) from err
except Exception as err:
log.debug("Encountered Exception", exc_info=True)
if retries > 0:
return self._retry_request(
options,
cast_type,
retries,
stream=stream,
stream_cls=stream_cls,
response_headers=None,
)
log.debug("Raising connection error")
raise APIConnectionError(request=request) from err
log.debug(
'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase
)
try:
response.raise_for_status()
except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code
log.debug("Encountered httpx.HTTPStatusError", exc_info=True)
if retries > 0 and self._should_retry(err.response):
err.response.close()
return self._retry_request(
options,
cast_type,
retries,
err.response.headers,
stream=stream,
stream_cls=stream_cls,
)
# If the response is streamed then we need to explicitly read the response
# to completion before attempting to access the response text.
if not err.response.is_closed:
err.response.read()
log.debug("Re-raising status error")
raise self._make_status_error(err.response) from None
# return self._parse_response(
# cast_type=cast_type,
# options=options,
# response=response,
# stream=stream,
# stream_cls=stream_cls,
# )
return self._process_response(
cast_type=cast_type,
options=options,
response=response,
stream=stream,
stream_cls=stream_cls,
)
def _retry_request(
self,
options: FinalRequestOptions,
cast_type: Type[ResponseT],
remaining_retries: int,
response_headers: httpx.Headers | None,
*,
stream: bool,
stream_cls: Type[StreamResponse] | None,
) -> ResponseT | StreamResponse:
remaining = remaining_retries - 1
if remaining == 1:
log.debug("1 retry left")
else:
log.debug("%i retries left", remaining)
timeout = self._calculate_retry_timeout(remaining, options, response_headers)
log.info("Retrying request to %s in %f seconds", options.url, timeout)
# In a synchronous context we are blocking the entire thread. Up to the library user to run the client in a
# different thread if necessary.
time.sleep(timeout)
return self._request(
options=options,
cast_type=cast_type,
remaining_retries=remaining,
stream=stream,
stream_cls=stream_cls,
)
def _process_response(
self,
*,
cast_type: Type[ResponseT],
options: FinalRequestOptions,
response: httpx.Response,
stream: bool,
stream_cls: Type[StreamResponse] | None,
) -> ResponseT:
# _legacy_response with raw_response_header to paser method
if response.request.headers.get(RAW_RESPONSE_HEADER) == "true":
return cast(
ResponseT,
LegacyAPIResponse(
raw=response,
client=self,
cast_type=cast_type,
stream=stream,
stream_cls=stream_cls,
options=options,
),
)
origin = get_origin(cast_type) or cast_type
if inspect.isclass(origin) and issubclass(origin, BaseAPIResponse):
if not issubclass(origin, APIResponse):
raise TypeError(f"API Response types must subclass {APIResponse}; Received {origin}")
response_cls = cast("type[BaseAPIResponse[Any]]", cast_type)
return cast(
ResponseT,
response_cls(
raw=response,
client=self,
cast_type=extract_response_type(response_cls),
stream=stream,
stream_cls=stream_cls,
options=options,
),
)
if cast_type == httpx.Response:
return cast(ResponseT, response)
api_response = APIResponse(
raw=response,
client=self,
cast_type=cast("type[ResponseT]", cast_type), # pyright: ignore[reportUnnecessaryCast]
stream=stream,
stream_cls=stream_cls,
options=options,
)
if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
return cast(ResponseT, api_response)
return api_response.parse()
def _request_api_list(
self,
model: Type[object],
page: Type[SyncPageT],
options: FinalRequestOptions,
) -> SyncPageT:
def _parser(resp: SyncPageT) -> SyncPageT:
resp._set_private_attributes(
client=self,
model=model,
options=options,
)
return resp
options.post_parser = _parser
return self.request(page, options, stream=False)
@overload
def get(
self,
path: str,
*,
cast_type: Type[ResponseT],
options: UserRequestInput = {},
stream: Literal[False] = False,
) -> ResponseT:
...
@overload
def get(
self,
path: str,
*,
cast_type: Type[ResponseT],
options: UserRequestInput = {},
stream: Literal[True],
stream_cls: Type[StreamResponse],
) -> StreamResponse:
...
@overload
def get(
self,
path: str,
*,
cast_type: Type[ResponseT],
options: UserRequestInput = {},
stream: bool,
stream_cls: Type[StreamResponse] | None = None,
) -> ResponseT | StreamResponse:
...
def get(
self,
path: str,
*,
cast_type: Type[ResponseT],
options: UserRequestInput = {},
stream: bool = False,
stream_cls: Type[StreamResponse] | None = None,
) -> ResponseT:
opts = FinalRequestOptions.construct(method="get", url=path, **options)
return cast(ResponseT, self.request(cast_type, opts, stream=stream, stream_cls=stream_cls))
@overload
def post(
self,
path: str,
*,
cast_type: Type[ResponseT],
body: Body | None = None,
options: UserRequestInput = {},
files: RequestFiles | None = None,
stream: Literal[False] = False,
) -> ResponseT:
...
@overload
def post(
self,
path: str,
*,
cast_type: Type[ResponseT],
body: Body | None = None,
options: UserRequestInput = {},
files: RequestFiles | None = None,
stream: Literal[True],
stream_cls: Type[StreamResponse],
) -> StreamResponse:
...
@overload
def post(
self,
path: str,
*,
cast_type: Type[ResponseT],
body: Body | None = None,
options: UserRequestInput = {},
files: RequestFiles | None = None,
stream: bool,
stream_cls: Type[StreamResponse] | None = None,
) -> ResponseT | StreamResponse:
...
def post(
self,
path: str,
*,
cast_type: Type[ResponseT],
body: Body | None = None,
options: UserRequestInput = {},
files: RequestFiles | None = None,
stream: bool = False,
stream_cls: Type[StreamResponse[Any]] | None = None,
) -> ResponseT | StreamResponse:
opts = FinalRequestOptions.construct(
method="post", url=path, json_data=body, files=to_httpx_files(files), **options
)
return cast(ResponseT, self.request(cast_type, opts, stream=stream, stream_cls=stream_cls))
def patch(
self,
path: str,
*,
cast_type: Type[ResponseT],
body: Body | None = None,
options: UserRequestInput = {},
) -> ResponseT:
opts = FinalRequestOptions.construct(method="patch", url=path, json_data=body, **options)
return self.request(
cast_type=cast_type, options=opts,
)
def put(
self,
path: str,
*,
cast_type: Type[ResponseT],
body: Body | None = None,
options: UserRequestInput = {},
files: RequestFiles | None = None,
) -> ResponseT | StreamResponse:
opts = FinalRequestOptions.construct(method="put", url=path, json_data=body, files=to_httpx_files(files),
**options)
return self.request(
cast_type=cast_type, options=opts,
)
def delete(
self,
path: str,
*,
cast_type: Type[ResponseT],
body: Body | None = None,
options: UserRequestInput = {},
) -> ResponseT | StreamResponse:
opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options)
return self.request(
cast_type=cast_type, options=opts,
)
def get_api_list(
self,
path: str,
*,
model: Type[object],
page: Type[SyncPageT],
body: Body | None = None,
options: UserRequestInput = {},
method: str = "get",
) -> SyncPageT:
opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options)
return self._request_api_list(model, page, opts)
def _make_status_error(self, response) -> APIStatusError:
response_text = response.text.strip()
status_code = response.status_code
error_msg = f"Error code: {status_code}, with error text {response_text}"
if status_code == 400:
return _errors.APIRequestFailedError(message=error_msg, response=response)
elif status_code == 401:
return _errors.APIAuthenticationError(message=error_msg, response=response)
elif status_code == 429:
return _errors.APIReachLimitError(message=error_msg, response=response)
elif status_code == 500:
return _errors.APIInternalError(message=error_msg, response=response)
elif status_code == 503:
return _errors.APIServerFlowExceedError(message=error_msg, response=response)
return APIStatusError(message=error_msg, response=response)
def make_request_options(
*,
query: Query | None = None,
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
post_parser: PostParser | NotGiven = NOT_GIVEN,
) -> UserRequestInput:
"""Create a dict of type RequestOptions without keys of NotGiven values."""
options: UserRequestInput = {}
if extra_headers is not None:
options["headers"] = extra_headers
if extra_body is not None:
options["extra_json"] = cast(AnyMapping, extra_body)
if query is not None:
options["params"] = query
if extra_query is not None:
options["params"] = {**options.get("params", {}), **extra_query}
if not isinstance(timeout, NotGiven):
options["timeout"] = timeout
if is_given(post_parser):
# internal
options["post_parser"] = post_parser # type: ignore
return options
def _merge_mappings(
obj1: Mapping[_T_co, Union[_T, Omit]],
obj2: Mapping[_T_co, Union[_T, Omit]],
) -> Dict[_T_co, _T]:
"""Merge two mappings of the same type, removing any values that are instances of `Omit`.
In cases with duplicate keys the second mapping takes precedence.
"""
merged = {**obj1, **obj2}
return {key: value for key, value in merged.items() if not isinstance(value, Omit)}
================================================
FILE: zhipuai/core/_jwt_token.py
================================================
# -*- coding:utf-8 -*-
import time
import cachetools.func
import jwt
# 缓存时间 3分钟
CACHE_TTL_SECONDS = 3 * 60
# token 有效期比缓存时间 多30秒
API_TOKEN_TTL_SECONDS = CACHE_TTL_SECONDS + 30
@cachetools.func.ttl_cache(maxsize=10, ttl=CACHE_TTL_SECONDS)
def generate_token(apikey: str):
try:
api_key, secret = apikey.split(".")
except Exception as e:
raise Exception("invalid api_key", e)
payload = {
"api_key": api_key,
"exp": int(round(time.time() * 1000)) + API_TOKEN_TTL_SECONDS * 1000,
"timestamp": int(round(time.time() * 1000)),
}
ret = jwt.encode(
payload,
secret,
algorithm="HS256",
headers={"alg": "HS256", "sign_type": "SIGN"},
)
return ret
================================================
FILE: zhipuai/core/_legacy_binary_response.py
================================================
from __future__ import annotations
import httpx
import os
from typing import Iterator, AsyncIterator, Any
class HttpxResponseContent:
@property
def content(self) -> bytes:
raise NotImplementedError("This method is not implemented for this class.")
@property
def text(self) -> str:
raise NotImplementedError("This method is not implemented for this class.")
@property
def encoding(self) -> str | None:
raise NotImplementedError("This method is not implemented for this class.")
@property
def charset_encoding(self) -> str | None:
raise NotImplementedError("This method is not implemented for this class.")
def json(self, **kwargs: Any) -> Any:
raise NotImplementedError("This method is not implemented for this class.")
def read(self) -> bytes:
raise NotImplementedError("This method is not implemented for this class.")
def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
raise NotImplementedError("This method is not implemented for this class.")
def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
raise NotImplementedError("This method is not implemented for this class.")
def iter_lines(self) -> Iterator[str]:
raise NotImplementedError("This method is not implemented for this class.")
def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]:
raise NotImplementedError("This method is not implemented for this class.")
def write_to_file(
self,
file: str | os.PathLike[str],
) -> None:
raise NotImplementedError("This method is not implemented for this class.")
def stream_to_file(
self,
file: str | os.PathLike[str],
*,
chunk_size: int | None = None,
) -> None:
raise NotImplementedError("This method is not implemented for this class.")
def close(self) -> None:
raise NotImplementedError("This method is not implemented for this class.")
async def aread(self) -> bytes:
raise NotImplementedError("This method is not implemented for this class.")
async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
raise NotImplementedError("This method is not implemented for this class.")
async def aiter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
raise NotImplementedError("This method is not implemented for this class.")
async def aiter_lines(self) -> AsyncIterator[str]:
raise NotImplementedError("This method is not implemented for this class.")
async def aiter_raw(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
raise NotImplementedError("This method is not implemented for this class.")
async def astream_to_file(
self,
file: str | os.PathLike[str],
*,
chunk_size: int | None = None,
) -> None:
raise NotImplementedError("This method is not implemented for this class.")
async def aclose(self) -> None:
raise NotImplementedError("This method is not implemented for this class.")
class HttpxBinaryResponseContent(HttpxResponseContent):
response: httpx.Response
def __init__(self, response: httpx.Response) -> None:
self.response = response
@property
def content(self) -> bytes:
return self.response.content
@property
def encoding(self) -> str | None:
return self.response.encoding
@property
def charset_encoding(self) -> str | None:
return self.response.charset_encoding
def read(self) -> bytes:
return self.response.read()
def text(self) -> str:
raise NotImplementedError("Not implemented for binary response content")
def json(self, **kwargs: Any) -> Any:
raise NotImplementedError("Not implemented for binary response content")
def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
raise NotImplementedError("Not implemented for binary response content")
def iter_lines(self) -> Iterator[str]:
raise NotImplementedError("Not implemented for binary response content")
async def aiter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
raise NotImplementedError("Not implemented for binary response content")
async def aiter_lines(self) -> AsyncIterator[str]:
raise NotImplementedError("Not implemented for binary response content")
def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
return self.response.iter_bytes(chunk_size)
def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]:
return self.response.iter_raw(chunk_size)
def write_to_file(
self,
file: str | os.PathLike[str],
) -> None:
"""Write the output to the given file.
Accepts a filename or any path-like object, e.g. pathlib.Path
Note: if you want to stream the data to the file instead of writing
all at once then you should use `.with_streaming_response` when making
the API request, e.g. `client.with_streaming_response.foo().stream_to_file('my_filename.txt')`
"""
with open(file, mode="wb") as f:
for data in self.response.iter_bytes():
f.write(data)
def stream_to_file(
self,
file: str | os.PathLike[str],
*,
chunk_size: int | None = None,
) -> None:
with open(file, mode="wb") as f:
for data in self.response.iter_bytes(chunk_size):
f.write(data)
def close(self) -> None:
return self.response.close()
async def aread(self) -> bytes:
return await self.response.aread()
async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
return self.response.aiter_bytes(chunk_size)
async def aiter_raw(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
return self.response.aiter_raw(chunk_size)
async def astream_to_file(
self,
file: str | os.PathLike[str],
*,
chunk_size: int | None = None,
) -> None:
path = anyio.Path(file)
async with await path.open(mode="wb") as f:
async for data in self.response.aiter_bytes(chunk_size):
await f.write(data)
async def aclose(self) -> None:
return await self.response.aclose()
class HttpxTextBinaryResponseContent(HttpxBinaryResponseContent):
response: httpx.Response
@property
def text(self) -> str:
return self.response.text
def json(self, **kwargs: Any) -> Any:
return self.response.json(**kwargs)
def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
return self.response.iter_text(chunk_size)
def iter_lines(self) -> Iterator[str]:
return self.response.iter_lines()
async def aiter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
return self.response.aiter_text(chunk_size)
async def aiter_lines(self) -> AsyncIterator[str]:
return self.response.aiter_lines()
================================================
FILE: zhipuai/core/_legacy_response.py
================================================
from __future__ import annotations
import os
import inspect
import logging
import datetime
import functools
from collections.abc import Iterator
from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload, AsyncIterator
from typing_extensions import Awaitable, ParamSpec, override, deprecated, get_origin
import anyio
import httpx
import pydantic
from ._base_type import NoneType
from ._utils import is_given, extract_type_arg, is_annotated_type
from ._base_models import BaseModel, is_basemodel
from ._constants import RAW_RESPONSE_HEADER
from ._sse_client import StreamResponse, is_stream_class_type, extract_stream_chunk_type
from ._errors import APIResponseValidationError
from ._legacy_binary_response import HttpxBinaryResponseContent, HttpxTextBinaryResponseContent, HttpxResponseContent
if TYPE_CHECKING:
from ._request_opt import FinalRequestOptions
from ._http_client import HttpClient
P = ParamSpec("P")
R = TypeVar("R")
_T = TypeVar("_T")
log: logging.Logger = logging.getLogger(__name__)
class LegacyAPIResponse(Generic[R]):
"""This is a legacy class as it will be replaced by `APIResponse`
and `AsyncAPIResponse` in the `_response.py` file in the next major
release.
For the sync client this will mostly be the same with the exception
of `content` & `text` will be methods instead of properties. In the
async client, all methods will be async.
A migration script will be provided & the migration in general should
be smooth.
"""
_cast_type: type[R]
_client: "HttpClient"
_parsed_by_type: dict[type[Any], Any]
_stream: bool
_stream_cls: type[StreamResponse[Any]] | None
_options: FinalRequestOptions
http_response: httpx.Response
def __init__(
self,
*,
raw: httpx.Response,
cast_type: type[R],
client: "HttpClient",
stream: bool,
stream_cls: type[StreamResponse[Any]] | None,
options: FinalRequestOptions,
) -> None:
self._cast_type = cast_type
self._client = client
self._parsed_by_type = {}
self._stream = stream
self._stream_cls = stream_cls
self._options = options
self.http_response = raw
@property
def request_id(self) -> str | None:
return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return]
@overload
def parse(self, *, to: type[_T]) -> _T:
...
@overload
def parse(self) -> R:
...
def parse(self, *, to: type[_T] | None = None) -> R | _T:
"""Returns the rich python representation of this response's data.
NOTE: For the async client: this will become a coroutine in the next major version.
For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
You can customise the type that the response is parsed into through
the `to` argument, e.g.
```py
from zhipuai import BaseModel
class MyModel(BaseModel):
foo: str
obj = response.parse(to=MyModel)
print(obj.foo)
```
We support parsing:
- `BaseModel`
- `dict`
- `list`
- `Union`
- `str`
- `int`
- `float`
- `httpx.Response`
"""
cache_key = to if to is not None else self._cast_type
cached = self._parsed_by_type.get(cache_key)
if cached is not None:
return cached # type: ignore[no-any-return]
parsed = self._parse(to=to)
if is_given(self._options.post_parser):
parsed = self._options.post_parser(parsed)
self._parsed_by_type[cache_key] = parsed
return parsed
@property
def headers(self) -> httpx.Headers:
return self.http_response.headers
@property
def http_request(self) -> httpx.Request:
return self.http_response.request
@property
def status_code(self) -> int:
return self.http_response.status_code
@property
def url(self) -> httpx.URL:
return self.http_response.url
@property
def method(self) -> str:
return self.http_request.method
@property
def content(self) -> bytes:
"""Return the binary response content.
NOTE: this will be removed in favour of `.read()` in the
next major version.
"""
return self.http_response.content
@property
def text(self) -> str:
"""Return the decoded response content.
NOTE: this will be turned into a method in the next major version.
"""
return self.http_response.text
@property
def http_version(self) -> str:
return self.http_response.http_version
@property
def is_closed(self) -> bool:
return self.http_response.is_closed
@property
def elapsed(self) -> datetime.timedelta:
"""The time taken for the complete request/response cycle to complete."""
return self.http_response.elapsed
def _parse(self, *, to: type[_T] | None = None) -> R | _T:
# unwrap `Annotated[T, ...]` -> `T`
if to and is_annotated_type(to):
to = extract_type_arg(to, 0)
if self._stream:
if to:
if not is_stream_class_type(to):
raise TypeError(f"Expected custom parse type to be a subclass of {StreamResponse}")
return cast(
_T,
to(
cast_type=extract_stream_chunk_type(
to,
failure_message="Expected custom stream type to be passed with a type argument, e.g. StreamResponse[ChunkType]",
),
response=self.http_response,
client=cast(Any, self._client),
),
)
if self._stream_cls:
return cast(
R,
self._stream_cls(
cast_type=extract_stream_chunk_type(self._stream_cls),
response=self.http_response,
client=cast(Any, self._client),
),
)
stream_cls = cast("type[StreamResponse[Any]] | None", self._client._default_stream_cls)
if stream_cls is None:
raise MissingStreamClassError()
return cast(
R,
stream_cls(
cast_type=self._cast_type,
response=self.http_response,
client=cast(Any, self._client),
),
)
cast_type = to if to is not None else self._cast_type
# unwrap `Annotated[T, ...]` -> `T`
if is_annotated_type(cast_type):
cast_type = extract_type_arg(cast_type, 0)
if cast_type is NoneType:
return cast(R, None)
response = self.http_response
if cast_type == str:
return cast(R, response.text)
if cast_type == int:
return cast(R, int(response.text))
if cast_type == float:
return cast(R, float(response.text))
origin = get_origin(cast_type) or cast_type
if inspect.isclass(origin) and issubclass(origin, HttpxResponseContent):
# in the response, e.g. mime file
*_, filename = response.headers.get("content-disposition", "").split("filename=")
# 判断文件类型是jsonl类型的使用HttpxTextBinaryResponseContent
if filename and filename.endswith(".jsonl"):
return cast(R, HttpxTextBinaryResponseContent(response))
elif filename and filename.endswith(".xlsx"):
return cast(R, HttpxTextBinaryResponseContent(response))
else:
return cast(R, cast_type(response)) # type: ignore
if origin == LegacyAPIResponse:
raise RuntimeError("Unexpected state - cast_type is `APIResponse`")
if inspect.isclass(origin) and issubclass(origin, httpx.Response):
# Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
# and pass that class to our request functions. We cannot change the variance to be either
# covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
# the response class ourselves but that is something that should be supported directly in httpx
# as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
if cast_type != httpx.Response:
raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_type`")
return cast(R, response)
if inspect.isclass(origin) and not issubclass(origin, BaseModel) and issubclass(origin, pydantic.BaseModel):
raise TypeError("Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`")
if (
cast_type is not object
and not origin is list
and not origin is dict
and not origin is Union
and not issubclass(origin, BaseModel)
):
raise RuntimeError(
f"Unsupported type, expected {cast_type} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
)
# split is required to handle cases where additional information is included
# in the response, e.g. application/json; charset=utf-8
content_type, *_ = response.headers.get("content-type", "*").split(";")
if content_type != "application/json":
if is_basemodel(cast_type):
try:
data = response.json()
except Exception as exc:
log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc)
else:
return self._client._process_response_data(
data=data,
cast_type=cast_type, # type: ignore
response=response,
)
if self._client._strict_response_validation:
raise APIResponseValidationError(
response=response,
message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.",
json_data=response.text,
)
# If the API responds with content that isn't JSON then we just return
# the (decoded) text without performing any parsing so that you can still
# handle the response however you need to.
return response.text # type: ignore
data = response.json()
return self._client._process_response_data(
data=data,
cast_type=cast_type, # type: ignore
response=response,
)
@override
def __repr__(self) -> str:
return f""
class MissingStreamClassError(TypeError):
def __init__(self) -> None:
super().__init__(
"The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `openai._streaming` for reference",
)
def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, LegacyAPIResponse[R]]:
"""Higher order function that takes one of our bound API methods and wraps it
to support returning the raw `APIResponse` object directly.
"""
@functools.wraps(func)
def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]:
extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
extra_headers[RAW_RESPONSE_HEADER] = "true"
kwargs["extra_headers"] = extra_headers
return cast(LegacyAPIResponse[R], func(*args, **kwargs))
return wrapped
================================================
FILE: zhipuai/core/_request_opt.py
================================================
from __future__ import annotations
from typing import Union, Any, cast, TYPE_CHECKING
from ._constants import RAW_RESPONSE_HEADER
from ._utils import is_given
from ._base_compat import ConfigDict, PYDANTIC_V2
import pydantic.generics
from httpx import Timeout
from typing_extensions import (
final, Unpack, ClassVar, TypedDict, Required, Callable
)
from ._base_type import Body, NotGiven, Headers, HttpxRequestFiles, Query, AnyMapping
from ._utils import remove_notgiven_indict, strip_not_given
class UserRequestInput(TypedDict, total=False):
headers: Headers
max_retries: int
timeout: float | Timeout | None
params: Query
extra_json: AnyMapping
class FinalRequestOptionsInput(TypedDict, total=False):
method: Required[str]
url: Required[str]
params: Query
headers: Headers
max_retries: int
timeout: float | Timeout | None
files: HttpxRequestFiles | None
json_data: Body
extra_json: AnyMapping
@final
class FinalRequestOptions(pydantic.BaseModel):
method: str
url: str
params: Query = {}
headers: Union[Headers, NotGiven] = NotGiven()
max_retries: Union[int, NotGiven] = NotGiven()
timeout: Union[float, Timeout, None, NotGiven] = NotGiven()
files: Union[HttpxRequestFiles, None] = None
idempotency_key: Union[str, None] = None
post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven()
# It should be noted that we cannot use `json` here as that would override
# a BaseModel method in an incompatible fashion.
json_data: Union[Body, None] = None
extra_json: Union[AnyMapping, None] = None
if PYDANTIC_V2:
model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
else:
class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
arbitrary_types_allowed: bool = True
def get_max_retries(self, max_retries: int) -> int:
if isinstance(self.max_retries, NotGiven):
return max_retries
return self.max_retries
def _strip_raw_response_header(self) -> None:
if not is_given(self.headers):
return
if self.headers.get(RAW_RESPONSE_HEADER):
self.headers = {**self.headers}
self.headers.pop(RAW_RESPONSE_HEADER)
# override the `construct` method so that we can run custom transformations.
# this is necessary as we don't want to do any actual runtime type checking
# (which means we can't use validators) but we do want to ensure that `NotGiven`
# values are not present
#
# type ignore required because we're adding explicit types to `**values`
@classmethod
def construct( # type: ignore
cls,
_fields_set: set[str] | None = None,
**values: Unpack[UserRequestInput],
) -> FinalRequestOptions:
kwargs: dict[str, Any] = {
# we unconditionally call `strip_not_given` on any value
# as it will just ignore any non-mapping types
key: strip_not_given(value)
for key, value in values.items()
}
if PYDANTIC_V2:
return super().model_construct(_fields_set, **kwargs)
return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated]
if not TYPE_CHECKING:
# type checkers incorrectly complain about this assignment
model_construct = construct
================================================
FILE: zhipuai/core/_response.py
================================================
from __future__ import annotations
import datetime
import inspect
from typing import TypeVar, Generic, cast, Any, TYPE_CHECKING, Iterator, Union, overload
import httpx
import logging
import pydantic
from typing_extensions import ParamSpec, get_origin, get_args, override
from ._base_type import NoneType
from ._sse_client import StreamResponse, is_stream_class_type, extract_stream_chunk_type
from ._base_models import is_basemodel, BaseModel
from ._utils import is_annotated_type, extract_type_arg, extract_type_var_from_base, is_given
from ._errors import ZhipuAIError, APIResponseValidationError
if TYPE_CHECKING:
from ._request_opt import FinalRequestOptions
from ._http_client import HttpClient
P = ParamSpec("P")
R = TypeVar("R")
_T = TypeVar("_T")
_APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]")
log: logging.Logger = logging.getLogger(__name__)
class BaseAPIResponse(Generic[R]):
_cast_type: type[R]
_client: "HttpClient"
_parsed_by_type: dict[type[Any], Any]
_is_sse_stream: bool
_stream_cls: type[StreamResponse[Any]]
_options: FinalRequestOptions
http_response: httpx.Response
def __init__(
self,
*,
raw: httpx.Response,
cast_type: type[R],
client: "HttpClient",
stream: bool,
stream_cls: type[StreamResponse[Any]] | None = None,
options: FinalRequestOptions,
) -> None:
self._cast_type = cast_type
self._client = client
self._parsed_by_type = {}
self._is_sse_stream = stream
self._stream_cls = stream_cls
self._options = options
self.http_response = raw
def _parse(self, *, to: type[_T] | None = None) -> R | _T:
# unwrap `Annotated[T, ...]` -> `T`
if to and is_annotated_type(to):
to = extract_type_arg(to, 0)
if self._is_sse_stream:
if to:
if not is_stream_class_type(to):
raise TypeError(f"Expected custom parse type to be a subclass of {StreamResponse}")
return cast(
_T,
to(
cast_type=extract_stream_chunk_type(
to,
failure_message="Expected custom stream type to be passed with a type argument, e.g. StreamResponse[ChunkType]",
),
response=self.http_response,
client=cast(Any, self._client),
),
)
if self._stream_cls:
return cast(
R,
self._stream_cls(
cast_type=extract_stream_chunk_type(self._stream_cls),
response=self.http_response,
client=cast(Any, self._client),
),
)
stream_cls = cast("type[Stream[Any]] | None", self._client._default_stream_cls)
if stream_cls is None:
raise MissingStreamClassError()
return cast(
R,
stream_cls(
cast_type=self._cast_type,
response=self.http_response,
client=cast(Any, self._client),
),
)
cast_type = to if to is not None else self._cast_type
# unwrap `Annotated[T, ...]` -> `T`
if is_annotated_type(cast_type):
cast_type = extract_type_arg(cast_type, 0)
if cast_type is NoneType:
return cast(R, None)
response = self.http_response
if cast_type == str:
return cast(R, response.text)
if cast_type == bytes:
return cast(R, response.content)
if cast_type == int:
return cast(R, int(response.text))
if cast_type == float:
return cast(R, float(response.text))
origin = get_origin(cast_type) or cast_type
# handle the legacy binary response case
if inspect.isclass(cast_type) and cast_type.__name__ == "HttpxBinaryResponseContent":
return cast(R, cast_type(response)) # type: ignore
if origin == APIResponse:
raise RuntimeError("Unexpected state - cast_type is `APIResponse`")
if inspect.isclass(origin) and issubclass(origin, httpx.Response):
# Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
# and pass that class to our request functions. We cannot change the variance to be either
# covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
# the response class ourselves but that is something that should be supported directly in httpx
# as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
if cast_type != httpx.Response:
raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_type`")
return cast(R, response)
if inspect.isclass(origin) and not issubclass(origin, BaseModel) and issubclass(origin, pydantic.BaseModel):
raise TypeError("Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`")
if (
cast_type is not object
and not origin is list
and not origin is dict
and not origin is Union
and not issubclass(origin, BaseModel)
):
raise RuntimeError(
f"Unsupported type, expected {cast_type} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
)
# split is required to handle cases where additional information is included
# in the response, e.g. application/json; charset=utf-8
content_type, *_ = response.headers.get("content-type", "*").split(";")
if content_type != "application/json":
if is_basemodel(cast_type):
try:
data = response.json()
except Exception as exc:
log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc)
else:
return self._client._process_response_data(
data=data,
cast_type=cast_type, # type: ignore
response=response,
)
if self._client._strict_response_validation:
raise APIResponseValidationError(
response=response,
message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.",
json_data=response.text,
)
# If the API responds with content that isn't JSON then we just return
# the (decoded) text without performing any parsing so that you can still
# handle the response however you need to.
return response.text # type: ignore
data = response.json()
return self._client._process_response_data(
data=data,
cast_type=cast_type, # type: ignore
response=response,
)
@property
def headers(self) -> httpx.Headers:
return self.http_response.headers
@property
def http_request(self) -> httpx.Request:
"""Returns the httpx Request instance associated with the current response."""
return self.http_response.request
@property
def status_code(self) -> int:
return self.http_response.status_code
@property
def url(self) -> httpx.URL:
"""Returns the URL for which the request was made."""
return self.http_response.url
@property
def method(self) -> str:
return self.http_request.method
@property
def http_version(self) -> str:
return self.http_response.http_version
@property
def elapsed(self) -> datetime.timedelta:
"""The time taken for the complete request/response cycle to complete."""
return self.http_response.elapsed
@property
def is_closed(self) -> bool:
"""Whether or not the response body has been closed.
If this is False then there is response data that has not been read yet.
You must either fully consume the response body or call `.close()`
before discarding the response to prevent resource leaks.
"""
return self.http_response.is_closed
@override
def __repr__(self) -> str:
return (
f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_type}>"
)
class APIResponse(BaseAPIResponse[R]):
@property
def request_id(self) -> str | None:
return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return]
@overload
def parse(self, *, to: type[_T]) -> _T:
...
@overload
def parse(self) -> R:
...
def parse(self, *, to: type[_T] | None = None) -> R | _T:
"""Returns the rich python representation of this response's data.
For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
You can customise the type that the response is parsed into through
the `to` argument, e.g.
```py
from openai import BaseModel
class MyModel(BaseModel):
foo: str
obj = response.parse(to=MyModel)
print(obj.foo)
```
We support parsing:
- `BaseModel`
- `dict`
- `list`
- `Union`
- `str`
- `int`
- `float`
- `httpx.Response`
"""
cache_key = to if to is not None else self._cast_type
cached = self._parsed_by_type.get(cache_key)
if cached is not None:
return cached # type: ignore[no-any-return]
if not self._is_sse_stream:
self.read()
parsed = self._parse(to=to)
if is_given(self._options.post_parser):
parsed = self._options.post_parser(parsed)
self._parsed_by_type[cache_key] = parsed
return parsed
def read(self) -> bytes:
"""Read and return the binary response content."""
try:
return self.http_response.read()
except httpx.StreamConsumed as exc:
# The default error raised by httpx isn't very
# helpful in our case so we re-raise it with
# a different error message.
raise StreamAlreadyConsumed() from exc
def text(self) -> str:
"""Read and decode the response content into a string."""
self.read()
return self.http_response.text
def json(self) -> object:
"""Read and decode the JSON response content."""
self.read()
return self.http_response.json()
def close(self) -> None:
"""Close the response and release the connection.
Automatically called if the response body is read to completion.
"""
self.http_response.close()
def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
"""
A byte-iterator over the decoded response content.
This automatically handles gzip, deflate and brotli encoded responses.
"""
for chunk in self.http_response.iter_bytes(chunk_size):
yield chunk
def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
"""A str-iterator over the decoded response content
that handles both gzip, deflate, etc but also detects the content's
string encoding.
"""
for chunk in self.http_response.iter_text(chunk_size):
yield chunk
def iter_lines(self) -> Iterator[str]:
"""Like `iter_text()` but will only yield chunks for each line"""
for chunk in self.http_response.iter_lines():
yield chunk
class MissingStreamClassError(TypeError):
def __init__(self) -> None:
super().__init__(
"The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `openai._streaming` for reference",
)
class StreamAlreadyConsumed(ZhipuAIError):
"""
Attempted to read or stream content, but the content has already
been streamed.
This can happen if you use a method like `.iter_lines()` and then attempt
to read th entire response body afterwards, e.g.
```py
response = await client.post(...)
async for line in response.iter_lines():
... # do something with `line`
content = await response.read()
# ^ error
```
If you want this behaviour you'll need to either manually accumulate the response
content or call `await response.read()` before iterating over the stream.
"""
def __init__(self) -> None:
message = (
"Attempted to read or stream some content, but the content has "
"already been streamed. "
"This could be due to attempting to stream the response "
"content more than once."
"\n\n"
"You can fix this by manually accumulating the response content while streaming "
"or by calling `.read()` before starting to stream."
)
super().__init__(message)
def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type:
"""Given a type like `APIResponse[T]`, returns the generic type variable `T`.
This also handles the case where a concrete subclass is given, e.g.
```py
class MyResponse(APIResponse[bytes]):
...
extract_response_type(MyResponse) -> bytes
```
"""
return extract_type_var_from_base(
typ,
generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse)),
index=0,
)
================================================
FILE: zhipuai/core/_sse_client.py
================================================
# -*- coding:utf-8 -*-
from __future__ import annotations
import inspect
import json
from typing import TYPE_CHECKING, Generic, Iterator, Mapping, Type, cast
import httpx
from typing_extensions import TypeGuard
from . import get_origin
from ._base_type import ResponseT
from ._errors import APIResponseError
from ._utils import extract_type_var_from_base, is_mapping
_FIELD_SEPARATOR = ':'
if TYPE_CHECKING:
from ._http_client import HttpClient
class StreamResponse(Generic[ResponseT]):
response: httpx.Response
_cast_type: Type[ResponseT]
def __init__(
self,
*,
cast_type: Type[ResponseT],
response: httpx.Response,
client: HttpClient,
) -> None:
self.response = response
self._cast_type = cast_type
self._data_process_func = client._process_response_data
self._stream_chunks = self.__stream__()
def __next__(self) -> ResponseT:
return self._stream_chunks.__next__()
def __iter__(self) -> Iterator[ResponseT]:
for item in self._stream_chunks:
yield item
def __stream__(self) -> Iterator[ResponseT]:
sse_line_parser = SSELineParser()
iterator = sse_line_parser.iter_lines(self.response.iter_lines())
for sse in iterator:
if sse.data.startswith('[DONE]'):
break
if sse.event is None:
data = sse.json_data()
if isinstance(data, Mapping) and data.get('agent_id'):
yield self._data_process_func(
data=data,
cast_type=self._cast_type,
response=self.response,
)
continue
if isinstance(data, Mapping) and data.get('error'):
raise APIResponseError(
message='An error occurred during streaming',
request=self.response.request,
json_data=data['error'],
)
if sse.event is None:
data = sse.json_data()
if is_mapping(data) and data.get('error'):
message = None
error = data.get('error')
if is_mapping(error):
message = error.get('message')
if not message or not isinstance(message, str):
message = 'An error occurred during streaming'
raise APIResponseError(
message=message,
request=self.response.request,
json_data=data['error'],
)
yield self._data_process_func(
data=data, cast_type=self._cast_type, response=self.response
)
else:
data = sse.json_data()
if (
sse.event == 'error'
and is_mapping(data)
and data.get('error')
):
message = None
error = data.get('error')
if is_mapping(error):
message = error.get('message')
if not message or not isinstance(message, str):
message = 'An error occurred during streaming'
raise APIResponseError(
message=message,
request=self.response.request,
json_data=data['error'],
)
yield self._data_process_func(
data=data, cast_type=self._cast_type, response=self.response
)
for sse in iterator:
pass
class Event(object):
def __init__(
self,
event: str | None = None,
data: str | None = None,
id: str | None = None,
retry: int | None = None,
):
self._event = event
self._data = data
self._id = id
self._retry = retry
def __repr__(self):
data_len = len(self._data) if self._data else 0
return f'Event(event={self._event}, data={self._data} ,data_length={data_len}, id={self._id}, retry={self._retry}'
@property
def event(self):
return self._event
@property
def data(self):
return self._data
def json_data(self):
return json.loads(self._data)
@property
def id(self):
return self._id
@property
def retry(self):
return self._retry
class SSELineParser:
_data: list[str]
_event: str | None
_retry: int | None
_id: str | None
def __init__(self):
self._event = None
self._data = []
self._id = None
self._retry = None
def iter_lines(self, lines: Iterator[str]) -> Iterator[Event]:
for line in lines:
line = line.rstrip('\n')
if not line:
if (
self._event is None
and not self._data
and self._id is None
and self._retry is None
):
continue
sse_event = Event(
event=self._event,
data='\n'.join(self._data),
id=self._id,
retry=self._retry,
)
self._event = None
self._data = []
self._id = None
self._retry = None
yield sse_event
self.decode_line(line)
def decode_line(self, line: str):
if line.startswith(':') or not line:
return
field, _p, value = line.partition(':')
if value.startswith(' '):
value = value[1:]
if field == 'data':
self._data.append(value)
elif field == 'event':
self._event = value
elif field == 'retry':
try:
self._retry = int(value)
except (TypeError, ValueError):
pass
return
def is_stream_class_type(typ: type) -> TypeGuard[type[StreamResponse[object]]]:
"""TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`"""
origin = get_origin(typ) or typ
return inspect.isclass(origin) and issubclass(origin, StreamResponse)
def extract_stream_chunk_type(
stream_cls: type,
*,
failure_message: str | None = None,
) -> type:
"""Given a type like `StreamResponse[T]`, returns the generic type variable `T`.
This also handles the case where a concrete subclass is given, e.g.
```py
class MyStream(StreamResponse[bytes]):
...
extract_stream_chunk_type(MyStream) -> bytes
```
"""
return extract_type_var_from_base(
stream_cls,
index=0,
generic_bases=cast('tuple[type, ...]', (StreamResponse,)),
failure_message=failure_message,
)
================================================
FILE: zhipuai/core/_utils/__init__.py
================================================
from ._utils import (
remove_notgiven_indict as remove_notgiven_indict,
flatten as flatten,
is_dict as is_dict,
is_list as is_list,
is_given as is_given,
is_tuple as is_tuple,
is_mapping as is_mapping,
is_tuple_t as is_tuple_t,
parse_date as parse_date,
is_iterable as is_iterable,
is_sequence as is_sequence,
coerce_float as coerce_float,
is_mapping_t as is_mapping_t,
removeprefix as removeprefix,
removesuffix as removesuffix,
extract_files as extract_files,
is_sequence_t as is_sequence_t,
required_args as required_args,
coerce_boolean as coerce_boolean,
coerce_integer as coerce_integer,
file_from_path as file_from_path,
parse_datetime as parse_datetime,
strip_not_given as strip_not_given,
deepcopy_minimal as deepcopy_minimal,
get_async_library as get_async_library,
maybe_coerce_float as maybe_coerce_float,
get_required_header as get_required_header,
maybe_coerce_boolean as maybe_coerce_boolean,
maybe_coerce_integer as maybe_coerce_integer,
drop_prefix_image_data as drop_prefix_image_data,
)
from ._typing import (
is_list_type as is_list_type,
is_union_type as is_union_type,
extract_type_arg as extract_type_arg,
is_iterable_type as is_iterable_type,
is_required_type as is_required_type,
is_annotated_type as is_annotated_type,
strip_annotated_type as strip_annotated_type,
extract_type_var_from_base as extract_type_var_from_base,
)
from ._transform import (
PropertyInfo as PropertyInfo,
transform as transform,
async_transform as async_transform,
maybe_transform as maybe_transform,
async_maybe_transform as async_maybe_transform,
)
================================================
FILE: zhipuai/core/_utils/_transform.py
================================================
from __future__ import annotations
import io
import base64
import pathlib
from typing import Any, Mapping, TypeVar, cast
from datetime import date, datetime
from typing_extensions import Literal, get_args, override, get_type_hints
import anyio
import pydantic
from ._utils import (
is_list,
is_mapping,
is_iterable,
)
from .._files import is_base64_file_input
from ._typing import (
is_list_type,
is_union_type,
extract_type_arg,
is_iterable_type,
is_required_type,
is_annotated_type,
strip_annotated_type,
)
from .._base_compat import model_dump, is_typeddict
_T = TypeVar("_T")
# TODO: support for drilling globals() and locals()
# TODO: ensure works correctly with forward references in all cases
PropertyFormat = Literal["iso8601", "base64", "custom"]
class PropertyInfo:
"""Metadata class to be used in Annotated types to provide information about a given type.
For example:
class MyParams(TypedDict):
account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')]
This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API.
"""
alias: str | None
format: PropertyFormat | None
format_template: str | None
discriminator: str | None
def __init__(
self,
*,
alias: str | None = None,
format: PropertyFormat | None = None,
format_template: str | None = None,
discriminator: str | None = None,
) -> None:
self.alias = alias
self.format = format
self.format_template = format_template
self.discriminator = discriminator
@override
def __repr__(self) -> str:
return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')"
def maybe_transform(
data: object,
expected_type: object,
) -> Any | None:
"""Wrapper over `transform()` that allows `None` to be passed.
See `transform()` for more details.
"""
if data is None:
return None
return transform(data, expected_type)
# Wrapper over _transform_recursive providing fake types
def transform(
data: _T,
expected_type: object,
) -> _T:
"""Transform dictionaries based off of type information from the given type, for example:
```py
class Params(TypedDict, total=False):
card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
transformed = transform({"card_id": ""}, Params)
# {'cardID': ''}
```
Any keys / data that does not have type information given will be included as is.
It should be noted that the transformations that this function does are not represented in the type system.
"""
transformed = _transform_recursive(data, annotation=cast(type, expected_type))
return cast(_T, transformed)
def _get_annotated_type(type_: type) -> type | None:
"""If the given type is an `Annotated` type then it is returned, if not `None` is returned.
This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]`
"""
if is_required_type(type_):
# Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]`
type_ = get_args(type_)[0]
if is_annotated_type(type_):
return type_
return None
def _maybe_transform_key(key: str, type_: type) -> str:
"""Transform the given `data` based on the annotations provided in `type_`.
Note: this function only looks at `Annotated` types that contain `PropertInfo` metadata.
"""
annotated_type = _get_annotated_type(type_)
if annotated_type is None:
# no `Annotated` definition for this type, no transformation needed
return key
# ignore the first argument as it is the actual type
annotations = get_args(annotated_type)[1:]
for annotation in annotations:
if isinstance(annotation, PropertyInfo) and annotation.alias is not None:
return annotation.alias
return key
def _transform_recursive(
data: object,
*,
annotation: type,
inner_type: type | None = None,
) -> object:
"""Transform the given data against the expected type.
Args:
annotation: The direct type annotation given to the particular piece of data.
This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
the list can be transformed using the metadata from the container type.
Defaults to the same value as the `annotation` argument.
"""
if inner_type is None:
inner_type = annotation
stripped_type = strip_annotated_type(inner_type)
if is_typeddict(stripped_type) and is_mapping(data):
return _transform_typeddict(data, stripped_type)
if (
# List[T]
(is_list_type(stripped_type) and is_list(data))
# Iterable[T]
or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
):
inner_type = extract_type_arg(stripped_type, 0)
return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
if is_union_type(stripped_type):
# For union types we run the transformation against all subtypes to ensure that everything is transformed.
#
# TODO: there may be edge cases where the same normalized field name will transform to two different names
# in different subtypes.
for subtype in get_args(stripped_type):
data = _transform_recursive(data, annotation=annotation, inner_type=subtype)
return data
if isinstance(data, pydantic.BaseModel):
return model_dump(data, exclude_unset=True)
annotated_type = _get_annotated_type(annotation)
if annotated_type is None:
return data
# ignore the first argument as it is the actual type
annotations = get_args(annotated_type)[1:]
for annotation in annotations:
if isinstance(annotation, PropertyInfo) and annotation.format is not None:
return _format_data(data, annotation.format, annotation.format_template)
return data
def _format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
if isinstance(data, (date, datetime)):
if format_ == "iso8601":
return data.isoformat()
if format_ == "custom" and format_template is not None:
return data.strftime(format_template)
if format_ == "base64" and is_base64_file_input(data):
binary: str | bytes | None = None
if isinstance(data, pathlib.Path):
binary = data.read_bytes()
elif isinstance(data, io.IOBase):
binary = data.read()
if isinstance(binary, str): # type: ignore[unreachable]
binary = binary.encode()
if not isinstance(binary, bytes):
raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
return base64.b64encode(binary).decode("ascii")
return data
def _transform_typeddict(
data: Mapping[str, object],
expected_type: type,
) -> Mapping[str, object]:
result: dict[str, object] = {}
annotations = get_type_hints(expected_type, include_extras=True)
for key, value in data.items():
type_ = annotations.get(key)
if type_ is None:
# we do not have a type annotation for this field, leave it as is
result[key] = value
else:
result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_)
return result
async def async_maybe_transform(
data: object,
expected_type: object,
) -> Any | None:
"""Wrapper over `async_transform()` that allows `None` to be passed.
See `async_transform()` for more details.
"""
if data is None:
return None
return await async_transform(data, expected_type)
async def async_transform(
data: _T,
expected_type: object,
) -> _T:
"""Transform dictionaries based off of type information from the given type, for example:
```py
class Params(TypedDict, total=False):
card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
transformed = transform({"card_id": ""}, Params)
# {'cardID': ''}
```
Any keys / data that does not have type information given will be included as is.
It should be noted that the transformations that this function does are not represented in the type system.
"""
transformed = await _async_transform_recursive(data, annotation=cast(type, expected_type))
return cast(_T, transformed)
async def _async_transform_recursive(
data: object,
*,
annotation: type,
inner_type: type | None = None,
) -> object:
"""Transform the given data against the expected type.
Args:
annotation: The direct type annotation given to the particular piece of data.
This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
the list can be transformed using the metadata from the container type.
Defaults to the same value as the `annotation` argument.
"""
if inner_type is None:
inner_type = annotation
stripped_type = strip_annotated_type(inner_type)
if is_typeddict(stripped_type) and is_mapping(data):
return await _async_transform_typeddict(data, stripped_type)
if (
# List[T]
(is_list_type(stripped_type) and is_list(data))
# Iterable[T]
or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
):
inner_type = extract_type_arg(stripped_type, 0)
return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
if is_union_type(stripped_type):
# For union types we run the transformation against all subtypes to ensure that everything is transformed.
#
# TODO: there may be edge cases where the same normalized field name will transform to two different names
# in different subtypes.
for subtype in get_args(stripped_type):
data = await _async_transform_recursive(data, annotation=annotation, inner_type=subtype)
return data
if isinstance(data, pydantic.BaseModel):
return model_dump(data, exclude_unset=True)
annotated_type = _get_annotated_type(annotation)
if annotated_type is None:
return data
# ignore the first argument as it is the actual type
annotations = get_args(annotated_type)[1:]
for annotation in annotations:
if isinstance(annotation, PropertyInfo) and annotation.format is not None:
return await _async_format_data(data, annotation.format, annotation.format_template)
return data
async def _async_format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
if isinstance(data, (date, datetime)):
if format_ == "iso8601":
return data.isoformat()
if format_ == "custom" and format_template is not None:
return data.strftime(format_template)
if format_ == "base64" and is_base64_file_input(data):
binary: str | bytes | None = None
if isinstance(data, pathlib.Path):
binary = await anyio.Path(data).read_bytes()
elif isinstance(data, io.IOBase):
binary = data.read()
if isinstance(binary, str): # type: ignore[unreachable]
binary = binary.encode()
if not isinstance(binary, bytes):
raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
return base64.b64encode(binary).decode("ascii")
return data
async def _async_transform_typeddict(
data: Mapping[str, object],
expected_type: type,
) -> Mapping[str, object]:
result: dict[str, object] = {}
annotations = get_type_hints(expected_type, include_extras=True)
for key, value in data.items():
type_ = annotations.get(key)
if type_ is None:
# we do not have a type annotation for this field, leave it as is
result[key] = value
else:
result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_)
return result
================================================
FILE: zhipuai/core/_utils/_typing.py
================================================
from __future__ import annotations
from typing import Any, TypeVar, Iterable, cast
from collections import abc as _c_abc
from typing_extensions import Required, Annotated, get_args, get_origin
from .._base_type import InheritsGeneric
from zhipuai.core._base_compat import is_union as _is_union
def is_annotated_type(typ: type) -> bool:
return get_origin(typ) == Annotated
def is_list_type(typ: type) -> bool:
return (get_origin(typ) or typ) == list
def is_iterable_type(typ: type) -> bool:
"""If the given type is `typing.Iterable[T]`"""
origin = get_origin(typ) or typ
return origin == Iterable or origin == _c_abc.Iterable
def is_union_type(typ: type) -> bool:
return _is_union(get_origin(typ))
def is_required_type(typ: type) -> bool:
return get_origin(typ) == Required
def is_typevar(typ: type) -> bool:
# type ignore is required because type checkers
# think this expression will always return False
return type(typ) == TypeVar # type: ignore
# Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]]
def strip_annotated_type(typ: type) -> type:
if is_required_type(typ) or is_annotated_type(typ):
return strip_annotated_type(cast(type, get_args(typ)[0]))
return typ
def extract_type_arg(typ: type, index: int) -> type:
args = get_args(typ)
try:
return cast(type, args[index])
except IndexError as err:
raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err
def extract_type_var_from_base(
typ: type,
*,
generic_bases: tuple[type, ...],
index: int,
failure_message: str | None = None,
) -> type:
"""Given a type like `Foo[T]`, returns the generic type variable `T`.
This also handles the case where a concrete subclass is given, e.g.
```py
class MyResponse(Foo[bytes]):
...
extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes
```
And where a generic subclass is given:
```py
_T = TypeVar('_T')
class MyResponse(Foo[_T]):
...
extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes
```
"""
cls = cast(object, get_origin(typ) or typ)
if cls in generic_bases:
# we're given the class directly
return extract_type_arg(typ, index)
# if a subclass is given
# ---
# this is needed as __orig_bases__ is not present in the typeshed stubs
# because it is intended to be for internal use only, however there does
# not seem to be a way to resolve generic TypeVars for inherited subclasses
# without using it.
if isinstance(cls, InheritsGeneric):
target_base_class: Any | None = None
for base in cls.__orig_bases__:
if base.__origin__ in generic_bases:
target_base_class = base
break
if target_base_class is None:
raise RuntimeError(
"Could not find the generic base class;\n"
"This should never happen;\n"
f"Does {cls} inherit from one of {generic_bases} ?"
)
extracted = extract_type_arg(target_base_class, index)
if is_typevar(extracted):
# If the extracted type argument is itself a type variable
# then that means the subclass itself is generic, so we have
# to resolve the type argument from the class itself, not
# the base class.
#
# Note: if there is more than 1 type argument, the subclass could
# change the ordering of the type arguments, this is not currently
# supported.
return extract_type_arg(typ, index)
return extracted
raise RuntimeError(failure_message or f"Could not resolve inner type variable at index {index} for {typ}")
================================================
FILE: zhipuai/core/_utils/_utils.py
================================================
from __future__ import annotations
import os
import re
import inspect
import functools
from typing import (
Any,
Tuple,
Mapping,
TypeVar,
Callable,
Iterable,
Sequence,
cast,
overload, List, Union,
)
from pathlib import Path
from typing_extensions import TypeGuard
import sniffio
from .._base_type import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike
from .._base_compat import parse_date as parse_date, parse_datetime as parse_datetime
def remove_notgiven_indict(obj):
if obj is None or (not isinstance(obj, Mapping)):
return obj
return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)}
_T = TypeVar("_T")
_TupleT = TypeVar("_TupleT", bound=Tuple[object, ...])
_MappingT = TypeVar("_MappingT", bound=Mapping[str, object])
_SequenceT = TypeVar("_SequenceT", bound=Sequence[object])
CallableT = TypeVar("CallableT", bound=Callable[..., Any])
def flatten(t: Iterable[Iterable[_T]]) -> list[_T]:
return [item for sublist in t for item in sublist]
def extract_files(
# TODO: this needs to take Dict but variance issues.....
# create protocol type ?
query: Mapping[str, object],
*,
paths: Sequence[Sequence[str]],
) -> list[tuple[str, FileTypes]]:
"""Recursively extract files from the given dictionary based on specified paths.
A path may look like this ['foo', 'files', '', 'data'].
Note: this mutates the given dictionary.
"""
files: list[tuple[str, FileTypes]] = []
for path in paths:
files.extend(_extract_items(query, path, index=0, flattened_key=None))
return files
def _extract_items(
obj: object,
path: Sequence[str],
*,
index: int,
flattened_key: str | None,
) -> list[tuple[str, FileTypes]]:
try:
key = path[index]
except IndexError:
if isinstance(obj, NotGiven):
# no value was provided - we can safely ignore
return []
# cyclical import
from .._files import assert_is_file_content
# We have exhausted the path, return the entry we found.
assert_is_file_content(obj, key=flattened_key)
assert flattened_key is not None
return [(flattened_key, cast(FileTypes, obj))]
index += 1
if is_dict(obj):
try:
# We are at the last entry in the path so we must remove the field
if (len(path)) == index:
item = obj.pop(key)
else:
item = obj[key]
except KeyError:
# Key was not present in the dictionary, this is not indicative of an error
# as the given path may not point to a required field. We also do not want
# to enforce required fields as the API may differ from the spec in some cases.
return []
if flattened_key is None:
flattened_key = key
else:
flattened_key += f"[{key}]"
return _extract_items(
item,
path,
index=index,
flattened_key=flattened_key,
)
elif is_list(obj):
if key != "":
return []
return flatten(
[
_extract_items(
item,
path,
index=index,
flattened_key=flattened_key + "[]" if flattened_key is not None else "[]",
)
for item in obj
]
)
# Something unexpected was passed, just ignore it.
return []
def is_given(obj: NotGivenOr[_T]) -> TypeGuard[_T]:
return not isinstance(obj, NotGiven)
# Type safe methods for narrowing types with TypeVars.
# The default narrowing for isinstance(obj, dict) is dict[unknown, unknown],
# however this cause Pyright to rightfully report errors. As we know we don't
# care about the contained types we can safely use `object` in it's place.
#
# There are two separate functions defined, `is_*` and `is_*_t` for different use cases.
# `is_*` is for when you're dealing with an unknown input
# `is_*_t` is for when you're narrowing a known union type to a specific subset
def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]:
return isinstance(obj, tuple)
def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]:
return isinstance(obj, tuple)
def is_sequence(obj: object) -> TypeGuard[Sequence[object]]:
return isinstance(obj, Sequence)
def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]:
return isinstance(obj, Sequence)
def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]:
return isinstance(obj, Mapping)
def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]:
return isinstance(obj, Mapping)
def is_dict(obj: object) -> TypeGuard[dict[object, object]]:
return isinstance(obj, dict)
def is_list(obj: object) -> TypeGuard[list[object]]:
return isinstance(obj, list)
def is_iterable(obj: object) -> TypeGuard[Iterable[object]]:
return isinstance(obj, Iterable)
def deepcopy_minimal(item: _T) -> _T:
"""Minimal reimplementation of copy.deepcopy() that will only copy certain object types:
- mappings, e.g. `dict`
- list
This is done for performance reasons.
"""
if is_mapping(item):
return cast(_T, {k: deepcopy_minimal(v) for k, v in item.items()})
if is_list(item):
return cast(_T, [deepcopy_minimal(entry) for entry in item])
return item
# copied from https://github.com/Rapptz/RoboDanny
def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str:
size = len(seq)
if size == 0:
return ""
if size == 1:
return seq[0]
if size == 2:
return f"{seq[0]} {final} {seq[1]}"
return delim.join(seq[:-1]) + f" {final} {seq[-1]}"
def quote(string: str) -> str:
"""Add single quotation marks around the given string. Does *not* do any escaping."""
return f"'{string}'"
def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
"""Decorator to enforce a given set of arguments or variants of arguments are passed to the decorated function.
Useful for enforcing runtime validation of overloaded functions.
Example usage:
```py
@overload
def foo(*, a: str) -> str:
...
@overload
def foo(*, b: bool) -> str:
...
# This enforces the same constraints that a static type checker would
# i.e. that either a or b must be passed to the function
@required_args(["a"], ["b"])
def foo(*, a: str | None = None, b: bool | None = None) -> str:
...
```
"""
def inner(func: CallableT) -> CallableT:
params = inspect.signature(func).parameters
positional = [
name
for name, param in params.items()
if param.kind
in {
param.POSITIONAL_ONLY,
param.POSITIONAL_OR_KEYWORD,
}
]
@functools.wraps(func)
def wrapper(*args: object, **kwargs: object) -> object:
given_params: set[str] = set()
for i, _ in enumerate(args):
try:
given_params.add(positional[i])
except IndexError:
raise TypeError(
f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given"
) from None
for key in kwargs.keys():
given_params.add(key)
for variant in variants:
matches = all((param in given_params for param in variant))
if matches:
break
else: # no break
if len(variants) > 1:
variations = human_join(
["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants]
)
msg = f"Missing required arguments; Expected either {variations} arguments to be given"
else:
# TODO: this error message is not deterministic
missing = list(set(variants[0]) - given_params)
if len(missing) > 1:
msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}"
else:
msg = f"Missing required argument: {quote(missing[0])}"
raise TypeError(msg)
return func(*args, **kwargs)
return wrapper # type: ignore
return inner
_K = TypeVar("_K")
_V = TypeVar("_V")
@overload
def strip_not_given(obj: None) -> None:
...
@overload
def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]:
...
@overload
def strip_not_given(obj: object) -> object:
...
def strip_not_given(obj: object | None) -> object:
"""Remove all top-level keys where their values are instances of `NotGiven`"""
if obj is None:
return None
if not is_mapping(obj):
return obj
return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)}
def coerce_integer(val: str) -> int:
return int(val, base=10)
def coerce_float(val: str) -> float:
return float(val)
def coerce_boolean(val: str) -> bool:
return val == "true" or val == "1" or val == "on"
def maybe_coerce_integer(val: str | None) -> int | None:
if val is None:
return None
return coerce_integer(val)
def maybe_coerce_float(val: str | None) -> float | None:
if val is None:
return None
return coerce_float(val)
def maybe_coerce_boolean(val: str | None) -> bool | None:
if val is None:
return None
return coerce_boolean(val)
def removeprefix(string: str, prefix: str) -> str:
"""Remove a prefix from a string.
Backport of `str.removeprefix` for Python < 3.9
"""
if string.startswith(prefix):
return string[len(prefix):]
return string
def removesuffix(string: str, suffix: str) -> str:
"""Remove a suffix from a string.
Backport of `str.removesuffix` for Python < 3.9
"""
if string.endswith(suffix):
return string[: -len(suffix)]
return string
def file_from_path(path: str) -> FileTypes:
contents = Path(path).read_bytes()
file_name = os.path.basename(path)
return (file_name, contents)
def get_required_header(headers: HeadersLike, header: str) -> str:
lower_header = header.lower()
if isinstance(headers, Mapping):
headers = cast(Headers, headers)
for k, v in headers.items():
if k.lower() == lower_header and isinstance(v, str):
return v
""" to deal with the case where the header looks like Stainless-Event-Id """
intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize())
for normalized_header in [header, lower_header, header.upper(), intercaps_header]:
value = headers.get(normalized_header)
if value:
return value
raise ValueError(f"Could not find {header} header")
def get_async_library() -> str:
try:
return sniffio.current_async_library()
except Exception:
return "false"
def drop_prefix_image_data(content: Union[str, List[dict]]) -> Union[str, List[dict]]:
"""
删除 ;base64, 前缀
:param image_data:
:return:
"""
if isinstance(content, List):
for data in content:
if data.get('type') == 'image_url':
image_data = data.get("image_url").get("url")
if image_data.startswith("data:image/"):
image_data = image_data.split("base64,")[-1]
data["image_url"]["url"] = image_data
return content
================================================
FILE: zhipuai/core/logs.py
================================================
import logging
import os
import time
logger = logging.getLogger(__name__)
class LoggerNameFilter(logging.Filter):
def filter(self, record):
# return record.name.startswith("loom_core") or record.name in "ERROR" or (
# record.name.startswith("uvicorn.error")
# and record.getMessage().startswith("Uvicorn running on")
# )
return True
def get_log_file(log_path: str, sub_dir: str):
"""
sub_dir should contain a timestamp.
"""
log_dir = os.path.join(log_path, sub_dir)
# Here should be creating a new directory each time, so `exist_ok=False`
os.makedirs(log_dir, exist_ok=False)
return os.path.join(log_dir, "zhipuai.log")
def get_config_dict(
log_level: str, log_file_path: str, log_backup_count: int, log_max_bytes: int
) -> dict:
# for windows, the path should be a raw string.
log_file_path = (
log_file_path.encode("unicode-escape").decode()
if os.name == "nt"
else log_file_path
)
log_level = log_level.upper()
config_dict = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"formatter": {
"format": (
"%(asctime)s %(name)-12s %(process)d %(levelname)-8s %(message)s"
)
},
},
"filters": {
"logger_name_filter": {
"()": __name__ + ".LoggerNameFilter",
},
},
"handlers": {
"stream_handler": {
"class": "logging.StreamHandler",
"formatter": "formatter",
"level": log_level,
# "stream": "ext://sys.stdout",
# "filters": ["logger_name_filter"],
},
"file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "formatter",
"level": log_level,
"filename": log_file_path,
"mode": "a",
"maxBytes": log_max_bytes,
"backupCount": log_backup_count,
"encoding": "utf8",
},
},
"loggers": {
"loom_core": {
"handlers": ["stream_handler", "file_handler"],
"level": log_level,
"propagate": False,
}
},
"root": {
"level": log_level,
"handlers": ["stream_handler", "file_handler"],
},
}
return config_dict
def get_timestamp_ms():
t = time.time()
return int(round(t * 1000))
================================================
FILE: zhipuai/core/pagination.py
================================================
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing import Any, List, Generic, TypeVar, Optional, cast
from typing_extensions import Protocol, override, runtime_checkable
from ._http_client import BasePage, PageInfo, BaseSyncPage
__all__ = ["SyncPage", "SyncCursorPage"]
_T = TypeVar("_T")
@runtime_checkable
class CursorPageItem(Protocol):
id: Optional[str]
class SyncPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
"""Note: no pagination actually occurs yet, this is for forwards-compatibility."""
data: List[_T]
object: str
@override
def _get_page_items(self) -> List[_T]:
data = self.data
if not data:
return []
return data
@override
def next_page_info(self) -> None:
"""
This page represents a response that isn't actually paginated at the API level
so there will never be a next page.
"""
return None
class SyncCursorPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
data: List[_T]
@override
def _get_page_items(self) -> List[_T]:
data = self.data
if not data:
return []
return data
@override
def next_page_info(self) -> Optional[PageInfo]:
data = self.data
if not data:
return None
item = cast(Any, data[-1])
if not isinstance(item, CursorPageItem) or item.id is None:
# TODO emit warning log
return None
return PageInfo(params={"after": item.id})
================================================
FILE: zhipuai/types/__init__.py
================================================
================================================
FILE: zhipuai/types/agents/__init__.py
================================================
================================================
FILE: zhipuai/types/agents/agents_completion.py
================================================
from typing import List, Optional
from ...core import BaseModel
__all__ = ["AgentsCompletion", "AgentsCompletionUsage"]
class AgentsCompletionMessage(BaseModel):
content: Optional[object] = None
role: str
class AgentsCompletionUsage(BaseModel):
prompt_tokens: int
completion_tokens: int
total_tokens: int
class AgentsCompletionChoice(BaseModel):
index: int
finish_reason: str
message: AgentsCompletionMessage
class AgentsError(BaseModel):
code: Optional[str] = None
message: Optional[str] = None
class AgentsCompletion(BaseModel):
agent_id: Optional[str] = None
conversation_id: Optional[str] = None
status: Optional[str] = None
choices: List[AgentsCompletionChoice]
request_id: Optional[str] = None
id: Optional[str] = None
usage: Optional[AgentsCompletionUsage] = None
error: Optional[AgentsError] = None
================================================
FILE: zhipuai/types/agents/agents_completion_chunk.py
================================================
from typing import List, Optional, Dict, Any
from ...core import BaseModel
__all__ = [
"AgentsCompletionUsage",
"AgentsCompletionChunk",
"AgentsChoice",
"AgentsChoiceDelta"
]
class AgentsChoiceDelta(BaseModel):
content: Optional[object] = None
role: Optional[str] = None
class AgentsChoice(BaseModel):
delta: AgentsChoiceDelta
finish_reason: Optional[str] = None
index: int
class AgentsCompletionUsage(BaseModel):
prompt_tokens: int
completion_tokens: int
total_tokens: int
class AgentsError(BaseModel):
code: Optional[str] = None
message: Optional[str] = None
class AgentsCompletionChunk(BaseModel):
agent_id: Optional[str] = None
conversation_id: Optional[str] = None
id: Optional[str] = None
choices: List[AgentsChoice]
usage: Optional[AgentsCompletionUsage] = None
error: Optional[AgentsError] = None
================================================
FILE: zhipuai/types/agents/chat_completions_create_param.py
================================================
from typing import Optional
from typing_extensions import TypedDict
class Reference(TypedDict, total=False):
enable: Optional[bool]
search_query: Optional[str]
================================================
FILE: zhipuai/types/assistant/__init__.py
================================================
from .assistant_completion import AssistantCompletion
__all__ = [
'AssistantCompletion',
]
================================================
FILE: zhipuai/types/assistant/assistant_completion.py
================================================
from typing import List, Optional, Dict, Any
from .message import MessageContent
from ...core import BaseModel
__all__ = ["AssistantCompletion", "CompletionUsage"]
class ErrorInfo(BaseModel):
code: str # 错误码
message: str # 错误信息
class AssistantChoice(BaseModel):
index: int # 结果下标
delta: MessageContent # 当前会话输出消息体
finish_reason: str
"""
# 推理结束原因 stop代表推理自然结束或触发停止词。 sensitive 代表模型推理内容被安全审核接口拦截。请注意,针对此类内容,请用户自行判断并决定是否撤回已公开的内容。
# network_error 代表模型推理服务异常。
"""
metadata: dict # 元信息,拓展字段
class CompletionUsage(BaseModel):
prompt_tokens: int # 输入的 tokens 数量
completion_tokens: int # 输出的 tokens 数量
total_tokens: int # 总 tokens 数量
class AssistantCompletion(BaseModel):
id: str # 请求 ID
conversation_id: str # 会话 ID
assistant_id: str # 智能体 ID
created: int # 请求创建时间,Unix 时间戳
status: str # 返回状态,包括:`completed` 表示生成结束`in_progress`表示生成中 `failed` 表示生成异常
last_error: Optional[ErrorInfo] # 异常信息
choices: List[AssistantChoice] # 增量返回的信息
metadata: Optional[Dict[str, Any]] # 元信息,拓展字段
usage: Optional[CompletionUsage] # tokens 数量统计
================================================
FILE: zhipuai/types/assistant/assistant_conversation_params.py
================================================
from typing import TypedDict, List, Optional, Union
class ConversationParameters(TypedDict, total=False):
assistant_id: str # 智能体 ID
page: int # 当前分页
page_size: int # 分页数量
================================================
FILE: zhipuai/types/assistant/assistant_conversation_resp.py
================================================
from typing import List, Optional, Dict, Any
from ...core import BaseModel
__all__ = [
"ConversationUsageListResp"
]
class Usage(BaseModel):
prompt_tokens: int # 用户输入的 tokens 数量
completion_tokens: int # 模型输入的 tokens 数量
total_tokens: int # 总 tokens 数量
class ConversationUsage(BaseModel):
id: str # 会话 id
assistant_id: str # 智能体Assistant id
create_time: int # 创建时间
update_time: int # 更新时间
usage: Usage # 会话中 tokens 数量统计
class ConversationUsageList(BaseModel):
assistant_id: str # 智能体id
has_more: bool # 是否还有更多页
conversation_list: List[ConversationUsage] # 返回的
class ConversationUsageListResp(BaseModel):
code: int
msg: str
data: ConversationUsageList
================================================
FILE: zhipuai/types/assistant/assistant_create_params.py
================================================
from typing import TypedDict, List, Optional, Union
class AssistantAttachments:
file_id: str
class MessageTextContent:
type: str # 目前支持 type = text
text: str
MessageContent = Union[MessageTextContent]
class ConversationMessage(TypedDict):
"""会话消息体"""
role: str # 用户的输入角色,例如 'user'
content: List[MessageContent] # 会话消息体的内容
class AssistantParameters(TypedDict, total=False):
"""智能体参数类"""
assistant_id: str # 智能体 ID
conversation_id: Optional[str] # 会话 ID,不传则创建新会话
model: str # 模型名称,默认为 'GLM-4-Assistant'
stream: bool # 是否支持流式 SSE,需要传入 True
messages: List[ConversationMessage] # 会话消息体
attachments: Optional[List[AssistantAttachments]] # 会话指定的文件,非必填
metadata: Optional[dict] # 元信息,拓展字段,非必填
class TranslateParameters(TypedDict, total=False):
from_language: str
to_language: str
class ExtraParameters(TypedDict, total=False):
translate: TranslateParameters
================================================
FILE: zhipuai/types/assistant/assistant_support_resp.py
================================================
from typing import List, Optional, Dict, Any
from .message import MessageContent
from ...core import BaseModel
__all__ = [
"AssistantSupportResp"
]
class AssistantSupport(BaseModel):
assistant_id: str # 智能体的 Assistant id,用于智能体会话
created_at: int # 创建时间
updated_at: int # 更新时间
name: str # 智能体名称
avatar: str # 智能体头像
description: str # 智能体描述
status: str # 智能体状态,目前只有 publish
tools: List[str] # 智能体支持的工具名
starter_prompts: List[str] # 智能体启动推荐的 prompt
class AssistantSupportResp(BaseModel):
code: int
msg: str
data: List[AssistantSupport] # 智能体列表
================================================
FILE: zhipuai/types/assistant/message/__init__.py
================================================
from .message_content import MessageContent
__all__ = [
"MessageContent"
]
================================================
FILE: zhipuai/types/assistant/message/message_content.py
================================================
from typing import Union
from typing_extensions import Annotated, TypeAlias
from ....core._utils import PropertyInfo
from .tools_delta_block import ToolsDeltaBlock
from .text_content_block import TextContentBlock
__all__ = ["MessageContent"]
MessageContent: TypeAlias = Annotated[
Union[ToolsDeltaBlock, TextContentBlock],
PropertyInfo(discriminator="type"),
]
================================================
FILE: zhipuai/types/assistant/message/text_content_block.py
================================================
from typing_extensions import Literal
from ....core import BaseModel
__all__ = ["TextContentBlock"]
class TextContentBlock(BaseModel):
content: str
role: str = "assistant"
type: Literal["content"] = "content"
"""Always `content`."""
================================================
FILE: zhipuai/types/assistant/message/tools/code_interpreter_delta_block.py
================================================
from typing import List
from typing_extensions import Literal
__all__ = ["CodeInterpreterToolBlock"]
from .....core import BaseModel
class CodeInterpreterToolOutput(BaseModel):
"""代码工具输出结果"""
type: str # 代码执行日志,目前只有 logs
logs: str # 代码执行的日志结果
error_msg: str # 错误信息
class CodeInterpreter(BaseModel):
"""代码解释器"""
input: str # 生成的代码片段,输入给代码沙盒
outputs: List[CodeInterpreterToolOutput] # 代码执行后的输出结果
class CodeInterpreterToolBlock(BaseModel):
"""代码工具块"""
code_interpreter: CodeInterpreter # 代码解释器对象
type: Literal["code_interpreter"] # 调用工具的类型,始终为 `code_interpreter`
================================================
FILE: zhipuai/types/assistant/message/tools/drawing_tool_delta_block.py
================================================
from typing import List
from typing_extensions import Literal
from .....core import BaseModel
__all__ = ["DrawingToolBlock"]
class DrawingToolOutput(BaseModel):
image: str
class DrawingTool(BaseModel):
input: str
outputs: List[DrawingToolOutput]
class DrawingToolBlock(BaseModel):
drawing_tool: DrawingTool
type: Literal["drawing_tool"]
"""Always `drawing_tool`."""
================================================
FILE: zhipuai/types/assistant/message/tools/function_delta_block.py
================================================
from typing import List, Union
from typing_extensions import Literal
__all__ = ["FunctionToolBlock"]
from .....core import BaseModel
class FunctionToolOutput(BaseModel):
content: str
class FunctionTool(BaseModel):
name: str
arguments: Union[str,dict]
outputs: List[FunctionToolOutput]
class FunctionToolBlock(BaseModel):
function: FunctionTool
type: Literal["function"]
"""Always `drawing_tool`."""
================================================
FILE: zhipuai/types/assistant/message/tools/retrieval_delta_black.py
================================================
from typing import List
from typing_extensions import Literal
from .....core import BaseModel
class RetrievalToolOutput(BaseModel):
"""
This class represents the output of a retrieval tool.
Attributes:
- text (str): The text snippet retrieved from the knowledge base.
- document (str): The name of the document from which the text snippet was retrieved, returned only in intelligent configuration.
"""
text: str
document: str
class RetrievalTool(BaseModel):
"""
This class represents the outputs of a retrieval tool.
Attributes:
- outputs (List[RetrievalToolOutput]): A list of text snippets and their respective document names retrieved from the knowledge base.
"""
outputs: List[RetrievalToolOutput]
class RetrievalToolBlock(BaseModel):
"""
This class represents a block for invoking the retrieval tool.
Attributes:
- retrieval (RetrievalTool): An instance of the RetrievalTool class containing the retrieval outputs.
- type (Literal["retrieval"]): The type of tool being used, always set to "retrieval".
"""
retrieval: RetrievalTool
type: Literal["retrieval"]
"""Always `retrieval`."""
================================================
FILE: zhipuai/types/assistant/message/tools/tools_type.py
================================================
from typing import Union
from typing_extensions import Annotated, TypeAlias
from .code_interpreter_delta_block import CodeInterpreterToolBlock
from .retrieval_delta_black import RetrievalToolBlock
from .web_browser_delta_block import WebBrowserToolBlock
from .....core._utils import PropertyInfo
from .drawing_tool_delta_block import DrawingToolBlock
from .function_delta_block import FunctionToolBlock
__all__ = ["ToolsType"]
ToolsType: TypeAlias = Annotated[
Union[DrawingToolBlock, CodeInterpreterToolBlock, WebBrowserToolBlock, RetrievalToolBlock, FunctionToolBlock],
PropertyInfo(discriminator="type"),
]
================================================
FILE: zhipuai/types/assistant/message/tools/web_browser_delta_block.py
================================================
from typing import List
from typing_extensions import Literal
from .....core import BaseModel
__all__ = ["WebBrowserToolBlock"]
class WebBrowserOutput(BaseModel):
"""
This class represents the output of a web browser search result.
Attributes:
- title (str): The title of the search result.
- link (str): The URL link to the search result's webpage.
- content (str): The textual content extracted from the search result.
- error_msg (str): Any error message encountered during the search or retrieval process.
"""
title: str
link: str
content: str
error_msg: str
class WebBrowser(BaseModel):
"""
This class represents the input and outputs of a web browser search.
Attributes:
- input (str): The input query for the web browser search.
- outputs (List[WebBrowserOutput]): A list of search results returned by the web browser.
"""
input: str
outputs: List[WebBrowserOutput]
class WebBrowserToolBlock(BaseModel):
"""
This class represents a block for invoking the web browser tool.
Attributes:
- web_browser (WebBrowser): An instance of the WebBrowser class containing the search input and outputs.
- type (Literal["web_browser"]): The type of tool being used, always set to "web_browser".
"""
web_browser: WebBrowser
type: Literal["web_browser"]
================================================
FILE: zhipuai/types/assistant/message/tools_delta_block.py
================================================
from typing import Optional, List
from typing_extensions import Literal
from .tools.tools_type import ToolsType
from ....core import BaseModel
__all__ = ["ToolsDeltaBlock"]
class ToolsDeltaBlock(BaseModel):
tool_calls: List[ToolsType]
"""The index of the content part in the message."""
role: str = "tool"
type: Literal["tool_calls"] = "tool_calls"
"""Always `tool_calls`."""
================================================
FILE: zhipuai/types/audio/__init__.py
================================================
from .audio_speech_params import(
AudioSpeechParams
)
from .audio_customization_param import(
AudioCustomizationParam
)
from .transcriptions_create_param import(
TranscriptionsParam
)
__all__ = ["AudioSpeechParams","AudioCustomizationParam","TranscriptionsParam"]
================================================
FILE: zhipuai/types/audio/audio_customization_param.py
================================================
from __future__ import annotations
from typing import List, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = ["AudioCustomizationParam"]
from ..sensitive_word_check import SensitiveWordCheckRequest
class AudioCustomizationParam(TypedDict, total=False):
model: str
"""模型编码"""
input: str
"""需要生成语音的文本"""
voice_text: str
"""需要生成语音的音色"""
response_format: str
"""需要生成语音文件的格式"""
sensitive_word_check: Optional[SensitiveWordCheckRequest]
request_id: str
"""由用户端传参,需保证唯一性;用于区分每次请求的唯一标识,用户端不传时平台会默认生成。"""
user_id: str
"""用户端。"""
================================================
FILE: zhipuai/types/audio/audio_speech_chunk.py
================================================
from typing import List, Optional, Dict, Any
from ...core import BaseModel
__all__ = [
"AudioSpeechChunk",
"AudioError",
"AudioSpeechChoice",
"AudioSpeechDelta"
]
class AudioSpeechDelta(BaseModel):
content: Optional[str] = None
role: Optional[str] = None
class AudioSpeechChoice(BaseModel):
delta: AudioSpeechDelta
finish_reason: Optional[str] = None
index: int
class AudioError(BaseModel):
code: Optional[str] = None
message: Optional[str] = None
class AudioSpeechChunk(BaseModel):
choices: List[AudioSpeechChoice]
request_id: Optional[str] = None
created: Optional[int] = None
error: Optional[AudioError] = None
================================================
FILE: zhipuai/types/audio/audio_speech_params.py
================================================
from __future__ import annotations
from typing import List, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = ["AudioSpeechParams"]
from ..sensitive_word_check import SensitiveWordCheckRequest
class AudioSpeechParams(TypedDict, total=False):
model: str
"""模型编码"""
input: str
"""需要生成语音的文本"""
voice: str
"""需要生成语音的音色"""
response_format: str
"""需要生成语音文件的格式"""
sensitive_word_check: Optional[SensitiveWordCheckRequest]
request_id: str
"""由用户端传参,需保证唯一性;用于区分每次请求的唯一标识,用户端不传时平台会默认生成。"""
user_id: str
"""用户端。"""
================================================
FILE: zhipuai/types/audio/transcriptions_create_param.py
================================================
from __future__ import annotations
from typing import List, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = ["TranscriptionsParam"]
from ..sensitive_word_check import SensitiveWordCheckRequest
class TranscriptionsParam(TypedDict, total=False):
model: str
"""模型编码"""
temperature:float
"""采样温度"""
stream: bool
"""是否流式输出"""
sensitive_word_check: Optional[SensitiveWordCheckRequest]
request_id: str
"""由用户端传参,需保证唯一性;用于区分每次请求的唯一标识,用户端不传时平台会默认生成。"""
user_id: str
"""用户端。"""
================================================
FILE: zhipuai/types/batch.py
================================================
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import builtins
from typing import List, Optional
from typing_extensions import Literal
from ..core import BaseModel
from .batch_error import BatchError
from .batch_request_counts import BatchRequestCounts
__all__ = ["Batch", "Errors"]
class Errors(BaseModel):
data: Optional[List[BatchError]] = None
object: Optional[str] = None
"""这个类型,一直是`list`。"""
class Batch(BaseModel):
id: str
completion_window: str
"""用于执行请求的地址信息。"""
created_at: int
"""这是 Unix timestamp (in seconds) 表示的创建时间。"""
endpoint: str
"""这是ZhipuAI endpoint的地址。"""
input_file_id: str
"""标记为batch的输入文件的ID。"""
object: Literal["batch"]
"""这个类型,一直是`batch`."""
status: Literal[
"validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"
]
"""batch 的状态。"""
cancelled_at: Optional[int] = None
"""Unix timestamp (in seconds) 表示的取消时间。"""
cancelling_at: Optional[int] = None
"""Unix timestamp (in seconds) 表示发起取消的请求时间 """
completed_at: Optional[int] = None
"""Unix timestamp (in seconds) 表示的完成时间。"""
error_file_id: Optional[str] = None
"""这个文件id包含了执行请求失败的请求的输出。"""
errors: Optional[Errors] = None
expired_at: Optional[int] = None
"""Unix timestamp (in seconds) 表示的将在过期时间。"""
expires_at: Optional[int] = None
"""Unix timestamp (in seconds) 触发过期"""
failed_at: Optional[int] = None
"""Unix timestamp (in seconds) 表示的失败时间。"""
finalizing_at: Optional[int] = None
"""Unix timestamp (in seconds) 表示的最终时间。"""
in_progress_at: Optional[int] = None
"""Unix timestamp (in seconds) 表示的开始处理时间。"""
metadata: Optional[builtins.object] = None
"""
key:value形式的元数据,以便将信息存储
结构化格式。键的长度是64个字符,值最长512个字符
"""
output_file_id: Optional[str] = None
"""完成请求的输出文件的ID。"""
request_counts: Optional[BatchRequestCounts] = None
"""批次中不同状态的请求计数"""
================================================
FILE: zhipuai/types/batch_create_params.py
================================================
from __future__ import annotations
from typing import Dict, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = ["BatchCreateParams"]
class BatchCreateParams(TypedDict, total=False):
completion_window: Required[str]
"""The time frame within which the batch should be processed.
Currently only `24h` is supported.
"""
endpoint: Required[Literal["/v1/chat/completions", "/v1/embeddings"]]
"""The endpoint to be used for all requests in the batch.
Currently `/v1/chat/completions` and `/v1/embeddings` are supported.
"""
input_file_id: Required[str]
"""The ID of an uploaded file that contains requests for the new batch.
See [upload file](https://platform.openai.com/docs/api-reference/files/create)
for how to upload a file.
Your input file must be formatted as a
[JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput),
and must be uploaded with the purpose `batch`.
"""
metadata: Optional[Dict[str, str]]
"""Optional custom metadata for the batch."""
auto_delete_input_file: Optional[bool]
================================================
FILE: zhipuai/types/batch_error.py
================================================
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing import Optional
from ..core import BaseModel
__all__ = ["BatchError"]
class BatchError(BaseModel):
code: Optional[str] = None
"""定义的业务错误码"""
line: Optional[int] = None
"""文件中的行号"""
message: Optional[str] = None
"""关于对话文件中的错误的描述"""
param: Optional[str] = None
"""参数名称,如果有的话"""
================================================
FILE: zhipuai/types/batch_list_params.py
================================================
from __future__ import annotations
from typing_extensions import TypedDict
__all__ = ["BatchListParams"]
class BatchListParams(TypedDict, total=False):
after: str
"""分页的游标,用于获取下一页的数据。
`after` 是一个指向当前页面的游标,用于获取下一页的数据。如果没有提供 `after`,则返回第一页的数据。
list.
"""
limit: int
"""这个参数用于限制返回的结果数量。
Limit 用于限制返回的结果数量。默认值为 10
"""
================================================
FILE: zhipuai/types/batch_request_counts.py
================================================
from ..core import BaseModel
__all__ = ["BatchRequestCounts"]
class BatchRequestCounts(BaseModel):
completed: int
"""这个数字表示已经完成的请求。"""
failed: int
"""这个数字表示失败的请求。"""
total: int
"""这个数字表示总的请求。"""
================================================
FILE: zhipuai/types/chat/__init__.py
================================================
================================================
FILE: zhipuai/types/chat/async_chat_completion.py
================================================
from typing import List, Optional
from ...core import BaseModel
from .chat_completion import CompletionChoice, CompletionUsage
__all__ = ["AsyncTaskStatus", "AsyncCompletion"]
class AsyncTaskStatus(BaseModel):
id: Optional[str] = None
request_id: Optional[str] = None
model: Optional[str] = None
task_status: Optional[str] = None
class AsyncCompletion(BaseModel):
id: Optional[str] = None
request_id: Optional[str] = None
model: Optional[str] = None
task_status: str
choices: List[CompletionChoice]
usage: CompletionUsage
================================================
FILE: zhipuai/types/chat/chat_completion.py
================================================
from typing import List, Optional
from ...core import BaseModel
__all__ = ["Completion", "CompletionUsage"]
class Function(BaseModel):
arguments: str
name: str
class CompletionMessageToolCall(BaseModel):
id: str
function: Function
type: str
class CompletionMessage(BaseModel):
content: Optional[str] = None
role: str
reasoning_content: Optional[str] = None
tool_calls: Optional[List[CompletionMessageToolCall]] = None
class CompletionUsage(BaseModel):
prompt_tokens: int
completion_tokens: int
total_tokens: int
class CompletionChoice(BaseModel):
index: int
finish_reason: str
message: CompletionMessage
class Completion(BaseModel):
model: Optional[str] = None
created: Optional[int] = None
choices: List[CompletionChoice]
request_id: Optional[str] = None
id: Optional[str] = None
usage: CompletionUsage
================================================
FILE: zhipuai/types/chat/chat_completion_chunk.py
================================================
from typing import List, Optional, Dict, Any
from ...core import BaseModel
__all__ = [
"CompletionUsage",
"ChatCompletionChunk",
"Choice",
"ChoiceDelta",
"ChoiceDeltaFunctionCall",
"ChoiceDeltaToolCall",
"ChoiceDeltaToolCallFunction",
"AudioCompletionChunk"
]
class ChoiceDeltaFunctionCall(BaseModel):
arguments: Optional[str] = None
name: Optional[str] = None
class ChoiceDeltaToolCallFunction(BaseModel):
arguments: Optional[str] = None
name: Optional[str] = None
class ChoiceDeltaToolCall(BaseModel):
index: int
id: Optional[str] = None
function: Optional[ChoiceDeltaToolCallFunction] = None
type: Optional[str] = None
class AudioCompletionChunk(BaseModel):
id: Optional[str] = None
data: Optional[str] = None
expires_at: Optional[int] = None
class ChoiceDelta(BaseModel):
content: Optional[str] = None
role: Optional[str] = None
reasoning_content: Optional[str] = None
tool_calls: Optional[List[ChoiceDeltaToolCall]] = None
audio: Optional[AudioCompletionChunk] = None
class Choice(BaseModel):
delta: ChoiceDelta
finish_reason: Optional[str] = None
index: int
class PromptTokensDetails(BaseModel):
cached_tokens: int
class CompletionTokensDetails(BaseModel):
reasoning_tokens: int
class CompletionUsage(BaseModel):
prompt_tokens: int
prompt_tokens_details: Optional[PromptTokensDetails] = None
completion_tokens: int
completion_tokens_details: Optional[CompletionTokensDetails] = None
total_tokens: int
class ChatCompletionChunk(BaseModel):
id: Optional[str] = None
choices: List[Choice]
created: Optional[int] = None
model: Optional[str] = None
usage: Optional[CompletionUsage] = None
extra_json: Dict[str, Any]
================================================
FILE: zhipuai/types/chat/chat_completions_create_param.py
================================================
from typing import Optional
from typing_extensions import TypedDict
class Reference(TypedDict, total=False):
enable: Optional[bool]
search_query: Optional[str]
================================================
FILE: zhipuai/types/chat/code_geex/code_geex_params.py
================================================
from typing import List, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = [
"CodeGeexTarget",
"CodeGeexContext",
"CodeGeexExtra",
]
class CodeGeexTarget(TypedDict, total=False):
"""补全的内容参数"""
path: Optional[str]
"""文件路径"""
language: Required[Literal[
"c", "c++", "cpp", "c#", "csharp", "c-sharp", "css", "cuda", "dart", "lua",
"objectivec", "objective-c", "objective-c++", "python", "perl", "prolog",
"swift", "lisp", "java", "scala", "tex", "jsx", "tsx", "vue", "markdown",
"html", "php", "js", "javascript", "typescript", "go", "shell", "rust",
"sql", "kotlin", "vb", "ruby", "pascal", "r", "fortran", "lean", "matlab",
"delphi", "scheme", "basic", "assembly", "groovy", "abap", "gdscript",
"haskell", "julia", "elixir", "excel", "clojure", "actionscript", "solidity",
"powershell", "erlang", "cobol", "alloy", "awk", "thrift", "sparql", "augeas",
"cmake", "f-sharp", "stan", "isabelle", "dockerfile", "rmarkdown",
"literate-agda", "tcl", "glsl", "antlr", "verilog", "racket", "standard-ml",
"elm", "yaml", "smalltalk", "ocaml", "idris", "visual-basic", "protocol-buffer",
"bluespec", "applescript", "makefile", "tcsh", "maple", "systemverilog",
"literate-coffeescript", "vhdl", "restructuredtext", "sas", "literate-haskell",
"java-server-pages", "coffeescript", "emacs-lisp", "mathematica", "xslt",
"zig", "common-lisp", "stata", "agda", "ada"
]]
"""代码语言类型,如python"""
code_prefix: Required[str]
"""补全位置的前文"""
code_suffix: Required[str]
"""补全位置的后文"""
class CodeGeexContext(TypedDict, total=False):
"""附加代码"""
path: Required[str]
"""附加代码文件的路径"""
code: Required[str]
"""附加的代码内容"""
class CodeGeexExtra(TypedDict, total=False):
target: Required[CodeGeexTarget]
"""补全的内容参数"""
contexts: Optional[List[CodeGeexContext]]
"""附加代码"""
================================================
FILE: zhipuai/types/embeddings.py
================================================
from __future__ import annotations
from typing import Optional, List
from ..core import BaseModel
from .chat.chat_completion import CompletionUsage
__all__ = ["Embedding", "EmbeddingsResponded"]
class Embedding(BaseModel):
object: str
index: Optional[int] = None
embedding: List[float]
class EmbeddingsResponded(BaseModel):
object: str
data: List[Embedding]
model: str
usage: CompletionUsage
================================================
FILE: zhipuai/types/file_parser/__init__.py
================================================
================================================
FILE: zhipuai/types/file_parser/file_parser_create_params.py
================================================
from __future__ import annotations
from typing_extensions import Literal, Required, TypedDict
from ...core import NOT_GIVEN, Body, Headers, NotGiven, FileTypes
__all__ = ["FileParserCreateParams", "FileParserDownloadParams"]
class FileParserCreateParams(TypedDict):
file: FileTypes
"""上传的文件"""
file_type: str
"""文件类型"""
tool_type: Literal["simple", "doc2x", "tencent", "zhipu-pro"]
"""工具类型"""
class FileParserDownloadParams(TypedDict):
task_id: str
"""解析任务id"""
format_type: Literal["text", "download_link"]
"""结果返回类型"""
================================================
FILE: zhipuai/types/file_parser/file_parser_resp.py
================================================
from typing import List, Optional
from zhipuai.core import BaseModel
__all__ = [
"FileParserTaskCreateResp"
]
class FileParserTaskCreateResp(BaseModel):
task_id: str
# 任务id
message: str
# message
success: bool
# 是否成功
================================================
FILE: zhipuai/types/files/__init__.py
================================================
from .file_object import FileObject, ListOfFileObject
from .upload_detail import UploadDetail
from .file_deleted import FileDeleted
__all__ = [
"FileObject",
"ListOfFileObject",
"UploadDetail",
"FileDeleted"
]
================================================
FILE: zhipuai/types/files/file_create_params.py
================================================
from __future__ import annotations
from typing import List, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = ["FileCreateParams"]
from . import UploadDetail
from ...core import FileTypes
class FileCreateParams(TypedDict, total=False):
file: FileTypes
"""file和 upload_detail二选一必填"""
upload_detail: List[UploadDetail]
"""file和 upload_detail二选一必填"""
purpose: Required[Literal["fine-tune", "retrieval", "batch"]]
"""
上传文件的用途,支持 "fine-tune和 "retrieval"
retrieval支持上传Doc、Docx、PDF、Xlsx、URL类型文件,且单个文件的大小不超过 5MB。
fine-tune支持上传.jsonl文件且当前单个文件的大小最大可为 100 MB ,文件中语料格式需满足微调指南中所描述的格式。
"""
custom_separator: Optional[List[str]]
"""
当 purpose 为 retrieval 且文件类型为 pdf, url, docx 时上传,切片规则默认为 `\n`。
"""
knowledge_id: str
"""
当文件上传目的为 retrieval 时,需要指定知识库ID进行上传。
"""
sentence_size: int
"""
当文件上传目的为 retrieval 时,需要指定知识库ID进行上传。
"""
================================================
FILE: zhipuai/types/files/file_deleted.py
================================================
from typing_extensions import Literal
from ...core import BaseModel
__all__ = ["FileDeleted"]
class FileDeleted(BaseModel):
id: str
deleted: bool
object: Literal["file"]
================================================
FILE: zhipuai/types/files/file_object.py
================================================
from typing import Optional, List
from ...core import BaseModel
__all__ = ["FileObject", "ListOfFileObject"]
class FileObject(BaseModel):
id: Optional[str] = None
bytes: Optional[int] = None
created_at: Optional[int] = None
filename: Optional[str] = None
object: Optional[str] = None
purpose: Optional[str] = None
status: Optional[str] = None
status_details: Optional[str] = None
class ListOfFileObject(BaseModel):
object: Optional[str] = None
data: List[FileObject]
has_more: Optional[bool] = None
================================================
FILE: zhipuai/types/files/upload_detail.py
================================================
from typing import Optional, List, Dict
from ...core import BaseModel
class UploadDetail(BaseModel):
url: str
knowledge_type: int
file_name: Optional[str] = None
sentence_size: Optional[int] = None
custom_separator: Optional[List[str]] = None
callback_url: Optional[str] = None
callback_header: Optional[Dict[str,str]] = None
================================================
FILE: zhipuai/types/fine_tuning/__init__.py
================================================
from __future__ import annotations
from .fine_tuning_job import FineTuningJob as FineTuningJob
from .fine_tuning_job import ListOfFineTuningJob as ListOfFineTuningJob
from .fine_tuning_job_event import FineTuningJobEvent as FineTuningJobEvent
================================================
FILE: zhipuai/types/fine_tuning/fine_tuning_job.py
================================================
from typing import List, Union, Optional, Dict, Any
from ...core import BaseModel
__all__ = ["FineTuningJob", "Error", "Hyperparameters", "ListOfFineTuningJob" ]
class Error(BaseModel):
code: str
message: str
param: Optional[str] = None
class Hyperparameters(BaseModel):
n_epochs: Union[str, int, None] = None
class FineTuningJob(BaseModel):
id: Optional[str] = None
request_id: Optional[str] = None
created_at: Optional[int] = None
error: Optional[Error] = None
fine_tuned_model: Optional[str] = None
finished_at: Optional[int] = None
hyperparameters: Optional[Hyperparameters] = None
model: Optional[str] = None
object: Optional[str] = None
result_files: List[str]
status: str
trained_tokens: Optional[int] = None
training_file: str
validation_file: Optional[str] = None
class ListOfFineTuningJob(BaseModel):
object: Optional[str] = None
data: List[FineTuningJob]
has_more: Optional[bool] = None
================================================
FILE: zhipuai/types/fine_tuning/fine_tuning_job_event.py
================================================
from typing import List, Union, Optional
from ...core import BaseModel
__all__ = ["FineTuningJobEvent", "Metric", "JobEvent"]
class Metric(BaseModel):
epoch: Optional[Union[str, int, float]] = None
current_steps: Optional[int] = None
total_steps: Optional[int] = None
elapsed_time: Optional[str] = None
remaining_time: Optional[str] = None
trained_tokens: Optional[int] = None
loss: Optional[Union[str, int, float]] = None
eval_loss: Optional[Union[str, int, float]] = None
acc: Optional[Union[str, int, float]] = None
eval_acc: Optional[Union[str, int, float]] = None
learning_rate: Optional[Union[str, int, float]] = None
class JobEvent(BaseModel):
object: Optional[str] = None
id: Optional[str] = None
type: Optional[str] = None
created_at: Optional[int] = None
level: Optional[str] = None
message: Optional[str] = None
data: Optional[Metric] = None
class FineTuningJobEvent(BaseModel):
object: Optional[str] = None
data: List[JobEvent]
has_more: Optional[bool] = None
================================================
FILE: zhipuai/types/fine_tuning/job_create_params.py
================================================
from __future__ import annotations
from typing import Union
from typing_extensions import Literal, TypedDict
__all__ = ["Hyperparameters"]
class Hyperparameters(TypedDict, total=False):
batch_size: Union[Literal["auto"], int]
learning_rate_multiplier: Union[Literal["auto"], float]
n_epochs: Union[Literal["auto"], int]
================================================
FILE: zhipuai/types/fine_tuning/models/__init__.py
================================================
from .fine_tuned_models import FineTunedModelsStatus
================================================
FILE: zhipuai/types/fine_tuning/models/fine_tuned_models.py
================================================
from typing import List, Union, Optional, ClassVar
from ....core import BaseModel, PYDANTIC_V2, ConfigDict
__all__ = ["FineTunedModelsStatus"]
class FineTunedModelsStatus(BaseModel):
if PYDANTIC_V2:
model_config: ClassVar[ConfigDict] = ConfigDict(extra="allow", protected_namespaces=())
request_id: str #请求id
model_name: str #模型名称
delete_status: str #删除状态 deleting(删除中), deleted (已删除)
================================================
FILE: zhipuai/types/image.py
================================================
from __future__ import annotations
from typing import Optional, List
from ..core import BaseModel
__all__ = ["GeneratedImage", "ImagesResponded"]
class GeneratedImage(BaseModel):
b64_json: Optional[str] = None
url: Optional[str] = None
revised_prompt: Optional[str] = None
class ImagesResponded(BaseModel):
created: int
data: List[GeneratedImage]
================================================
FILE: zhipuai/types/knowledge/__init__.py
================================================
from .knowledge import KnowledgeInfo
from .knowledge_used import KnowledgeStatistics, KnowledgeUsed
__all__ = [
'KnowledgeInfo',
"KnowledgeStatistics",
"KnowledgeUsed",
]
================================================
FILE: zhipuai/types/knowledge/document/__init__.py
================================================
from .document import DocumentData, DocumentObject, DocumentSuccessinfo, DocumentFailedInfo
__all__ = [
"DocumentData",
"DocumentObject",
"DocumentSuccessinfo",
"DocumentFailedInfo",
]
================================================
FILE: zhipuai/types/knowledge/document/document.py
================================================
from typing import Optional, List
from ....core import BaseModel
__all__ = ["DocumentData", "DocumentObject", "DocumentSuccessinfo", "DocumentFailedInfo"]
class DocumentSuccessinfo(BaseModel):
documentId: Optional[str] = None
"""文件id"""
filename: Optional[str] = None
"""文件名称"""
class DocumentFailedInfo(BaseModel):
failReason: Optional[str] = None
"""上传失败的原因,包括:文件格式不支持、文件大小超出限制、知识库容量已满、容量上限为 50 万字。"""
filename: Optional[str] = None
"""文件名称"""
documentId: Optional[str] = None
"""知识库id"""
class DocumentObject(BaseModel):
"""文档信息"""
successInfos: Optional[List[DocumentSuccessinfo]] = None
"""上传成功的文件信息"""
failedInfos: Optional[List[DocumentFailedInfo]] = None
"""上传失败的文件信息"""
class DocumentDataFailInfo(BaseModel):
"""失败原因"""
embedding_code: Optional[int] = None # 失败码 10001:知识不可用,知识库空间已达上限 10002:知识不可用,知识库空间已达上限(字数超出限制)
embedding_msg: Optional[str] = None # 失败原因
class DocumentData(BaseModel):
id: str = None # 知识唯一id
custom_separator: List[str] = None # 切片规则
sentence_size: str = None # 切片大小
length: int = None # 文件大小(字节)
word_num: int = None # 文件字数
name: str = None # 文件名
url: str = None # 文件下载链接
embedding_stat: int = None # 0:向量化中 1:向量化完成 2:向量化失败
failInfo: Optional[DocumentDataFailInfo] = None # 失败原因 向量化失败embedding_stat=2的时候 会有此值
================================================
FILE: zhipuai/types/knowledge/document/document_edit_params.py
================================================
from typing import Optional, List, Literal, TypedDict, Dict
__all__ = ["DocumentEditParams"]
class DocumentEditParams(TypedDict):
"""
知识参数类型定义
Attributes:
id (str): 知识ID
knowledge_type (int): 知识类型:
1:文章知识: 支持pdf,url,docx
2.问答知识-文档: 支持pdf,url,docx
3.问答知识-表格: 支持xlsx
4.商品库-表格: 支持xlsx
5.自定义: 支持pdf,url,docx
custom_separator (Optional[List[str]]): 当前知识类型为自定义(knowledge_type=5)时的切片规则,默认\n
sentence_size (Optional[int]): 当前知识类型为自定义(knowledge_type=5)时的切片字数,取值范围: 20-2000,默认300
callback_url (Optional[str]): 回调地址
callback_header (Optional[dict]): 回调时携带的header
"""
id: str
knowledge_type: int
custom_separator: Optional[List[str]]
sentence_size: Optional[int]
callback_url: Optional[str]
callback_header: Optional[Dict[str, str]]
================================================
FILE: zhipuai/types/knowledge/document/document_list_params.py
================================================
from __future__ import annotations
from typing import Dict, Optional
from typing_extensions import Literal, Required, TypedDict
class DocumentListParams(TypedDict, total=False):
"""
文件查询参数类型定义
Attributes:
purpose (Optional[str]): 文件用途
knowledge_id (Optional[str]): 当文件用途为 retrieval 时,需要提供查询的知识库ID
page (Optional[int]): 页,默认1
limit (Optional[int]): 查询文件列表数,默认10
after (Optional[str]): 查询指定fileID之后的文件列表(当文件用途为 fine-tune 时需要)
order (Optional[str]): 排序规则,可选值['desc', 'asc'],默认desc(当文件用途为 fine-tune 时需要)
"""
purpose: Optional[str]
knowledge_id: Optional[str]
page: Optional[int]
limit: Optional[int]
after: Optional[str]
order: Optional[str]
================================================
FILE: zhipuai/types/knowledge/document/document_list_resp.py
================================================
from __future__ import annotations
from typing import Dict, Optional, List
from . import DocumentData
from ....core import BaseModel
__all__ = [
"DocumentPage"
]
class DocumentPage(BaseModel):
list: List[DocumentData]
object: str
================================================
FILE: zhipuai/types/knowledge/knowledge.py
================================================
from typing import Optional
from ...core import BaseModel
__all__ = ["KnowledgeInfo"]
class KnowledgeInfo(BaseModel):
id: Optional[str] = None
"""知识库唯一 id"""
embedding_id: Optional[str] = None # 知识库绑定的向量化模型 见模型列表 [内部服务开放接口文档](https://lslfd0slxc.feishu.cn/docx/YauWdbBiMopV0FxB7KncPWCEn8f#H15NduiQZo3ugmxnWQFcfAHpnQ4)
name: Optional[str] = None # 知识库名称 100字限制
customer_identifier: Optional[str] = None # 用户标识 长度32位以内
description: Optional[str] = None # 知识库描述 500字限制
background: Optional[str] = None # 背景颜色(给枚举)'blue', 'red', 'orange', 'purple', 'sky'
icon: Optional[str] = None # 知识库图标(给枚举) question: 问号、book: 书籍、seal: 印章、wrench: 扳手、tag: 标签、horn: 喇叭、house: 房子
bucket_id: Optional[str] = None # 桶id 限制32位
================================================
FILE: zhipuai/types/knowledge/knowledge_create_params.py
================================================
from __future__ import annotations
from typing import Dict, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = ["KnowledgeBaseParams"]
class KnowledgeBaseParams(TypedDict):
"""
知识库参数类型定义
Attributes:
embedding_id (int): 知识库绑定的向量化模型ID
name (str): 知识库名称,限制100字
customer_identifier (Optional[str]): 用户标识,长度32位以内
description (Optional[str]): 知识库描述,限制500字
background (Optional[Literal['blue', 'red', 'orange', 'purple', 'sky']]): 背景颜色
icon (Optional[Literal['question', 'book', 'seal', 'wrench', 'tag', 'horn', 'house']]): 知识库图标
bucket_id (Optional[str]): 桶ID,限制32位
"""
embedding_id: int
name: str
customer_identifier: Optional[str]
description: Optional[str]
background: Optional[Literal['blue', 'red', 'orange', 'purple', 'sky']] = None
icon: Optional[Literal['question', 'book', 'seal', 'wrench', 'tag', 'horn', 'house']] = None
bucket_id: Optional[str]
================================================
FILE: zhipuai/types/knowledge/knowledge_list_params.py
================================================
from __future__ import annotations
from typing import Dict, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = ["KnowledgeListParams"]
class KnowledgeListParams(TypedDict, total=False):
page: int = 1
""" 页码,默认 1,第一页
"""
size: int = 10
"""每页数量 默认10
"""
================================================
FILE: zhipuai/types/knowledge/knowledge_list_resp.py
================================================
from __future__ import annotations
from typing import Dict, Optional, List
from . import KnowledgeInfo
from ...core import BaseModel
__all__ = [
"KnowledgePage"
]
class KnowledgePage(BaseModel):
list: List[KnowledgeInfo]
object: str
================================================
FILE: zhipuai/types/knowledge/knowledge_used.py
================================================
from typing import Optional
from ...core import BaseModel
__all__ = [
"KnowledgeStatistics",
"KnowledgeUsed"
]
class KnowledgeStatistics(BaseModel):
"""
使用量统计
"""
word_num: Optional[int] = None
length: Optional[int] = None
class KnowledgeUsed(BaseModel):
used: Optional[KnowledgeStatistics] = None
"""已使用量"""
total: Optional[KnowledgeStatistics] = None
"""知识库总量"""
================================================
FILE: zhipuai/types/moderation/__init__.py
================================================
================================================
FILE: zhipuai/types/moderation/moderation_completion.py
================================================
from typing import List, Optional, Union, Dict
from ...core import BaseModel
__all__ = ["Completion"]
class Completion(BaseModel):
model: Optional[str] = None
input: Optional[Union[str, List[str], Dict]] = None # 新增 input 字段
================================================
FILE: zhipuai/types/sensitive_word_check/__init__.py
================================================
from .sensitive_word_check import SensitiveWordCheckRequest
__all__ = [
"SensitiveWordCheckRequest"
]
================================================
FILE: zhipuai/types/sensitive_word_check/sensitive_word_check.py
================================================
from typing import Optional
from typing_extensions import TypedDict
class SensitiveWordCheckRequest(TypedDict, total=False):
type: Optional[str]
"""敏感词类型,当前仅支持ALL"""
status: Optional[str]
"""敏感词启用禁用状态
启用:ENABLE
禁用:DISABLE
备注:默认开启敏感词校验,如果要关闭敏感词校验,需联系商务获取对应权限,否则敏感词禁用不生效。
"""
================================================
FILE: zhipuai/types/tools/__init__.py
================================================
from .web_search import (
WebSearch,
SearchIntent,
SearchResult,
SearchRecommend,
)
from .web_search_chunk import (
WebSearchChunk
)
__all__ = [
'WebSearch',
'SearchIntent',
'SearchResult',
'SearchRecommend',
'WebSearchChunk'
]
================================================
FILE: zhipuai/types/tools/tools_web_search_params.py
================================================
from __future__ import annotations
from typing import Union, Optional, List
from typing_extensions import Literal, Required, TypedDict
__all__ = ["WebSearchParams"]
class WebSearchParams(TypedDict):
"""
工具名:web-search-pro参数类型定义
Attributes:
:param model: str, 模型名称
:param request_id: Optional[str], 请求ID
:param stream: Optional[bool], 是否流式
:param messages: Union[str, List[str], List[int], object, None],
包含历史对话上下文的内容,按照 {"role": "user", "content": "你好"} 的json 数组形式进行传参
当前版本仅支持 User Message 单轮对话,工具会理解User Message并进行搜索,
请尽可能传入不带指令格式的用户原始提问,以提高搜索准确率。
:param scope: Optional[str], 指定搜索范围,全网、学术等,默认全网
:param location: Optional[str], 指定搜索用户地区 location 提高相关性
:param recent_days: Optional[int],支持指定返回 N 天(1-30)更新的搜索结果
"""
model: str
request_id: Optional[str]
stream: Optional[bool]
messages: Union[str, List[str], List[int], object, None]
scope: Optional[str] = None
location: Optional[str] = None
recent_days: Optional[int] = None
================================================
FILE: zhipuai/types/tools/web_search.py
================================================
from typing import List, Optional
from ..chat.chat_completion import Function
from ...core import BaseModel
__all__ = [
"WebSearch",
"SearchIntent",
"SearchResult",
"SearchRecommend",
]
class SearchIntent(BaseModel):
index: int
# 搜索轮次,默认为 0
query: str
# 搜索优化 query
intent: str
# 判断的意图类型
keywords: str
# 搜索关键词
class SearchResult(BaseModel):
index: int
# 搜索轮次,默认为 0
title: str
# 标题
link: str
# 链接
content: str
# 内容
icon: str
# 图标
media: str
# 来源媒体
refer: str
# 角标序号 [ref_1]
class SearchRecommend(BaseModel):
index: int
# 搜索轮次,默认为 0
query: str
# 推荐query
class WebSearchMessageToolCall(BaseModel):
id: str
search_intent: Optional[SearchIntent]
search_result: Optional[SearchResult]
search_recommend: Optional[SearchRecommend]
type: str
class WebSearchMessage(BaseModel):
role: str
tool_calls: Optional[List[WebSearchMessageToolCall]] = None
class WebSearchChoice(BaseModel):
index: int
finish_reason: str
message: WebSearchMessage
class WebSearch(BaseModel):
created: Optional[int] = None
choices: List[WebSearchChoice]
request_id: Optional[str] = None
id: Optional[str] = None
================================================
FILE: zhipuai/types/tools/web_search_chunk.py
================================================
from typing import List, Optional, Dict, Any
from .web_search import SearchIntent, SearchResult, SearchRecommend
from ...core import BaseModel
__all__ = [
"WebSearchChunk"
]
class ChoiceDeltaToolCall(BaseModel):
index: int
id: Optional[str] = None
search_intent: Optional[SearchIntent] = None
search_result: Optional[SearchResult] = None
search_recommend: Optional[SearchRecommend] = None
type: Optional[str] = None
class ChoiceDelta(BaseModel):
role: Optional[str] = None
tool_calls: Optional[List[ChoiceDeltaToolCall]] = None
class Choice(BaseModel):
delta: ChoiceDelta
finish_reason: Optional[str] = None
index: int
class WebSearchChunk(BaseModel):
id: Optional[str] = None
choices: List[Choice]
created: Optional[int] = None
================================================
FILE: zhipuai/types/video/__init__.py
================================================
from .video_object import (
VideoObject,
VideoResult
)
__all__ = ["VideoObject", "VideoResult"]
================================================
FILE: zhipuai/types/video/video_create_params.py
================================================
from __future__ import annotations
from typing import List, Optional
from typing_extensions import Literal, Required, TypedDict
__all__ = ["VideoCreateParams"]
from ..sensitive_word_check import SensitiveWordCheckRequest
class VideoCreateParams(TypedDict, total=False):
model: str
"""模型编码"""
prompt: str
"""所需视频的文本描述"""
image_url: str
"""所需视频的文本描述"""
sensitive_word_check: Optional[SensitiveWordCheckRequest]
"""支持 URL 或者 Base64、传入 image 奖进行图生视频
* 图片格式:
* 图片大小:"""
request_id: str
"""由用户端传参,需保证唯一性;用于区分每次请求的唯一标识,用户端不传时平台会默认生成。"""
user_id: str
"""用户端。"""
================================================
FILE: zhipuai/types/video/video_object.py
================================================
from typing import Optional, List
from ...core import BaseModel
__all__ = ["VideoObject", "VideoResult"]
class VideoResult(BaseModel):
url: str
"""视频url"""
cover_image_url: str
"""预览图"""
class VideoObject(BaseModel):
id: Optional[str] = None
"""智谱 AI 开放平台生成的任务订单号,调用请求结果接口时请使用此订单号"""
model: str
"""模型名称"""
video_result: List[VideoResult]
"""视频生成结果"""
task_status: str
"""处理状态,PROCESSING(处理中),SUCCESS(成功),FAIL(失败)
注:处理中状态需通过查询获取结果"""
request_id: str
"""用户在客户端请求时提交的任务编号或者平台生成的任务编号"""
================================================
FILE: zhipuai/types/web_search/__init__.py
================================================
from .web_search_create_params import (
WebSearchCreatParams
)
__all__ = ["WebSearchCreatParams"]
================================================
FILE: zhipuai/types/web_search/web_search_create_params.py
================================================
from __future__ import annotations
from typing import Union, Optional, List
from typing_extensions import Literal, Required, TypedDict
from ...types.sensitive_word_check import SensitiveWordCheckRequest
__all__ = ["WebSearchCreatParams"]
class WebSearchCreatParams(TypedDict):
search_engine: str
"""搜索引擎"""
search_query: str
"""搜索query文本"""
request_id: str
"""由用户端传参,需保证唯一性;用于区分每次请求的唯一标识,用户端不传时平台会默认生成。"""
user_id: str
"""用户端。"""
sensitive_word_check: Optional[SensitiveWordCheckRequest]
================================================
FILE: zhipuai/types/web_search/web_search_resp.py
================================================
from typing import List, Optional
from ...core import BaseModel
__all__ = [
"SearchIntentResp",
"SearchResultResp",
]
class SearchIntentResp(BaseModel):
query: str
# 搜索优化 query
intent: str
# 判断的意图类型
keywords: str
# 搜索关键词
class SearchResultResp(BaseModel):
title: str
# 标题
link: str
# 链接
content: str
# 内容
icon: str
# 图标
media: str
# 来源媒体
refer: str
# 角标序号 [ref_1]
publish_date: str
# 发布时间
class WebSearchResp(BaseModel):
created: Optional[int] = None
request_id: Optional[str] = None
id: Optional[str] = None
search_intent: Optional[SearchIntentResp]
search_result: Optional[SearchResultResp]