我們可以參考某一個(gè)大模型對(duì)應(yīng)的官方文檔,學(xué)習(xí)如何調(diào)用其API。
智譜AI是清華大學(xué)計(jì)算機(jī)系技術(shù)成果轉(zhuǎn)化而來(lái)的公司,公司產(chǎn)品包括:中英雙語(yǔ)千億級(jí)超大規(guī)模預(yù)訓(xùn)練模型GLM-130B,并基于此推出對(duì)話模型ChatGLM;高效率代碼模型CodeGeeX;多模態(tài)理解模型CogVLM和文生圖模型CogView等。
調(diào)用API首先需要獲取API,每個(gè)用戶需要自己注冊(cè)申請(qǐng)對(duì)應(yīng)的API。進(jìn)入智譜AI官網(wǎng),注冊(cè)后申請(qǐng)API,復(fù)制API_KEY以便后續(xù)調(diào)用:

現(xiàn)在打開(kāi)API調(diào)用參考文檔:通用大模型和圖像大模型,直接復(fù)制其代碼,看看輸出是什么樣的!
同步調(diào)用就是創(chuàng)建一個(gè)調(diào)用任務(wù)后,一直運(yùn)行這個(gè)任務(wù)直到收到大模型的響應(yīng)輸出;對(duì)應(yīng)的是異步調(diào)用,創(chuàng)建調(diào)用任務(wù)后獲得這個(gè)任務(wù)的request-id,之后可以去干其他事情,后續(xù)通過(guò)這個(gè)任務(wù)ID查看模型的輸出。
from zhipuai import ZhipuAI # 先安裝ZhipuAI的包 pip install ZhipuAI
client = ZhipuAI(api_key="xxxx") # 填寫(xiě)您自己的APIKey
response = client.chat.completions.create(
model="glm-4", # 填寫(xiě)需要調(diào)用的模型名稱(chēng)
messages=[
# messages是json格式的數(shù)據(jù),大模型逐條響應(yīng)
{"role": "user", "content": "作為一名營(yíng)銷(xiāo)專(zhuān)家,請(qǐng)為我的產(chǎn)品創(chuàng)作一個(gè)吸引人的slogan"},
{"role": "assistant", "content": "當(dāng)然,為了創(chuàng)作一個(gè)吸引人的slogan,請(qǐng)告訴我一些關(guān)于您產(chǎn)品的信息"},
{"role": "user", "content": "智譜AI開(kāi)放平臺(tái)"},
{"role": "assistant", "content": "智啟未來(lái),譜繪無(wú)限一智譜AI,讓創(chuàng)新觸手可及!"},
{"role": "user", "content": "創(chuàng)造一個(gè)更精準(zhǔn)、吸引人的slogan"}
],
)
# 直接輸出response,查看響應(yīng)的具體內(nèi)容
print(response)
輸出的完整json數(shù)據(jù):

如果只關(guān)注最終輸出的message的content,可以只取response.choices[0].message.content。
上面例子傳入大模型的message列表里面,有user的信息,也有assistant的信息,大模型實(shí)際響應(yīng)的只有user對(duì)應(yīng)的content,但是assistant的內(nèi)容可以為大模型提供一些上下文或者提示。
message只傳入用戶的輸入,并多次問(wèn)答的例子如下:
from zhipuai import ZhipuAI
client = ZhipuAI(api_key="xxxxxx") # 填寫(xiě)您自己的APIKey
# 循環(huán)提問(wèn)/對(duì)話
while True:
# 接收用戶輸入作為問(wèn)題
prompt = input("\nuser:")
response = client.chat.completions.create(
model="glm-4", # 填寫(xiě)需要調(diào)用的模型名稱(chēng)
messages=[
{"role": "user", "content": prompt}
],
)
answer = response.choices[0].message.content
print("\nZhipuAI:",answer) # 只輸出大模型響應(yīng)的message.context
123456789101112131415
結(jié)果:

上述例子雖然user能夠無(wú)限次的與大模型進(jìn)行對(duì)話(交互),但由于message中只有用戶單次的問(wèn)題,沒(méi)有保存上下文的信息,因此如果前后問(wèn)題有銜接,這樣的方式是不行的。應(yīng)該使用多輪對(duì)話,將每輪對(duì)話的問(wèn)答保存在message中,傳給大模型為其提供對(duì)話的上下文。
GLM_4異步調(diào)用
參考官方文檔,異步調(diào)用獲取結(jié)果包括兩步:①獲取模型的響應(yīng)ID,②根據(jù)ID查詢(xún)響應(yīng)結(jié)果;
import time
from zhipuai import ZhipuAI
client = ZhipuAI(api_key="xxxxxx") # 請(qǐng)?zhí)顚?xiě)您自己的APIKey
response = client.chat.asyncCompletions.create(
model="glm-4", # 填寫(xiě)需要調(diào)用的模型名稱(chēng)
messages=[
{
"role": "user",
"content": "請(qǐng)你作為童話故事大王,寫(xiě)一篇短篇童話故事,故事的主題是要永遠(yuǎn)保持一顆善良的心,要能夠激發(fā)兒童的學(xué)習(xí)興趣和想象力,同時(shí)也能夠幫助兒童更好地理解和接受故事中所蘊(yùn)含的道理和價(jià)值觀。"
}
],
)
# 獲取響應(yīng)ID
task_id = response.id
task_status = ''
get_cnt = 0
while task_status != 'SUCCESS' and task_status != 'FAILED' and get_cnt <= 40:
# 查詢(xún)響應(yīng)結(jié)果
result_response = client.chat.asyncCompletions.retrieve_completion_result(id=task_id)
print(result_response)
task_status = result_response.task_status
time.sleep(2)
get_cnt += 1
1234567891011121314151617181920212223242526
運(yùn)行輸出如下:

可以看到在得到大模型的響應(yīng)輸出前,狀態(tài)一直是processing;知道大模型響應(yīng)。
文生圖大模型API調(diào)用
Cogview是文生圖的大模型,直接復(fù)制的官方文檔的代碼:
from zhipuai import ZhipuAI
client = ZhipuAI(api_key="xxxxx") # 請(qǐng)?zhí)顚?xiě)您自己的APIKey
response = client.images.generations(
model="cogview-3", #填寫(xiě)需要調(diào)用的模型名稱(chēng)
prompt="一只可愛(ài)的小貓咪",
)
print(response.data[0].url)
123456789
結(jié)果(0.25一張照片嗚嗚嗚嗚嗚嗚嗚)返回圖片url:https://sfile.chatglm.cn/testpath/b158178b-e00c-5ea0-92bb-f2962922b877\_0.png ??:

通義千問(wèn)是阿里云開(kāi)發(fā)的基于QWen模型的聊天模型,QWen模型是開(kāi)源的。調(diào)用API同樣需要先獲取API_KEY——首先注冊(cè)阿里云的賬號(hào),然后進(jìn)入靈積平臺(tái)創(chuàng)建API-KEY:

之后查看通義千問(wèn)的官方API調(diào)用文檔??快速入門(mén),會(huì)話可以分為單輪會(huì)話和多輪會(huì)話:
單輪會(huì)話
可以通過(guò)message和prompt兩種方式調(diào)用API:
import random
from http import HTTPStatus # 通義千問(wèn)API是通過(guò)HTTP調(diào)用的
import dashscope
dashscope.api_key = 'xxxxx' # 設(shè)置自己申請(qǐng)的API_KEY; 這個(gè)方式設(shè)置有泄露api的可能
def call_with_messages():
prompt = input("user:")
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': prompt}]
response = dashscope.Generation.call(
dashscope.Generation.Models.qwen_turbo, # 選擇模型
messages=messages,
# set the random seed, optional, default to 1234 if not set
seed=random.randint(1, 10000),
result_format='message', # set the result to be "message" format.
)
# 之后HTTPStatus為OK時(shí),才是調(diào)用成功
if response.status_code == HTTPStatus.OK:
print(response)
else:
print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
response.request_id, response.status_code,
response.code, response.message
))
# For prerequisites running the following sample, visit https://help.aliyun.com/document_detail/611472.html
def call_with_prompt():
prompt = input("user:")
response = dashscope.Generation.call(
model=dashscope.Generation.Models.qwen_turbo, # 選擇模型
prompt=prompt
)
# The response status_code is HTTPStatus.OK indicate success,
# otherwise indicate request is failed, you can get error code
# and message from code and message.
if response.status_code == HTTPStatus.OK:
print(response.output) # The output text
print(response.usage) # The usage information
else:
print(response.code) # The error code.
print(response.message) # The error message.
if __name__ == '__main__':
call_with_messages()
print("\n")
call_with_prompt()
兩種方式的單輪會(huì)話輸出如下:

這里需要注意通過(guò)message和prompt調(diào)用,這兩種方式對(duì)應(yīng)的輸出Json格式是不同的。
多輪會(huì)話
通過(guò)messages調(diào)用API,每輪會(huì)話用戶的問(wèn)題(the content of user)和大模型的輸出(content of assistant)會(huì)存儲(chǔ)在messages這個(gè)列表中,之后的輸出會(huì)參考前面的內(nèi)容,體現(xiàn)了大模型的記憶性!(可以在體驗(yàn)中心,選擇多輪會(huì)話,注意觀察代碼中messages的變化):

觀察對(duì)應(yīng)的代碼,每輪會(huì)話結(jié)束后,user的問(wèn)題和模型的響應(yīng)都會(huì)append在messages中:

from http import HTTPStatus
import dashscope
from dashscope import Generation
from dashscope.api_entities.dashscope_response import Role
dashscope.api_key = 'xxxxx' # 設(shè)置API_KEY
def conversation_with_messages():
messages = [{'role': Role.SYSTEM, 'content': 'You are a helpful assistant.'} ]
# 循環(huán)實(shí)現(xiàn)多輪會(huì)話
while True:
prompt = input("USER:")
# 添加新一輪會(huì)話用戶的問(wèn)題
messages.append({'role': Role.USER, 'content': prompt})
response = Generation.call(
Generation.Models.qwen_turbo, #選擇響應(yīng)的模型
messages=messages,
result_format='message', # set the result to be "message" format.
)
if response.status_code == HTTPStatus.OK:
print(response)
# 把模型的輸出添加到messages中
messages.append({'role': response.output.choices[0]['message']['role'],
'content': response.output.choices[0]['message']['content']})
else:
print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
response.request_id, response.status_code,
response.code, response.message
))
exit()
if __name__ == '__main__':
conversation_with_messages()
123456789101112131415161718192021222324252627282930313233
結(jié)果如下:

本文章轉(zhuǎn)載微信公眾號(hào)@佑佑有話說(shuō)