{"id":18983801,"url":"https://github.com/metaglm/zhipuai-sdk-python-v4","last_synced_at":"2025-04-10T20:03:54.927Z","repository":{"id":218638204,"uuid":"746973869","full_name":"MetaGLM/zhipuai-sdk-python-v4","owner":"MetaGLM","description":null,"archived":false,"fork":false,"pushed_at":"2025-04-10T03:53:35.000Z","size":700,"stargazers_count":182,"open_issues_count":11,"forks_count":22,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-04-10T04:38:07.938Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MetaGLM.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-01-23T02:16:10.000Z","updated_at":"2025-04-10T03:53:38.000Z","dependencies_parsed_at":"2024-01-23T04:06:25.600Z","dependency_job_id":"d966f9e4-990f-4352-ac39-7a6f0020203a","html_url":"https://github.com/MetaGLM/zhipuai-sdk-python-v4","commit_stats":null,"previous_names":["zhipuai/zhipuai-sdk-python-v4","metaglm/zhipuai-sdk-python-v4"],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MetaGLM%2Fzhipuai-sdk-python-v4","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MetaGLM%2Fzhipuai-sdk-python-v4/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MetaGLM%2Fzhipuai-sdk-python-v4/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MetaGLM%2Fzhipuai-sdk-python-v4/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MetaGLM","download_url":"https://codeload.github.com/MetaGLM/zhipuai-sdk-python-v4/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248287830,"owners_count":21078792,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-08T16:18:35.308Z","updated_at":"2025-04-10T20:03:54.903Z","avatar_url":"https://github.com/MetaGLM.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 智谱大模型开放接口SDK\n\n[![PyPI version](https://img.shields.io/pypi/v/zhipuai.svg)](https://pypi.org/project/zhipuai/)\n\n智谱[开放平台](https://open.bigmodel.cn/dev/api)大模型接口 Python SDK（Big Model API SDK in Python），让开发者更便捷的调用智谱开放API\n\n\n## 简介\n- 对所有接口进行了类型封装。\n- 初始化client并调用成员函数，无需关注http调用过程的各种细节，所见即所得。\n- 默认缓存token。\n\n## 安装\n\n\n### Python版本支持\n正式的 Python (3.8, 3.9, 3.10, 3.11, 3.12)\n\n### 使用 pip 安装 `zhipuai` 软件包及其依赖\n\n```sh\npip install zhipuai\n```\n\n## 使用\n\n- 调用流程：\n    1. 使用 APISecretKey 创建 Client\n    2. 调用 Client 对应的成员方法\n- 开放平台[接口文档](https://open.bigmodel.cn/dev/api)以及[使用指南](https://open.bigmodel.cn/dev/howuse/)中有更多的 demo 示例，请在 demo 中使用自己的 ApiKey 进行测试。\n\n### 创建Client\nsdk支持通过环境变量配置APIKey\n- env\n\n`ZHIPUAI_API_KEY`: 您的APIKey\n\n`ZHIPUAI_BASE_URL`: 您的API地址\n\n- 也支持通过代码传入APIKey\n```python\nfrom zhipuai import ZhipuAI\n\nclient = ZhipuAI(\n    api_key=\"\", # 填写您的 APIKey\n) \n```\n### 客户端网络链接配置\n在`core/_http_client.py`中，可以配置网络链接的超时时间，重试次数，限制等参数\n```python\n# 通过 `Timeout` 控制接口`connect` 和 `read` 超时时间，默认为`timeout=300.0, connect=8.0`\nZHIPUAI_DEFAULT_TIMEOUT = httpx.Timeout(timeout=300.0, connect=8.0)\n# 通过 `retry` 参数控制重试次数，默认为3次\nZHIPUAI_DEFAULT_MAX_RETRIES = 3\n# 通过 `Limits` 控制最大连接数和保持连接数，默认为`max_connections=50, max_keepalive_connections=10`\nZHIPUAI_DEFAULT_LIMITS = httpx.Limits(max_connections=50, max_keepalive_connections=10)\n \n```\n同样在`ZhipuAI`入参中可以配置\n```python\nclient = ZhipuAI(\n    timeout= httpx.Timeout(timeout=300.0, connect=8.0),\n    max_retries=3,\n)\n```\n\n\n### 同步调用\n\n```python\nfrom zhipuai import ZhipuAI \n \nclient = ZhipuAI()  # 填写您自己的APIKey\nresponse = client.chat.completions.create(\n  model=\"glm-4\",  # 填写需要调用的模型名称\n  messages=[\n    {\"role\": \"user\", \"content\": \"作为一名营销专家，请为我的产品创作一个吸引人的slogan\"},\n    {\"role\": \"assistant\", \"content\": \"当然，为了创作一个吸引人的slogan，请告诉我一些关于您产品的信息\"},\n    {\"role\": \"user\", \"content\": \"智谱AI开放平台\"},\n    {\"role\": \"assistant\", \"content\": \"智启未来，谱绘无限一智谱AI，让创新触手可及!\"},\n    {\"role\": \"user\", \"content\": \"创造一个更精准、吸引人的slogan\"}\n  ],\n  tools=[\n    {\n      \"type\": \"web_search\",\n      \"web_search\": {\n        \"search_query\": \"帮我看看清华的升学率\",\n        \"search_result\": True,\n      }\n    }\n  ],\n  # 拓展参数\n  extra_body={\"temperature\": 0.5, \"max_tokens\": 50},\n)\nprint(response) \n```\n\n### SSE 调用\n\n```python\nfrom zhipuai import ZhipuAI\nclient = ZhipuAI(api_key=\"\") # 请填写您自己的APIKey\nresponse = client.chat.completions.create(\n    model=\"\",  # 填写需要调用的模型名称\n    messages=[\n        {\"role\": \"system\", \"content\": \"你是一个人工智能助手，你叫叫chatGLM\"},\n        {\"role\": \"user\", \"content\": \"你好！你叫什么名字\"},\n    ],\n    stream=True,\n)\nfor chunk in response:\n    print(chunk.choices[0].delta)\n```\n\n### 多模态\n```python\n\n\n# Function to encode the image\ndef encode_image(image_path):\n    import base64\n    with open(image_path, \"rb\") as image_file:\n        return base64.b64encode(image_file.read()).decode('utf-8')\n\n\ndef test_completions_vis():\n  client = ZhipuAI()  # 填写您自己的APIKey\n  base64_image  = encode_image(\"img/MetaGLM.png\")\n  response = client.chat.completions.create(\n    model=\"glm-4v\",  # 填写需要调用的模型名称\n    extra_body={\"temperature\": 0.5, \"max_tokens\": 50},\n    messages=[\n      {\n        \"role\": \"user\",\n        \"content\": [\n          {\n            \"type\": \"text\",\n            \"text\": \"图里有什么\"\n          },\n\n          # {\n          #     \"type\": \"image_url\",\n          #     \"image_url\": {\n          #         \"url\": \"https://img1.baidu.com/it/u=1369931113,3388870256\u0026fm=253\u0026app=138\u0026size=w931\u0026n=0\u0026f=JPEG\u0026fmt=auto?sec=1703696400\u0026t=f3028c7a1dca43a080aeb8239f09cc2f\"\n          #     }\n          # },\n          {\n            \"type\": \"image_url\",\n            \"image_url\": {\n              \"url\": f\"data:image/jpeg;base64,{base64_image}\"\n            }\n          }\n        ]\n      }\n    ]\n  )\n  print(response)\n\ntest_completions_vis()\n```\n\n### 角色扮演\n\u003e 提供能力的模型名称，请从官网获取\n```python\n\ndef test_completions_charglm():\n    client = ZhipuAI()  # 请填写您自己的APIKey\n    response = client.chat.completions.create(\n        model=\"charglm-3\",  # 填写需要调用的模型名称\n        messages=[\n            {\n                \"role\": \"user\",\n                \"content\": \"请问你在做什么\"\n            }\n        ],\n        meta={\n          \"user_info\": \"我是陆星辰，是一个男性，是一位知名导演，也是苏梦远的合作导演。我擅长拍摄音乐题材的电影。苏梦远对我的态度是尊敬的，并视我为良师益友。\",\n          \"bot_info\": \"苏梦远，本名苏远心，是一位当红的国内女歌手及演员。在参加选秀节目后，凭借独特的嗓音及出众的舞台魅力迅速成名，进入娱乐圈。她外表美丽动人，但真正的魅力在于她的才华和勤奋。苏梦远是音乐学院毕业的优秀生，善于创作，拥有多首热门原创歌曲。除了音乐方面的成就，她还热衷于慈善事业，积极参加公益活动，用实际行动传递正能量。在工作中，她对待工作非常敬业，拍戏时总是全身心投入角色，赢得了业内人士的赞誉和粉丝的喜爱。虽然在娱乐圈，但她始终保持低调、谦逊的态度，深得同行尊重。在表达时，苏梦远喜欢使用“我们”和“一起”，强调团队精神。\",\n          \"bot_name\": \"苏梦远\",\n          \"user_name\": \"陆星辰\"\n        },\n    )\n    print(response)\ntest_completions_charglm()\n```\n\n\n### 智能体 \n```python\n\ndef test_assistant() -\u003e None: \n  client = ZhipuAI()  # 填写您自己的APIKey\n \n\n  generate = client.assistant.conversation(\n    assistant_id=\"659e54b1b8006379b4b2abd6\",\n    model=\"glm-4-assistant\",\n    messages=[\n      {\n        \"role\": \"user\",\n        \"content\": [{\n          \"type\": \"text\",\n          \"text\": \"帮我搜索下智谱的cogvideox发布时间\"\n        }]\n      }\n    ],\n    stream=True,\n    attachments=None,\n    metadata=None,\n    request_id=\"request_1790291013237211136\",\n    user_id=\"12345678\"\n  )\n  for assistant in generate:\n    print(assistant)\n\ntest_assistant()\n```\n\n### 视频生成 \n```python\n\n\ndef test_videos(): \n  client = ZhipuAI()  # 填写您自己的APIKey\n  try:\n    response = client.videos.generations(\n      model=\"cogvideo\",\n      prompt=\"一个开船的人\",\n\n      user_id=\"1212222\"\n    )\n    print(response)\n    \ntest_videos()\n```\n\n\n\n### 异常处理\n\n模块定义了一些统一的参数返回(例如:响应错误，网络超时错误)\n\n业务定义了http错误的响应类 (在接口返回，40x或者50x), 会抛出 `zhipuai.APIStatusError`  ,包含 `status_code` 和 `response` 属性. 它们都是继承 `zhipuai.APIStatusError`.\n其它Exception，属于不可预知的错误\n```python\nfrom zhipuai import ZhipuAI\nimport zhipuai\nclient = ZhipuAI()  # 填写您自己的APIKey\ntry:\n  response = client.chat.completions.create(\n    model=\"glm-4\",  # 填写需要调用的模型名称\n    messages=[\n      {\"role\": \"user\", \"content\": \"作为一名营销专家，请为我的产品创作一个吸引人的slogan\"},\n      {\"role\": \"assistant\", \"content\": \"当然，为了创作一个吸引人的slogan，请告诉我一些关于您产品的信息\"},\n      {\"role\": \"user\", \"content\": \"智谱AI开放平台\"},\n      {\"role\": \"assistant\", \"content\": \"智启未来，谱绘无限一智谱AI，让创新触手可及!\"},\n      {\"role\": \"user\", \"content\": \"创造一个更精准、吸引人的slogan\"}\n    ]\n  )\n  print(response)\n \nexcept zhipuai.APIStatusError as err:\n  print(err) \nexcept zhipuai.APITimeoutError as err:\n  print(err) \n```\n\nError codes are as followed:\n\n| Status Code | Error Type                 |\n|-------------| -------------------------- |\n| 400         | `APIRequestFailedError`          |\n| 401         | `APIAuthenticationError`      |\n| 429         | `APIReachLimitError`           |\n| 500         | `APIInternalError`      |\n| 503         | `APIServerFlowExceedError`      |\n| N/A         | `APIStatusError`       |\n\n\n\n### 更新日志\n\n`2024-8-12`  \n- 修改视频提示词可选,增加文件删除\n- Assistant业务\n- embedding 3 fix dimensions\n  \n`2024-7-25`  \n- cogvideo 修复\n  \n`2024-7-12` \n- 高级搜索工具 Web search 业务 \n- specified Python versions (3.8, 3.9, 3.10, 3.11, 3.12) \n- cogvideo 业务集成\n  \n`2024-5-20` \n- 一些 `python3.12` 的依赖问题， \n- 增加分页处理代码，重写部分相应类的实例化规则\n- 增加类型转换校验\n- 批处理任务相关api \n- 文件流响应包装器   \n\n`2024-4-29` \n- 一些 `python3.7` 的代码适配问题， \n- 接口失败重试机制，通过 `retry` 参数控制重试次数，默认为3次\n- 接口超时策略调整，通过 `Timeout` 控制接口`connect` 和 `read` 超时时间，默认为`timeout=300.0, connect=8.0`\n- 对话模块增加超拟人大模型参数支持，`model=\"charglm-3\"`, `meta`参数支持\n  \n`2024-4-23` \n- 一些兼容 `pydantic\u003c3,\u003e=1.9.0 ` 的代码，\n- 报文处理的业务请求参数和响应参数可通过配置扩充\n- 兼容了一些参数 `top_p:1`,`temperture:0`(do_sample重写false，参数top_p temperture不生效)\n- 图像理解部分，  image_url参数base64内容包含 `data:image/jpeg;base64`兼容\n- 删除jwt认证逻辑\n  \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmetaglm%2Fzhipuai-sdk-python-v4","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmetaglm%2Fzhipuai-sdk-python-v4","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmetaglm%2Fzhipuai-sdk-python-v4/lists"}