smartSpeaker/chatglm6b_example.py

81 lines
2.5 KiB
Python
Raw Normal View History

2023-12-22 09:04:16 +00:00
import zhipuai
from zhipuai.model_api import ChatGLM6bParams
#from tts_ws_python3_demo import *
#from tts_ws_python3_demo import Ws_Param
zhipuai.api_key = "404ec324361f90f214fd6828c0750933.rsoTPnAXfKUnty0J"
def invoke_example():
params = ChatGLM6bParams(
prompt=[{"role": "user", "content": "人工智能"}], top_p=0.7, temperature=0.9
)
response = zhipuai.model_api.invoke(**params.asdict())
print(response)
def async_invoke_example():
params = ChatGLM6bParams(
prompt=[{"role": "user", "content": "人工智能"}], top_p=0.7, temperature=0.9
)
response = zhipuai.model_api.async_invoke(**params.asdict())
print(response)
"""
说明
add: 事件流开启
error: 平台服务或者模型异常响应的异常事件
interrupted: 中断事件例如触发敏感词
finish: 数据接收完毕关闭事件流
"""
def sse_invoke_example():
params = ChatGLM6bParams(
prompt=[{"role": "user", "content": "人工智能"}], top_p=0.7, temperature=0.9
)
response = zhipuai.model_api.sse_invoke(**params.asdict())
for event in response.events():
if event.event == "add":
print(event.data)
elif event.event == "error" or event.event == "interrupted":
print(event.data)
elif event.event == "finish":
print(event.data)
print(event.meta)
else:
print(event.data)
def query_async_invoke_result_example():
response = zhipuai.model_api.query_async_invoke_result("your task_id")
print(response)
def gettxt(text):
params = ChatGLM6bParams(
prompt=[{"role": "user", "content": text}], top_p=0.7, temperature=0.9
)
response = zhipuai.model_api.invoke(**params.asdict())
# print(response['data']['choices'][0]['content'])
return (response['data']['choices'][0]['content'])
if __name__ == "__main__":
while 1:
temp = input()
text = gettxt(temp)
text = text.replace('\n', '')
wsParam = Ws_Param(APPID='44385032', APISecret='YWNkNTZhMTkwZWFiZjhjNjU4MDg2MzY4',
APIKey='83f2198f66ed394e7a73deb57c1c1b44',
Text=text)
websocket.enableTrace(False)
wsUrl = wsParam.create_url()
ws = websocket.WebSocketApp(
wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
ws.on_open = on_open
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
file = "demo.mp3"
os.system(file)