Skip to content

Commit

Permalink
fix: truncate messages after hint was added
Browse files Browse the repository at this point in the history
  • Loading branch information
edwardzjl committed Dec 18, 2024
1 parent 2709bb6 commit 4e27317
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions api/chatbot/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,24 @@ async def chatbot(state: MessagesState) -> MessagesState:

bound = prompt | chat_model

windowed_messages: list[BaseMessage] = trim_messages(
state["messages"],
token_counter=token_counter,
max_tokens=max_tokens,
start_on="human", # This means that the first message should be from the user after trimming.
)
if hazard := windowed_messages[-1].additional_kwargs.get("hazard"):
hint_message = None
if hazard := state["messages"][-1].additional_kwargs.get("hazard"):
hint_message = SystemMessage(
content=f"""The user input may contain inproper content related to:
{hazard_categories.get(hazard)}
Please respond with care and professionalism. Avoid engaging with harmful or unethical content. Instead, guide the user towards more constructive and respectful communication."""
)
windowed_messages.append(hint_message)

all_messages = (
state["messages"] + hint_message if hint_message else state["messages"]
)
windowed_messages: list[BaseMessage] = trim_messages(
all_messages,
token_counter=token_counter,
max_tokens=max_tokens,
start_on="human", # This means that the first message should be from the user after trimming.
)

messages = await bound.ainvoke(
{
Expand Down

0 comments on commit 4e27317

Please sign in to comment.