#!/usr/bin/env python3 # -*- coding: utf-8 -*- """专题四 · 步骤 6:Agent 公开 API streaming 模式验收(无 event: error)。""" from __future__ import annotations import json import sys import _bootstrap # noqa: F401 import _config as C from dify_api import Dify def main() -> int: d = Dify(C.DIFY_EMAIL, C.DIFY_PASSWORD) try: d.login() body = { "inputs": {}, "query": C.AGENT_TEST_QUERY, "response_mode": "streaming", "user": "debug-workbuddy", } remote = "/tmp/agent_stream_test.json" with d.sftp.open(remote, "w") as f: f.write(json.dumps(body, ensure_ascii=False)) cmd = ( "curl -s -N -m 420 -X POST %s/v1/chat-messages " "-H 'Authorization: Bearer %s' " "-H 'Content-Type: application/json' " "-d @%s" % (C.DIFY_BASE, C.APP_API_KEY, remote) ) out, err = d.sh(cmd, t=450) text = out or err print(text[-2000:] if len(text) > 2000 else text) if "event: error" in text: print("\n[FAIL] 流式响应含 event: error") return 1 if "agent_message" in text or "message" in text: print("\n[OK] 流式响应正常") return 0 print("\n[WARN] 未检测到 agent_message,请人工核对上方输出") return 1 finally: d.close() if __name__ == "__main__": sys.exit(main())