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

Anthropic requires the first message to be a non empty 'user' role #669

Merged
merged 10 commits into from
Aug 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
5 changes: 5 additions & 0 deletions .changeset/violet-meals-crash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-plugins-anthropic": patch
---

Anthropic requires the first message to be a non empty 'user' role
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def chat(

latest_system_message = _latest_system_message(chat_ctx)
anthropic_ctx = _build_anthropic_context(chat_ctx.messages, id(self))
collaped_anthropic_ctx = _collapse_messages(anthropic_ctx)
collaped_anthropic_ctx = _merge_messages(anthropic_ctx)
stream = self._client.messages.create(
max_tokens=opts.get("max_tokens", 1000),
system=latest_system_message,
Expand Down Expand Up @@ -205,7 +205,7 @@ def _latest_system_message(chat_ctx: llm.ChatContext) -> str:
return latest_system_str


def _collapse_messages(
def _merge_messages(
messages: List[anthropic.types.MessageParam],
) -> List[anthropic.types.MessageParam]:
# Anthropic enforces alternating messages
Expand All @@ -223,6 +223,11 @@ def _collapse_messages(

last_message["content"].extend(m["content"])

if len(combined_messages) == 0 or combined_messages[0]["role"] != "user":
combined_messages.insert(
0, {"role": "user", "content": [{"type": "text", "text": "(empty)"}]}
)

return combined_messages


Expand Down
Loading