Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: add prefix fill support for Claude to try and boost haiku performance (#958)
Charles Packerbe0aa0d7d27e
diff --git a/letta/llm_api/anthropic.py b/letta/llm_api/anthropic.pyindex f365a052d..bb5fcf96f 100644--- a/letta/llm_api/anthropic.py+++ b/letta/llm_api/anthropic.py@@ -19,6 +19,8 @@ from anthropic.types.beta import (from letta.errors import BedrockError, BedrockPermissionErrorfrom letta.llm_api.aws_bedrock import get_bedrock_client+from letta.llm_api.helpers import add_inner_thoughts_to_functions+from letta.local_llm.constants import INNER_THOUGHTS_KWARG, INNER_THOUGHTS_KWARG_DESCRIPTIONfrom letta.local_llm.utils import num_tokens_from_functions, num_tokens_from_messagesfrom letta.schemas.message import Message as _Messagefrom letta.schemas.message import MessageRole as _MessageRole@@ -513,9 +515,23 @@ def convert_anthropic_stream_event_to_chatcompletion(def _prepare_anthropic_request(data: ChatCompletionRequest,inner_thoughts_xml_tag: Optional[str] = "thinking",+ # if true, prefix fill the generation with the thinking tag+ prefix_fill: bool = True,+ # if true, put COT inside the tool calls instead of inside the content+ put_inner_thoughts_in_kwargs: bool = False,) -> dict:"""Prepare the request data for Anthropic API format."""- # convert the tools++ # if needed, put inner thoughts as a kwarg for all tools+ if data.tools and put_inner_thoughts_in_kwargs:+ functions = add_inner_thoughts_to_functions(+ functions=[t.function.model_dump() for t in data.tools],+ inner_thoughts_key=INNER_THOUGHTS_KWARG,+ inner_thoughts_description=INNER_THOUGHTS_KWARG_DESCRIPTION,+ )+ data.tools = [Tool(function=f) for f in functions]++ # convert the tools to Anthropic's payload formatanthropic_tools = None if data.tools is None else convert_tools_to_anthropic_format(data.tools)# pydantic -> dict@@ -529,11 +545,25 @@ def _prepare_anthropic_request(data.pop("tools")data.pop("tool_choice", None)elif anthropic_tools is not None:+ # TODO eventually enable parallel tool usedata["tools"] = anthropic_tools- if len(anthropic_tools) == 1:++ # tool_choice_type other than "auto" only plays nice if thinking goes inside the tool calls+ if put_inner_thoughts_in_kwargs:+ if len(anthropic_tools) == 1:+ data["tool_choice"] = {+ "type": "tool",+ "name": anthropic_tools[0]["name"],+ "disable_parallel_tool_use": True,+ }+ else:+ data["tool_choice"] = {+ "type": "any",+ "disable_parallel_tool_use": True,+ }+ else:data["tool_choice"] = {- "type": "tool",- "name": anthropic_tools[0]["name"],+ "type": "auto","disable_parallel_tool_use": True,}@@ -548,8 +578,21 @@ def _prepare_anthropic_request(message["content"] = None# Convert to Anthropic format- msg_objs = [_Message.dict_to_message(user_id=None, agent_id=None, openai_message_dict=m) for m in data["messages"]]- data["messages"] = [m.to_anthropic_dict(inner_thoughts_xml_tag=inner_thoughts_xml_tag) for m in msg_objs]+ msg_objs = [+ _Message.dict_to_message(+ user_id=None,+ agent_id=None,+ openai_message_dict=m,+ )+ for m in data["messages"]+ ]+ data["messages"] = [+ m.to_anthropic_dict(+ inner_thoughts_xml_tag=inner_thoughts_xml_tag,+ put_inner_thoughts_in_kwargs=put_inner_thoughts_in_kwargs,+ )+ for m in msg_objs+ ]# Ensure first message is userif data["messages"][0]["role"] != "user":@@ -558,6 +601,16 @@ def _prepare_anthropic_request(# Handle alternating messagesdata["messages"] = merge_tool_results_into_user_messages(data["messages"])+ # Handle prefix fill (not compatible with inner-thouguhts-in-kwargs)+ # https://docs.anthropic.com/en/api/messages#body-messages+ # NOTE: cannot prefill with tools for opus:+ # Your API request included an `assistant` message in the final position, which would pre-fill the `assistant` response. When using tools with "claude-3-opus-20240229"+ if prefix_fill and not put_inner_thoughts_in_kwargs and "opus" not in data["model"]:+ data["messages"].append(+ # Start the thinking process for the assistant+ {"role": "assistant", "content": f"<{inner_thoughts_xml_tag}>"},+ )+# Validate max_tokensassert "max_tokens" in data, data@@ -571,6 +624,7 @@ def _prepare_anthropic_request(def anthropic_chat_completions_request(data: ChatCompletionRequest,inner_thoughts_xml_tag: Optional[str] = "thinking",+ put_inner_thoughts_in_kwargs: bool = False,betas: List[str] = ["tools-2024-04-04"],) -> ChatCompletionResponse:"""https://docs.anthropic.com/claude/docs/tool-use"""@@ -580,7 +634,11 @@ def anthropic_chat_completions_request(anthropic_client = anthropic.Anthropic(api_key=anthropic_override_key)elif model_settings.anthropic_api_key:anthropic_client = anthropic.Anthropic()- data = _prepare_anthropic_request(data, inner_thoughts_xml_tag)+ data = _prepare_anthropic_request(+ data=data,+ inner_thoughts_xml_tag=inner_thoughts_xml_tag,+ put_inner_thoughts_in_kwargs=put_inner_thoughts_in_kwargs,+ )response = anthropic_client.beta.messages.create(**data,betas=betas,@@ -611,6 +669,7 @@ def anthropic_bedrock_chat_completions_request(def anthropic_chat_completions_request_stream(data: ChatCompletionRequest,inner_thoughts_xml_tag: Optional[str] = "thinking",+ put_inner_thoughts_in_kwargs: bool = False,betas: List[str] = ["tools-2024-04-04"],) -> Generator[ChatCompletionChunkResponse, None, None]:"""Stream chat completions from Anthropic API.@@ -618,7 +677,11 @@ def anthropic_chat_completions_request_stream(Similar to OpenAI's streaming, but using Anthropic's native streaming support.See: https://docs.anthropic.com/claude/reference/messages-streaming"""- data = _prepare_anthropic_request(data, inner_thoughts_xml_tag)+ data = _prepare_anthropic_request(+ data=data,+ inner_thoughts_xml_tag=inner_thoughts_xml_tag,+ put_inner_thoughts_in_kwargs=put_inner_thoughts_in_kwargs,+ )anthropic_override_key = ProviderManager().get_anthropic_override_key()if anthropic_override_key:@@ -666,6 +729,7 @@ def anthropic_chat_completions_process_stream(chat_completion_request: ChatCompletionRequest,stream_interface: Optional[Union[AgentChunkStreamingInterface, AgentRefreshStreamingInterface]] = None,inner_thoughts_xml_tag: Optional[str] = "thinking",+ put_inner_thoughts_in_kwargs: bool = False,create_message_id: bool = True,create_message_datetime: bool = True,betas: List[str] = ["tools-2024-04-04"],@@ -743,6 +807,7 @@ def anthropic_chat_completions_process_stream(anthropic_chat_completions_request_stream(data=chat_completion_request,inner_thoughts_xml_tag=inner_thoughts_xml_tag,+ put_inner_thoughts_in_kwargs=put_inner_thoughts_in_kwargs,betas=betas,)):diff --git a/letta/llm_api/llm_api_tools.py b/letta/llm_api/llm_api_tools.pyindex f5083e7fb..77ba4839d 100644--- a/letta/llm_api/llm_api_tools.py+++ b/letta/llm_api/llm_api_tools.py@@ -278,14 +278,21 @@ def create(response = anthropic_chat_completions_process_stream(chat_completion_request=chat_completion_request,+ put_inner_thoughts_in_kwargs=llm_config.put_inner_thoughts_in_kwargs,stream_interface=stream_interface,)- return response- # Client did not request token streaming (expect a blocking backend response)- return anthropic_chat_completions_request(- data=chat_completion_request,- )+ else:+ # Client did not request token streaming (expect a blocking backend response)+ response = anthropic_chat_completions_request(+ data=chat_completion_request,+ put_inner_thoughts_in_kwargs=llm_config.put_inner_thoughts_in_kwargs,+ )++ if llm_config.put_inner_thoughts_in_kwargs:+ response = unpack_all_inner_thoughts_from_kwargs(response=response, inner_thoughts_key=INNER_THOUGHTS_KWARG)++ return response# elif llm_config.model_endpoint_type == "cohere":# if stream:diff --git a/letta/schemas/message.py b/letta/schemas/message.pyindex c9887772d..722a749b1 100644--- a/letta/schemas/message.py+++ b/letta/schemas/message.py@@ -542,7 +542,11 @@ class Message(BaseMessage):return openai_message- def to_anthropic_dict(self, inner_thoughts_xml_tag="thinking") -> dict:+ def to_anthropic_dict(+ self,+ inner_thoughts_xml_tag="thinking",+ put_inner_thoughts_in_kwargs: bool = False,+ ) -> dict:"""Convert to an Anthropic message dictionary@@ -586,26 +590,38 @@ class Message(BaseMessage):"role": self.role,}content = []- if self.text is not None:+ # COT / reasoning / thinking+ if self.text is not None and not put_inner_thoughts_in_kwargs:content.append({"type": "text","text": add_xml_tag(string=self.text, xml_tag=inner_thoughts_xml_tag),})+ # Tool callingif self.tool_calls is not None:for tool_call in self.tool_calls:++ if put_inner_thoughts_in_kwargs:+ tool_call_input = add_inner_thoughts_to_tool_call(+ tool_call,+ inner_thoughts=self.text,+ inner_thoughts_key=INNER_THOUGHTS_KWARG,+ ).model_dump()+ else:+ tool_call_input = json.loads(tool_call.function.arguments)+content.append({"type": "tool_use","id": tool_call.id,"name": tool_call.function.name,- "input": json.loads(tool_call.function.arguments),+ "input": tool_call_input,})# If the only content was text, unpack it back into a singleton- # TODO+ # TODO support multi-modalanthropic_message["content"] = content# Optional fields, do not include if nulldiff --git a/letta/schemas/providers.py b/letta/schemas/providers.pyindex 1fad89436..e96787598 100644--- a/letta/schemas/providers.py+++ b/letta/schemas/providers.py@@ -347,6 +347,15 @@ class AnthropicProvider(Provider):configs = []for model in models:++ # We set this to false by default, because Anthropic can+ # natively support <thinking> tags inside of content fields+ # However, putting COT inside of tool calls can make it more+ # reliable for tool calling (no chance of a non-tool call step)+ # Since tool_choice_type 'any' doesn't work with in-content COT+ # NOTE For Haiku, it can be flaky if we don't enable this by default+ inner_thoughts_in_kwargs = True if "haiku" in model["name"] else False+configs.append(LLMConfig(model=model["name"],@@ -354,6 +363,7 @@ class AnthropicProvider(Provider):model_endpoint=self.base_url,context_window=model["context_window"],handle=self.get_handle(model["name"]),+ put_inner_thoughts_in_kwargs=inner_thoughts_in_kwargs,))return configsdiff --git a/letta/server/rest_api/interface.py b/letta/server/rest_api/interface.pyindex a9e617f75..e58cbde1e 100644--- a/letta/server/rest_api/interface.py+++ b/letta/server/rest_api/interface.py@@ -436,11 +436,15 @@ class StreamingServerInterface(AgentChunkStreamingInterface):# inner thoughtsif message_delta.content is not None:- processed_chunk = ReasoningMessage(- id=message_id,- date=message_date,- reasoning=message_delta.content,- )+ if message_delta.content == "":+ print("skipping empty content")+ processed_chunk = None+ else:+ processed_chunk = ReasoningMessage(+ id=message_id,+ date=message_date,+ reasoning=message_delta.content,+ )# tool callselif message_delta.tool_calls is not None and len(message_delta.tool_calls) > 0:@@ -496,15 +500,24 @@ class StreamingServerInterface(AgentChunkStreamingInterface):if tool_call.function.name:tool_call_delta["name"] = tool_call.function.name- processed_chunk = ToolCallMessage(- id=message_id,- date=message_date,- tool_call=ToolCallDelta(- name=tool_call_delta.get("name"),- arguments=tool_call_delta.get("arguments"),- tool_call_id=tool_call_delta.get("id"),- ),- )+ # We might end up with a no-op, in which case we should omit+ if (+ tool_call_delta.get("name") is None+ and tool_call_delta.get("arguments") in [None, ""]+ and tool_call_delta.get("id") is None+ ):+ processed_chunk = None+ print("skipping empty chunk...")+ else:+ processed_chunk = ToolCallMessage(+ id=message_id,+ date=message_date,+ tool_call=ToolCallDelta(+ name=tool_call_delta.get("name"),+ arguments=tool_call_delta.get("arguments"),+ tool_call_id=tool_call_delta.get("id"),+ ),+ )elif self.inner_thoughts_in_kwargs and tool_call.function:processed_chunk = None@@ -525,11 +538,12 @@ class StreamingServerInterface(AgentChunkStreamingInterface):self.function_id_buffer += tool_call.idif tool_call.function.arguments:- if chunk.model.startswith("claude-"):- updates_main_json = tool_call.function.arguments- updates_inner_thoughts = ""- else: # OpenAI- updates_main_json, updates_inner_thoughts = self.function_args_reader.process_fragment(tool_call.function.arguments)+ # if chunk.model.startswith("claude-"):+ # updates_main_json = tool_call.function.arguments+ # updates_inner_thoughts = ""+ # else: # OpenAI+ # updates_main_json, updates_inner_thoughts = self.function_args_reader.process_fragment(tool_call.function.arguments)+ updates_main_json, updates_inner_thoughts = self.function_args_reader.process_fragment(tool_call.function.arguments)# If we have inner thoughts, we should output them as a chunkif updates_inner_thoughts:@@ -787,15 +801,24 @@ class StreamingServerInterface(AgentChunkStreamingInterface):if tool_call.function.name:tool_call_delta["name"] = tool_call.function.name- processed_chunk = ToolCallMessage(- id=message_id,- date=message_date,- tool_call=ToolCallDelta(- name=tool_call_delta.get("name"),- arguments=tool_call_delta.get("arguments"),- tool_call_id=tool_call_delta.get("id"),- ),- )+ # We might end up with a no-op, in which case we should omit+ if (+ tool_call_delta.get("name") is None+ and tool_call_delta.get("arguments") in [None, ""]+ and tool_call_delta.get("id") is None+ ):+ processed_chunk = None+ print("skipping empty chunk...")+ else:+ processed_chunk = ToolCallMessage(+ id=message_id,+ date=message_date,+ tool_call=ToolCallDelta(+ name=tool_call_delta.get("name"),+ arguments=tool_call_delta.get("arguments"),+ tool_call_id=tool_call_delta.get("id"),+ ),+ )elif choice.finish_reason is not None:# skip if there's a finish