celery执行异步任务并调用返回值
@shared_task(queue='tool_invoke')
def tool_invoke_task_queue(type: str, data: Union[bytes, str], path: str = None):
bucket = 'tools'
try:
if type == 'image':
file = download_and_convert_to_filestorage(data)
data = file.read()
logger.info(f"file.name {file.name}")
# path = f"{path}/{file.name}"
MINIO.put(bucket, path, data)
except Exception as e:
raise ValueError('文件上传失败')
url = MINIO.get_public_url(bucket, path)
url = str(URL(os.getenv('OSS_FILE_PRE')) / url.lstrip("/"))
logger.info(f"文件的url为: {url}")
return url
result = tool.invoke(
user_id="",
tool_parameters=tool_parameters
)
if isinstance(result, ToolInvokeMessage):
result = {**result.dict(), 'type': result.type.value}
if result['type'] not in ['text', 'json','link']:
result = ToolInvokeService.format_result(result, oss_base_path)
elif isinstance(result, list):
result = [ToolInvokeService.format_result(
{**r.dict(), 'type': r.type.value},
oss_base_path
) for r in result]
return result, credentials_schema
@staticmethod
def format_result(result: dict, oss_base_path: str) -> dict:
if result['type'] in ['text', 'json','link']:
return result
if result['type'] == 'blob':
path = f"{oss_base_path}{ToolInvokeService.mime_type_to_extension(result['meta']['mime_type'])}"
elif result['type'] == 'image':
path = oss_base_path
async_result=tool_invoke_task_queue.delay(result['type'], result['message'], path)
url = async_result.get()
print("url",url)
result['message'] = url
return result
当直接执行如下代码时
a=tool_invoke_task_queue.delay(a,b)
result['message']=a
会报错:
sqlalchemy.exc.StatementError: (builtins.TypeError) Object of type AsyncResult is not JSON serializable
因此,需要解决异步任务获取返回值
Buy me a cup of coffee ☕.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现