xiaozhi-agent / pylmkit

PyLMKit: 帮助用户快速构建实用的大模型应用
https://www.yuque.com/txhy/pylmkit
Apache License 2.0
36 stars 4 forks source link

AttributeError: module 'zhipuai' has no attribute 'model_api' #3

Closed alaisgood closed 7 months ago

alaisgood commented 7 months ago

参考官方文档,zhipuai 的api调用已改为client.chat.completions.create 因此将相关代码改成如下形式后才能正常运行,请参考是否有必要更新。

_zhipu.py

import os

import zhipuai

from zhipuai import ZhipuAI

class ChatZhipu(object): def init(self, zhipu_apikey="", model="chatglm_turbo", temperature=0.95, top_p=0.7, incremental=True):

zhipuai.api_key = os.environ.get("zhipu_apikey", zhipu_apikey)

    #self.model = model
    self.zhipu_apikey=os.environ.get("zhipu_apikey", zhipu_apikey)
    self.model = "glm-4"
    self.temperature = temperature
    self.top_p = top_p
    self.incremental = incremental
    self.client = ZhipuAI(api_key=self.zhipu_apikey) 

def invoke(self, query, **kwargs):
    response = self.client.chat.completions.create(
        messages=[{"role": "user", "content": query}],
        model=self.model,
        temperature=self.temperature,
        top_p=self.top_p,
        #incremental=self.incremental,
        **kwargs
    )
    return response.choices[0].message

def stream(self, query, **kwargs):
    response = self.client.chat.completions.create(
        messages=[{"role": "user", "content": query}],
        model=self.model,
        temperature=self.temperature,
        top_p=self.top_p,
        #incremental=self.incremental,
        stream=True,
        **kwargs
    )
    '''
      说明:
      add: 事件流开启
      error: 平台服务或者模型异常,响应的异常事件
      interrupted: 中断事件,例如:触发敏感词
      finish: 数据接收完毕,关闭事件流
    '''
    for event in response.events():
        if event.event == "add":
            yield event.data
        elif event.event == "error" or event.event == "interrupted":
            yield event.data
        elif event.event == "finish":
            yield event.data
            yield event.meta
        else:
            yield event.data
xiaozhi-agent commented 7 months ago

666,已经更新,支持zhipuai新版本,请更新pylmkit==0.0.20

pip install pylmkit -U

智谱AI调用接口不变,调用样例如下:

import os
from pylmkit.llms import ChatZhipu

os.environ['zhipu_apikey'] = ""

# 智谱AI
model = ChatZhipu()
res = model.invoke("如何学习python")  # 普通模式
print(res)

res = model.stream("如何学习python")  # 流式
print(res)
for i in res:
    print(i)