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

feat: Add more option to utils to shorten text #1112

Merged
merged 1 commit into from
Sep 20, 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
13 changes: 12 additions & 1 deletion phospho-python/phospho/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from phospho.utils import (
generate_timestamp,
generate_uuid,
shorten_text,
)

# Add other job types here
Expand Down Expand Up @@ -483,6 +484,8 @@ def transcript(
with_previous_messages: bool = False,
only_previous_messages: bool = False,
max_previous_messages: Optional[int] = None,
message_content_max_len: Optional[int] = None,
message_content_shorten_how: Literal["left", "right", "center"] = "left",
) -> str:
"""
Return a string representation of the message.
Expand All @@ -508,7 +511,15 @@ def transcript(
if with_role:
transcript += f"{self.role}: {self.content}"
else:
transcript += "\n" + self.content
if message_content_max_len is not None:
content = shorten_text(
prompt=self.content,
max_length=message_content_max_len,
how=message_content_shorten_how,
)
else:
content = self.content
transcript += "\n" + content
return transcript

def previous_messages_transcript(
Expand Down
13 changes: 10 additions & 3 deletions phospho-python/phospho/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,10 +256,10 @@ def shorten_text(
prompt: Optional[str],
max_length: int,
margin: int = 20,
how: Literal["left", "right"] = "left",
how: Literal["left", "right", "center"] = "left",
) -> str:
"""
Shorten the text to fit in the max_length by only keeping the beginning of the text
Shorten the prompt to fit in the max_length by only keeping some part of the text.
"""
try:
import tiktoken
Expand All @@ -278,7 +278,14 @@ def shorten_text(
else:
if how == "left":
return encoding.decode(tokens[: max_length - margin])
if how == "right":
elif how == "right":
return encoding.decode(tokens[-(max_length - margin) :])
elif how == "center":
# Keep the beginning and the end of the text, with [...] in the middle
return (
encoding.decode(tokens[: (max_length - margin) // 2])
+ " [...] "
+ encoding.decode(tokens[-(max_length - margin) // 2 :])
)
else:
raise ValueError(f"Unknown value for how: {how}")
Loading