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

refactor: avoid downloading tokenizer if truncate is False #1152

Merged
merged 2 commits into from
Oct 23, 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
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,16 @@ def resolve_secret(secret: Optional[Secret]) -> Optional[str]:
# We pop the model_max_length as it is not sent to the model but used to truncate the prompt if needed
model_max_length = kwargs.get("model_max_length", 4096)

# Truncate prompt if prompt tokens > model_max_length-max_length
# (max_length is the length of the generated text)
# we use GPT2 tokenizer which will likely provide good token count approximation

self.prompt_handler = DefaultPromptHandler(
tokenizer="gpt2",
model_max_length=model_max_length,
max_length=self.max_length or 100,
)
# we initialize the prompt handler only if truncate is True: we avoid unnecessarily downloading the tokenizer
if self.truncate:
# Truncate prompt if prompt tokens > model_max_length-max_length
# (max_length is the length of the generated text)
# we use GPT2 tokenizer which will likely provide good token count approximation
self.prompt_handler = DefaultPromptHandler(
tokenizer="gpt2",
model_max_length=model_max_length,
max_length=self.max_length or 100,
)

model_adapter_cls = self.get_model_adapter(model=model)
if not model_adapter_cls:
Expand Down
8 changes: 8 additions & 0 deletions integrations/amazon_bedrock/tests/test_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ def test_constructor_prompt_handler_initialized(mock_boto3_session, mock_prompt_
assert layer.prompt_handler.model_max_length == 4096


def test_prompt_handler_absent_when_truncate_false(mock_boto3_session):
"""
Test that the prompt_handler is not initialized when truncate is set to False.
"""
generator = AmazonBedrockGenerator(model="anthropic.claude-v2", truncate=False)
assert not hasattr(generator, "prompt_handler")


def test_constructor_with_model_kwargs(mock_boto3_session):
"""
Test that model_kwargs are correctly set in the constructor
Expand Down