使用python异步执行工作流的步骤有3步:
- 异步执行工作流,获取工作流的execute_id,之后就能根据这个id查询工作流的执行情况
- 如果execute_id=“Success”,就表示工作流执行完毕
- 执行完毕后,打印output,就是大模型最后的全部
示例代码
from loguru import logger
import requests
import json
def run_coze_ai(coze_api_token: str, coze_workflow_id: str, parameter: dict):
"""异步执行扣子AI的工作流
参数:
coze_api_token (str): 扣子API令牌
coze_workflow_id (str): 扣子工作流ID
parameter (dict): 工作流参数
返回:
str: 执行ID
更多参考:
https://www.coze.cn/open/playground/workflow_run
"""
from cozepy import COZE_CN_BASE_URL, Coze, TokenAuth, Message, ChatStatus, MessageContentType # noqa
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=COZE_CN_BASE_URL)
workflow = coze.workflows.runs.create(workflow_id=coze_workflow_id, is_async=True, parameters=parameter)
logger.debug(f"AI工作流执行,执行的ID:{workflow.execute_id}")
return workflow.execute_id
def run_coze_workflow_history(coze_api_token: str, coze_workflow_id: str, coze_history_id: str):
"""查看扣子执行结果
参数:
coze_api_token (str): 扣子API令牌
coze_workflow_id (str): 扣子工作流ID
coze_history_id (str): 执行ID
返回:
dict: 执行结果
更多参考:
https://www.coze.cn/open/playground/workflow_run_history
"""
url = f"https://api.coze.cn/v1/workflows/{coze_workflow_id}/run_histories/{coze_history_id}"
headers = {"Authorization": f"Bearer {coze_api_token}", "Content-Type": "application/json"}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # 检查HTTP错误状态
response_data = response.json().get("data", [None])[0]
return response_data
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
return None
def main():
coze_api_token = 'patxxxxxxxx'
coze_workflow_id = '752xxxxxx'
parameter = {"工作流输入变量名": "工作流输入变量值"} # 启动工作流的初始输入
# 异步执行
execute_id = run_coze_ai(coze_api_token=coze_api_token, coze_workflow_id=coze_workflow_id,parameter=parameter) # 异步执行的id
execute_status = run_coze_workflow_history(coze_api_token, coze_workflow_id, execute_id)
if execute_status['execute_status'] == "Running": # 运行中
logger.debug(f"coze ai {execute_id} is running")
elif execute_status['execute_status'] == "Success": # 成功
logger.debug(f"coze ai {execute_id} is success")
ai_output_data = json.loads(json.loads(execute_status['output'])['Output'])
print(f"AI的输出是:\n{ai_output_data}")
elif execute_status['execute_status'] == "Fail": # 失败
logger.warning(f"coze ai {execute_id} is fail")
if __name__ == '__main__':
main()
1035

被折叠的 条评论
为什么被折叠?



