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

Fill the prompt with as much messages as possible #21

Merged
merged 1 commit into from
Dec 19, 2024
Merged
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
28 changes: 22 additions & 6 deletions libertai_agents/libertai_agents/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,37 @@
)
raw_messages = [x.model_dump() for x in messages]

for i in range(len(raw_messages)):
prompt = (
self.tokenizer.apply_chat_template(
conversation=system_messages,
tools=[x.args_schema for x in tools],
tokenize=False,
add_generation_prompt=True,
)
if len(system_messages) != 0
else ""
)
if self.__count_tokens(prompt) > self.context_length:
raise ValueError(

Check warning on line 90 in libertai_agents/libertai_agents/models/base.py

View check run for this annotation

Codecov / codecov/patch

libertai_agents/libertai_agents/models/base.py#L90

Added line #L90 was not covered by tests
f"Can't fit system messages into the available context length ({self.context_length} tokens)"
)

# Adding as many messages as we can fit into the context, starting from the last ones
for i in reversed(range(len(raw_messages))):
included_messages: list = system_messages + raw_messages[i:]
prompt = self.tokenizer.apply_chat_template(
new_prompt = self.tokenizer.apply_chat_template(
conversation=included_messages,
tools=[x.args_schema for x in tools],
tokenize=False,
add_generation_prompt=True,
)
if not isinstance(prompt, str):
raise TypeError("Generated prompt isn't a string")
if self.__count_tokens(prompt) <= self.context_length:
if self.__count_tokens(new_prompt) >= self.context_length:
return prompt
raise ValueError(
f"Can't fit messages into the available context length ({self.context_length} tokens)"
)
prompt = new_prompt

return prompt

def generate_tool_call_id(self) -> str | None:
"""
Expand Down
Loading