Revert: broken agent completion by #9631 (#9760)

### What problem does this PR solve?

Revert broken agent completion by #9631.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
This commit is contained in:
Yongteng Lei
2025-08-27 17:16:55 +08:00
committed by GitHub
parent 986b9cbb1a
commit 6cb3e08381
2 changed files with 71 additions and 73 deletions

View File

@ -135,24 +135,6 @@ class UserCanvasService(CommonService):
return True
def structure_answer(conv, ans, message_id, session_id):
if not conv:
return ans
content = ""
if ans["event"] == "message":
if ans["data"].get("start_to_think") is True:
content = "<think>"
elif ans["data"].get("end_to_think") is True:
content = "</think>"
else:
content = ans["data"]["content"]
reference = ans["data"].get("reference")
result = {"id": message_id, "session_id": session_id, "answer": content}
if reference:
result["reference"] = [reference]
return result
def completion(tenant_id, agent_id, session_id=None, **kwargs):
query = kwargs.get("query", "") or kwargs.get("question", "")
files = kwargs.get("files", [])
@ -196,14 +178,13 @@ def completion(tenant_id, agent_id, session_id=None, **kwargs):
})
txt = ""
for ans in canvas.run(query=query, files=files, user_id=user_id, inputs=inputs):
ans = structure_answer(conv, ans, message_id, session_id)
txt += ans["answer"]
if ans.get("answer") or ans.get("reference"):
yield "data:" + json.dumps({"code": 0, "data": ans},
ensure_ascii=False) + "\n\n"
ans["session_id"] = session_id
if ans["event"] == "message":
txt += ans["data"]["content"]
yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n"
conv.message.append({"role": "assistant", "content": txt, "created_at": time.time(), "id": message_id})
conv.reference.append(canvas.get_reference())
conv.reference = canvas.get_reference()
conv.errors = canvas.error
conv.dsl = str(canvas)
conv = conv.to_dict()
@ -232,9 +213,9 @@ def completionOpenAI(tenant_id, agent_id, question, session_id=None, stream=True
except Exception as e:
logging.exception(f"Agent OpenAI-Compatible completionOpenAI parse answer failed: {e}")
continue
if not ans["data"]["answer"]:
if ans.get("event") != "message" or not ans.get("data", {}).get("reference", None):
continue
content_piece = ans["data"]["answer"]
content_piece = ans["data"]["content"]
completion_tokens += len(tiktokenenc.encode(content_piece))
yield "data: " + json.dumps(
@ -279,9 +260,9 @@ def completionOpenAI(tenant_id, agent_id, question, session_id=None, stream=True
):
if isinstance(ans, str):
ans = json.loads(ans[5:])
if not ans["data"]["answer"]:
if ans.get("event") != "message" or not ans.get("data", {}).get("reference", None):
continue
all_content += ans["data"]["answer"]
all_content += ans["data"]["content"]
completion_tokens = len(tiktokenenc.encode(all_content))