1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| async def generate_tool_call_chunks( tool_calls: list, answer_id: str, created: int, model: str, system_fingerprint: Optional[str] = None, finish_reason: str = "tool_calls" ): """ 异步生成器,模拟流式发送工具调用数据 Args: tool_calls: 工具调用列表,每个元素应包含: { "id": "call_xxx", "function": { "name": "function_name", "arguments": '{"param1": "value1"}' # JSON字符串 } } answer_id: 回答ID created: 创建时间戳 model: 模型名称 system_fingerprint: 系统指纹 finish_reason: 完成原因,默认为 "tool_calls" """ for idx, tool_call in enumerate(tool_calls): tool_id = tool_call.get("id", f"call_{idx}") function_name = tool_call["function"]["name"] arguments_str = tool_call["function"]["arguments"]
if isinstance(arguments_str, dict): arguments_str = json.dumps(arguments_str, ensure_ascii=False)
chunk_start = { "id": answer_id, "object": "chat.completion.chunk", "created": created, "model": model, "system_fingerprint": system_fingerprint, "choices": [{ "index": 0, "delta": { "tool_calls": [{ "index": idx, "id": tool_id, "type": "function", "function": { "name": function_name, "arguments": "" } }] }, "logprobs": None, "finish_reason": None }] } yield f"data: {json.dumps(chunk_start, ensure_ascii=False)}\n\n" await asyncio.sleep(random.uniform(0.01, 0.03))
for char in arguments_str: chunk_arg = { "id": answer_id, "object": "chat.completion.chunk", "created": created, "model": model, "system_fingerprint": system_fingerprint, "choices": [{ "index": 0, "delta": { "tool_calls": [{ "index": idx, "function": { "arguments": char } }] }, "logprobs": None, "finish_reason": None }] } yield f"data: {json.dumps(chunk_arg, ensure_ascii=False)}\n\n" await asyncio.sleep(random.uniform(0.005, 0.015))
completion_data = { "id": answer_id, "object": "chat.completion.chunk", "created": created, "model": model, "system_fingerprint": system_fingerprint, "choices": [{ "index": 0, "delta": {}, "logprobs": None, "finish_reason": finish_reason }] } yield f"data: {json.dumps(completion_data, ensure_ascii=False)}\n\n"
yield "data: [DONE]\n\n"
|