Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PY] fix: Optimizing the to_string Function #2107

Merged
merged 3 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions python/packages/ai/teams/utils/to_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,25 @@ def to_string(tokenizer: Tokenizer, value: Any, as_json: bool = False) -> str:
tokenizer (Tokenizer): The tokenizer object used for encoding.
value (Any): The value to be converted.
as_json (bool, optional): Flag indicating whether to return the value as JSON string.
Defaults to False.
Defaults to False.

Returns:
str: The string representation of the value.
"""
if value is None:
return ""

if hasattr(value, "isoformat") and callable(value.isoformat):
# Used when the value is a datetime object
return value.isoformat()
value = todict(value)

if as_json:
return json.dumps(value, default=lambda o: o.__dict__)
return json.dumps(value, default=lambda o: o.__dict__, ensure_ascii=False)

# Return shorter version of object
yaml_str = yaml.dump(value)
json_str = json.dumps(value, default=lambda o: o.__dict__)
yaml_str = yaml.dump(value, allow_unicode=True)
json_str = json.dumps(value, default=lambda o: o.__dict__, ensure_ascii=False)
if len(tokenizer.encode(yaml_str)) < len(tokenizer.encode(json_str)):
return yaml_str

Expand Down
3 changes: 3 additions & 0 deletions python/packages/ai/tests/utils/test_to_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,6 @@ def test_to_string_with_object(self):
def test_to_string_with_object_as_json(self):
obj = {"key": "value", "key2": [1, 2, 3]}
self.assertEqual(to_string(self.tokenizer, obj, as_json=True), json.dumps(obj))

def test_to_string_with_nonen_string(self):
self.assertEqual(to_string(self.tokenizer, "非英文"), '"非英文"')
Loading