Skip to content

Commit b1ae757

Browse files
committed
fix baggage escape
enhance input tool_calls obtain update
1 parent 05487b3 commit b1ae757

File tree

7 files changed

+45
-19
lines changed

7 files changed

+45
-19
lines changed

CHANGLOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
## [0.1.19] - 2025-11-10
2+
### Fixed
3+
- fix baggage escape problem
4+
- enhance input tool_calls obtain
5+
16
## [0.1.18] - 2025-10-10
27
### Added
38
- fix prompt syntax error, use Union instead of |

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ The CozeLoop SDK is a Python client for interacting with [CozeLoop platform](htt
77
Key features:
88
- Report trace
99
- Get and format prompt
10+
- Execute Prompt as a Service (PTaaS)
1011

1112
## Requirements
1213
- Python 3.8 or higher

README.zh_CN.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ CozeLoop SDK 是一个用于与 [CozeLoop 平台](https://loop.coze.cn) 进行
77
主要功能:
88
- Trace上报
99
- Prompt拉取
10+
- 执行Prompt as a Service (PTaaS)
1011

1112
## 要求
1213
- Python 3.8 或更高版本

cozeloop/integration/langchain/trace_model/llm_model.py

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import time
66
from typing import List, Optional, Union, Dict, Any
77
from pydantic.dataclasses import dataclass
8-
from langchain_core.messages import BaseMessage, ToolMessage, AIMessageChunk
8+
from langchain_core.messages import BaseMessage, ToolMessage, AIMessageChunk, AIMessage
99
from langchain_core.outputs import Generation, ChatGeneration
1010

1111

@@ -122,11 +122,30 @@ def __init__(self, messages: List[Union[BaseMessage, List[BaseMessage]]], invoca
122122
elif isinstance(inner_messages, List):
123123
for message in inner_messages:
124124
process_messages.append(message)
125+
126+
tool_call_id_name_map = {}
127+
for message in process_messages:
128+
if isinstance(message, (AIMessageChunk, AIMessage)):
129+
for tool_call in message.additional_kwargs.get('tool_calls', []):
130+
if tool_call.get('id', ''):
131+
tool_call_id_name_map[tool_call.get('id', '')] = tool_call.get('function', {}).get('name', '')
132+
for tool_call in message.tool_calls:
133+
if tool_call.get('id', ''):
134+
tool_call_id_name_map[tool_call.get('id', '')] = tool_call.get('name', '')
135+
125136
for message in process_messages:
126-
if isinstance(message, AIMessageChunk):
127-
self._messages.append(Message(role=message.type, content=message.content, tool_calls=convert_tool_calls(message.additional_kwargs.get('tool_calls', []))))
137+
if isinstance(message, (AIMessageChunk, AIMessage)):
138+
tool_calls = convert_tool_calls_by_additional_kwargs(message.additional_kwargs.get('tool_calls', []))
139+
if len(tool_calls) == 0:
140+
tool_calls = convert_tool_calls_by_raw(message.tool_calls)
141+
self._messages.append(Message(role=message.type, content=message.content, tool_calls=tool_calls))
128142
elif isinstance(message, ToolMessage):
129-
tool_call = ToolCall(id=message.tool_call_id, type=message.type, function= ToolFunction(name=message.additional_kwargs.get('name', '')))
143+
name = ''
144+
if tool_call_id_name_map.get(message.tool_call_id, None) is not None:
145+
name = tool_call_id_name_map[message.tool_call_id]
146+
if message.additional_kwargs.get('name', ''):
147+
name = message.additional_kwargs.get('name', '')
148+
tool_call = ToolCall(id=message.tool_call_id, type=message.type, function=ToolFunction(name=name))
130149
self._messages.append(Message(role=message.type, content=message.content, tool_calls=[tool_call]))
131150
else:
132151
self._messages.append(Message(role=message.type, content=message.content))
@@ -161,7 +180,7 @@ def to_json(self):
161180
for i, generation in enumerate(self.generations):
162181
choice: Choice = None
163182
if isinstance(generation, ChatGeneration):
164-
tool_calls = convert_tool_calls(generation.message.additional_kwargs.get('tool_calls', []))
183+
tool_calls = convert_tool_calls_by_additional_kwargs(generation.message.additional_kwargs.get('tool_calls', []))
165184
if len(tool_calls) == 0 and 'function_call' in generation.message.additional_kwargs:
166185
function_call = generation.message.additional_kwargs.get('function_call', {})
167186
function = ToolFunction(name=function_call.get('name', ''), arguments=json.loads(function_call.get('arguments', {})))
@@ -178,9 +197,17 @@ def to_json(self):
178197
ensure_ascii=False)
179198

180199

181-
def convert_tool_calls(tool_calls: list) -> List[ToolCall]:
200+
def convert_tool_calls_by_raw(tool_calls: list) -> List[ToolCall]:
201+
format_tool_calls: List[ToolCall] = []
202+
for tool_call in tool_calls:
203+
function = ToolFunction(name=tool_call.get('name', ''), arguments=tool_call.get('args', {}))
204+
format_tool_calls.append(ToolCall(id=tool_call.get('id', ''), type=tool_call.get('type', ''), function=function))
205+
return format_tool_calls
206+
207+
208+
def convert_tool_calls_by_additional_kwargs(tool_calls: list) -> List[ToolCall]:
182209
format_tool_calls: List[ToolCall] = []
183210
for tool_call in tool_calls:
184-
function = ToolFunction(name=tool_call.get('function', {}).get('name', ''), arguments=json.loads(tool_call.get('function', {}).get('arguments', {})))
211+
function = ToolFunction(name=tool_call.get('function', {}).get('name', ''), arguments=json.loads(tool_call.get('function', {}).get('arguments', '{}')))
185212
format_tool_calls.append(ToolCall(id=tool_call.get('id', ''), type=tool_call.get('type', ''), function=function))
186213
return format_tool_calls

cozeloop/internal/trace/span.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -456,26 +456,18 @@ def set_multi_modality_map(self, key: str):
456456
self.multi_modality_key_map[key] = True
457457

458458
def set_baggage(self, baggage_item: Dict[str, str]):
459-
if not baggage_item:
460-
return
461-
self.set_baggage_escape(baggage_item, True)
462-
463-
def set_baggage_escape(self, baggage_item: Dict[str, str], escape: bool):
464459
if not baggage_item:
465460
return
466461
try:
467462
for key, value in baggage_item.items():
468463
if self.is_valid_baggage_item(key, value):
469464
self.set_tags({key: value})
470-
if escape:
471-
key = urllib.parse.quote(key)
472-
value = urllib.parse.quote(value)
473465
self.set_baggage_item(key, value)
474466
else:
475467
logger.error(f"[trace] invalid baggageItem:{key}:{value}")
476468
pass
477469
except Exception as e:
478-
logger.error(f"Failed to set_baggage_escape: {e}")
470+
logger.error(f"Failed to set_baggage: {e}")
479471

480472
def is_valid_baggage_item(self, key: str, value: str) -> bool:
481473
key_limit = get_tag_key_size_limit()
@@ -565,7 +557,7 @@ def to_header(self) -> Dict[str, str]:
565557
def to_header_baggage(self) -> str:
566558
if not self.baggage:
567559
return ""
568-
return ",".join(f"{k}={v}" for k, v in self.baggage().items() if k and v)
560+
return ",".join(f"{urllib.parse.quote(k)}={urllib.parse.quote(v)}" for k, v in self.baggage().items() if k and v)
569561

570562
def to_header_parent(self) -> str:
571563
return f"{GLOBAL_TRACE_VERSION:02x}-{self.trace_id}-{self.span_id}-{self.flags:02x}"

cozeloop/internal/trace/trace.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def _start_span(self,
145145
tag_truncate_conf=self.tag_truncate_conf,
146146
)
147147

148-
span.set_baggage_escape(baggage, False)
148+
span.set_baggage(baggage)
149149
return span
150150

151151
def flush(self):

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "cozeloop"
3-
version = "0.1.18"
3+
version = "0.1.19"
44
description = "coze loop sdk"
55
authors = ["JiangQi715 <[email protected]>"]
66
license = "MIT"

0 commit comments

Comments
 (0)