Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: patch streaming API code (#1693)
Charles Packerad3fa859854e
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 0625156c8..f46031f7a 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -27,6 +27,9 @@ from memgpt.schemas.enums import OptionStatefrom memgpt.schemas.memory import Memoryfrom memgpt.schemas.message import Messagefrom memgpt.schemas.openai.chat_completion_response import ChatCompletionResponse+from memgpt.schemas.openai.chat_completion_response import (+ Message as ChatCompletionMessage,+)from memgpt.schemas.passage import Passagefrom memgpt.schemas.tool import Toolfrom memgpt.system import (@@ -441,9 +444,21 @@ class Agent(object):except Exception as e:raise e- def _handle_ai_response(self, response_message: Message, override_tool_call_id: bool = True) -> Tuple[List[Message], bool, bool]:+ def _handle_ai_response(+ self,+ response_message: ChatCompletionMessage, # TODO should we eventually move the Message creation outside of this function?+ override_tool_call_id: bool = True,+ # If we are streaming, we needed to create a Message ID ahead of time,+ # and now we want to use it in the creation of the Message object+ # TODO figure out a cleaner way to do this+ response_message_id: Optional[str] = None,+ ) -> Tuple[List[Message], bool, bool]:"""Handles parsing and function execution"""+ # Hacky failsafe for now to make sure we didn't implement the streaming Message ID creation incorrectly+ if response_message_id is not None:+ assert response_message_id.startswith("message-"), response_message_id+messages = [] # append these to the history when done# Step 2: check if LLM wanted to call a function@@ -474,6 +489,7 @@ class Agent(object):# NOTE: we're recreating the message here# TODO should probably just overwrite the fields?Message.dict_to_message(+ id=response_message_id,agent_id=self.agent_state.id,user_id=self.agent_state.user_id,model=self.model,@@ -619,6 +635,7 @@ class Agent(object):# Standard non-function replymessages.append(Message.dict_to_message(+ id=response_message_id,agent_id=self.agent_state.id,user_id=self.agent_state.user_id,model=self.model,@@ -765,7 +782,12 @@ class Agent(object):# (if yes) Step 5: send the info on the function call and function response to LLMresponse_message = response.choices[0].messageresponse_message.model_copy() # TODO why are we copying here?- all_response_messages, heartbeat_request, function_failed = self._handle_ai_response(response_message)+ all_response_messages, heartbeat_request, function_failed = self._handle_ai_response(+ response_message,+ # TODO this is kind of hacky, find a better way to handle this+ # the only time we set up message creation ahead of time is when streaming is on+ response_message_id=response.id if stream else None,+ )# Add the extra metadata to the assistant response# (e.g. enough metadata to enable recreating the API call)diff --git a/memgpt/client/client.py b/memgpt/client/client.pyindex a4c3a66be..c7472622f 100644--- a/memgpt/client/client.py+++ b/memgpt/client/client.py@@ -375,7 +375,7 @@ class RESTClient(AbstractClient):# agent interactions- def user_message(self, agent_id: str, message: str) -> Union[List[Dict], Tuple[List[Dict], int]]:+ def user_message(self, agent_id: str, message: str) -> MemGPTResponse:return self.send_message(agent_id, message, role="user")def save(self):@@ -423,7 +423,7 @@ class RESTClient(AbstractClient):) -> MemGPTResponse:messages = [MessageCreate(role=role, text=message, name=name)]# TODO: figure out how to handle stream_steps and stream_tokens- request = MemGPTRequest(messages=messages, stream_steps=stream)+ request = MemGPTRequest(messages=messages, stream_steps=stream, return_message_object=True)response = requests.post(f"{self.base_url}/api/agents/{agent_id}/messages", json=request.model_dump(), headers=self.headers)if response.status_code != 200:raise ValueError(f"Failed to send message: {response.text}")diff --git a/memgpt/constants.py b/memgpt/constants.pyindex d3f7634f1..b9b59a4d6 100644--- a/memgpt/constants.py+++ b/memgpt/constants.py@@ -3,6 +3,11 @@ from logging import CRITICAL, DEBUG, ERROR, INFO, NOTSET, WARN, WARNINGMEMGPT_DIR = os.path.join(os.path.expanduser("~"), ".memgpt")+# String in the error message for when the context window is too large+# Example full message:+# This model's maximum context length is 8192 tokens. However, your messages resulted in 8198 tokens (7450 in the messages, 748 in the functions). Please reduce the length of the messages or functions.+OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRING = "maximum context length"+# System prompt templatingIN_CONTEXT_MEMORY_KEYWORD = "CORE_MEMORY"diff --git a/memgpt/llm_api/llm_api_tools.py b/memgpt/llm_api/llm_api_tools.pyindex 310a91a84..5603a9b81 100644--- a/memgpt/llm_api/llm_api_tools.py+++ b/memgpt/llm_api/llm_api_tools.py@@ -3,13 +3,12 @@ import jsonimport osimport randomimport time-import uuidimport warningsfrom typing import List, Optional, Unionimport requests-from memgpt.constants import CLI_WARNING_PREFIX+from memgpt.constants import CLI_WARNING_PREFIX, OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRINGfrom memgpt.credentials import MemGPTCredentialsfrom memgpt.llm_api.anthropic import anthropic_chat_completions_requestfrom memgpt.llm_api.azure_openai import (@@ -134,7 +133,7 @@ def is_context_overflow_error(exception: requests.exceptions.RequestException) -"""Checks if an exception is due to context overflow (based on common OpenAI response messages)"""from memgpt.utils import printd- match_string = "maximum context length"+ match_string = OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRING# Backwards compatibility with openai python package/client v0.28 (pre-v1 client migration)if match_string in str(exception):@@ -231,9 +230,9 @@ def create(# agent_state: AgentState,llm_config: LLMConfig,messages: List[Message],- user_id: uuid.UUID = None, # option UUID to associate request with- functions: list = None,- functions_python: list = None,+ user_id: Optional[str] = None, # option UUID to associate request with+ functions: Optional[list] = None,+ functions_python: Optional[list] = None,function_call: str = "auto",# hintfirst_message: bool = False,diff --git a/memgpt/llm_api/openai.py b/memgpt/llm_api/openai.pyindex d33d03f9a..3d2899901 100644--- a/memgpt/llm_api/openai.py+++ b/memgpt/llm_api/openai.py@@ -6,7 +6,11 @@ import requestsfrom httpx_sse import connect_ssefrom httpx_sse._exceptions import SSEError+from memgpt.constants import OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRING+from memgpt.errors import LLMErrorfrom memgpt.local_llm.utils import num_tokens_from_functions, num_tokens_from_messages+from memgpt.schemas.message import Message as _Message+from memgpt.schemas.message import MessageRole as _MessageRolefrom memgpt.schemas.openai.chat_completion_request import ChatCompletionRequestfrom memgpt.schemas.openai.chat_completion_response import (ChatCompletionChunkResponse,@@ -22,7 +26,7 @@ from memgpt.streaming_interface import (AgentChunkStreamingInterface,AgentRefreshStreamingInterface,)-from memgpt.utils import get_utc_time, smart_urljoin+from memgpt.utils import smart_urljoinOPENAI_SSE_DONE = "[DONE]"@@ -82,6 +86,8 @@ def openai_chat_completions_process_stream(api_key: str,chat_completion_request: ChatCompletionRequest,stream_inferface: Optional[Union[AgentChunkStreamingInterface, AgentRefreshStreamingInterface]] = None,+ create_message_id: bool = True,+ create_message_datetime: bool = True,) -> ChatCompletionResponse:"""Process a streaming completion response, and return a ChatCompletionRequest at the end.@@ -114,13 +120,26 @@ def openai_chat_completions_process_stream(model=chat_completion_request.model,)+ # Create a dummy Message object to get an ID and date+ # TODO(sarah): add message ID generation function+ dummy_message = _Message(+ role=_MessageRole.assistant,+ text="",+ user_id="",+ agent_id="",+ model="",+ name=None,+ tool_calls=None,+ tool_call_id=None,+ )+TEMP_STREAM_RESPONSE_ID = "temp_id"TEMP_STREAM_FINISH_REASON = "temp_null"TEMP_STREAM_TOOL_CALL_ID = "temp_id"chat_completion_response = ChatCompletionResponse(- id=TEMP_STREAM_RESPONSE_ID,+ id=dummy_message.id if create_message_id else TEMP_STREAM_RESPONSE_ID,choices=[],- created=get_utc_time(),+ created=dummy_message.created_at, # NOTE: doesn't matter since both will do get_utc_time()model=chat_completion_request.model,usage=UsageStatistics(completion_tokens=0,@@ -138,11 +157,14 @@ def openai_chat_completions_process_stream(openai_chat_completions_request_stream(url=url, api_key=api_key, chat_completion_request=chat_completion_request)):assert isinstance(chat_completion_chunk, ChatCompletionChunkResponse), type(chat_completion_chunk)- # print(chat_completion_chunk)if stream_inferface:if isinstance(stream_inferface, AgentChunkStreamingInterface):- stream_inferface.process_chunk(chat_completion_chunk)+ stream_inferface.process_chunk(+ chat_completion_chunk,+ message_id=chat_completion_response.id if create_message_id else chat_completion_chunk.id,+ message_date=chat_completion_response.created if create_message_datetime else chat_completion_chunk.created,+ )elif isinstance(stream_inferface, AgentRefreshStreamingInterface):stream_inferface.process_refresh(chat_completion_response)else:@@ -209,10 +231,12 @@ def openai_chat_completions_process_stream(raise NotImplementedError(f"Old function_call style not support with stream=True")# overwrite response fields based on latest chunk- chat_completion_response.id = chat_completion_chunk.id- chat_completion_response.system_fingerprint = chat_completion_chunk.system_fingerprint- chat_completion_response.created = chat_completion_chunk.created+ if not create_message_id:+ chat_completion_response.id = chat_completion_chunk.id+ if not create_message_datetime:+ chat_completion_response.created = chat_completion_chunk.createdchat_completion_response.model = chat_completion_chunk.model+ chat_completion_response.system_fingerprint = chat_completion_chunk.system_fingerprint# increment chunk countern_chunks += 1@@ -234,7 +258,8 @@ def openai_chat_completions_process_stream(for c in chat_completion_response.choices])- assert chat_completion_response.id != TEMP_STREAM_RESPONSE_ID+ if not create_message_id:+ assert chat_completion_response.id != dummy_message.id# compute token usage before returning# TODO try actually computing the #tokens instead of assuming the chunks is the same@@ -263,7 +288,10 @@ def _sse_post(url: str, data: dict, headers: dict) -> Generator[ChatCompletionChresponse_dict = json.loads(response_bytes.decode("utf-8"))error_message = response_dict["error"]["message"]# e.g.: This model's maximum context length is 8192 tokens. However, your messages resulted in 8198 tokens (7450 in the messages, 748 in the functions). Please reduce the length of the messages or functions.- raise Exception(error_message)+ if OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRING in error_message:+ raise LLMError(error_message)+ except LLMError:+ raiseexcept:print(f"Failed to parse SSE message, throwing SSE HTTP error up the stack")event_source.response.raise_for_status()diff --git a/memgpt/memory.py b/memgpt/memory.pyindex bfe679563..7543c5c7d 100644--- a/memgpt/memory.py+++ b/memgpt/memory.py@@ -276,6 +276,7 @@ def summarize_messages(llm_config=agent_state.llm_config,user_id=agent_state.user_id,messages=message_sequence,+ stream=False,)printd(f"summarize_messages gpt reply: {response.choices[0]}")diff --git a/memgpt/schemas/enums.py b/memgpt/schemas/enums.pyindex c8ebae734..78427c834 100644--- a/memgpt/schemas/enums.py+++ b/memgpt/schemas/enums.py@@ -5,6 +5,7 @@ class MessageRole(str, Enum):assistant = "assistant"user = "user"tool = "tool"+ function = "function"system = "system"diff --git a/memgpt/schemas/memgpt_message.py b/memgpt/schemas/memgpt_message.pyindex 5b659b471..3e7d2fc59 100644--- a/memgpt/schemas/memgpt_message.py+++ b/memgpt/schemas/memgpt_message.py@@ -1,5 +1,6 @@+import jsonfrom datetime import datetime, timezone-from typing import Literal, Union+from typing import Literal, Optional, Unionfrom pydantic import BaseModel, field_serializer@@ -12,7 +13,11 @@ class BaseMemGPTMessage(BaseModel):@field_serializer("date")def serialize_datetime(self, dt: datetime, _info):- return dt.now(timezone.utc).isoformat()+ if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:+ dt = dt.replace(tzinfo=timezone.utc)+ # Remove microseconds since it seems like we're inconsistent with getting them+ # TODO figure out why we don't always get microseconds (get_utc_time() does)+ return dt.isoformat(timespec="seconds")class InternalMonologue(BaseMemGPTMessage):@@ -32,6 +37,20 @@ class FunctionCall(BaseModel):arguments: str+class FunctionCallDelta(BaseModel):+ name: Optional[str]+ arguments: Optional[str]++ # NOTE: this is a workaround to exclude None values from the JSON dump,+ # since the OpenAI style of returning chunks doesn't include keys with null values+ def model_dump(self, *args, **kwargs):+ kwargs["exclude_none"] = True+ return super().model_dump(*args, **kwargs)++ def json(self, *args, **kwargs):+ return json.dumps(self.model_dump(exclude_none=True), *args, **kwargs)++class FunctionCallMessage(BaseMemGPTMessage):"""{@@ -44,7 +63,21 @@ class FunctionCallMessage(BaseMemGPTMessage):}"""- function_call: FunctionCall+ function_call: Union[FunctionCall, FunctionCallDelta]++ # NOTE: this is required for the FunctionCallDelta exclude_none to work correctly+ def model_dump(self, *args, **kwargs):+ kwargs["exclude_none"] = True+ data = super().model_dump(*args, **kwargs)+ if isinstance(data["function_call"], dict):+ data["function_call"] = {k: v for k, v in data["function_call"].items() if v is not None}+ return data++ class Config:+ json_encoders = {+ FunctionCallDelta: lambda v: v.model_dump(exclude_none=True),+ FunctionCall: lambda v: v.model_dump(exclude_none=True),+ }class FunctionReturn(BaseMemGPTMessage):diff --git a/memgpt/schemas/memgpt_request.py b/memgpt/schemas/memgpt_request.pyindex f46930130..06e6f41fd 100644--- a/memgpt/schemas/memgpt_request.py+++ b/memgpt/schemas/memgpt_request.py@@ -16,3 +16,8 @@ class MemGPTRequest(BaseModel):default=False,description="Flag to determine if individual tokens should be streamed. Set to True for token streaming (requires stream_steps = True).",)++ return_message_object: bool = Field(+ default=False,+ description="Set True to return the raw Message object. Set False to return the Message in the format of the MemGPT API.",+ )diff --git a/memgpt/schemas/message.py b/memgpt/schemas/message.pyindex 4df31072f..222b83bf1 100644--- a/memgpt/schemas/message.py+++ b/memgpt/schemas/message.py@@ -11,7 +11,7 @@ from memgpt.local_llm.constants import INNER_THOUGHTS_KWARGfrom memgpt.schemas.enums import MessageRolefrom memgpt.schemas.memgpt_base import MemGPTBasefrom memgpt.schemas.memgpt_message import LegacyMemGPTMessage, MemGPTMessage-from memgpt.schemas.openai.chat_completions import ToolCall+from memgpt.schemas.openai.chat_completions import ToolCall, ToolCallFunctionfrom memgpt.utils import get_utc_time, is_utc_datetime, json_dumps@@ -103,6 +103,7 @@ class Message(BaseMessage):model: Optional[str] = None, # model used to make function callallow_functions_style: bool = False, # allow deprecated functions style?created_at: Optional[datetime] = None,+ id: Optional[str] = None,):"""Convert a ChatCompletion message object into a Message object (synced to DB)"""if not created_at:@@ -120,18 +121,45 @@ class Message(BaseMessage):# Convert from 'function' response to a 'tool' response# NOTE: this does not conventionally include a tool_call_id, it's on the caster to provide it- return Message(+ message_args = dict(user_id=user_id,agent_id=agent_id,model=model,# standard fields expected in an OpenAI ChatCompletion message object- role="tool", # NOTE+ role=MessageRole.tool, # NOTEtext=openai_message_dict["content"],name=openai_message_dict["name"] if "name" in openai_message_dict else None,tool_calls=openai_message_dict["tool_calls"] if "tool_calls" in openai_message_dict else None,tool_call_id=openai_message_dict["tool_call_id"] if "tool_call_id" in openai_message_dict else None,created_at=created_at,)+ if id is not None:+ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role=MessageRole.tool, # NOTE+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=openai_message_dict["tool_calls"] if "tool_calls" in openai_message_dict else None,+ tool_call_id=openai_message_dict["tool_call_id"] if "tool_call_id" in openai_message_dict else None,+ created_at=created_at,+ id=str(id),+ )+ else:+ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role=MessageRole.tool, # NOTE+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=openai_message_dict["tool_calls"] if "tool_calls" in openai_message_dict else None,+ tool_call_id=openai_message_dict["tool_call_id"] if "tool_call_id" in openai_message_dict else None,+ created_at=created_at,+ )elif "function_call" in openai_message_dict and openai_message_dict["function_call"] is not None:if not allow_functions_style:@@ -144,26 +172,41 @@ class Message(BaseMessage):tool_calls = [ToolCall(id=openai_message_dict["tool_call_id"], # NOTE: unconventional source, not to spec- tool_call_type="function",- function={- "name": openai_message_dict["function_call"]["name"],- "arguments": openai_message_dict["function_call"]["arguments"],- },+ type="function",+ function=ToolCallFunction(+ name=openai_message_dict["function_call"]["name"],+ arguments=openai_message_dict["function_call"]["arguments"],+ ),)]- return Message(- user_id=user_id,- agent_id=agent_id,- model=model,- # standard fields expected in an OpenAI ChatCompletion message object- role=openai_message_dict["role"],- text=openai_message_dict["content"],- name=openai_message_dict["name"] if "name" in openai_message_dict else None,- tool_calls=tool_calls,- tool_call_id=None, # NOTE: None, since this field is only non-null for role=='tool'- created_at=created_at,- )+ if id is not None:+ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role=MessageRole(openai_message_dict["role"]),+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=tool_calls,+ tool_call_id=None, # NOTE: None, since this field is only non-null for role=='tool'+ created_at=created_at,+ id=str(id),+ )+ else:+ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role=MessageRole(openai_message_dict["role"]),+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=tool_calls,+ tool_call_id=None, # NOTE: None, since this field is only non-null for role=='tool'+ created_at=created_at,+ )else:# Basic sanity check@@ -177,25 +220,40 @@ class Message(BaseMessage):assert openai_message_dict["role"] == "assistant", openai_message_dicttool_calls = [- ToolCall(id=tool_call["id"], tool_call_type=tool_call["type"], function=tool_call["function"])+ ToolCall(id=tool_call["id"], type=tool_call["type"], function=tool_call["function"])for tool_call in openai_message_dict["tool_calls"]]else:tool_calls = None# If we're going from tool-call style- return Message(- user_id=user_id,- agent_id=agent_id,- model=model,- # standard fields expected in an OpenAI ChatCompletion message object- role=openai_message_dict["role"],- text=openai_message_dict["content"],- name=openai_message_dict["name"] if "name" in openai_message_dict else None,- tool_calls=tool_calls,- tool_call_id=openai_message_dict["tool_call_id"] if "tool_call_id" in openai_message_dict else None,- created_at=created_at,- )+ if id is not None:+ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role=MessageRole(openai_message_dict["role"]),+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=tool_calls,+ tool_call_id=openai_message_dict["tool_call_id"] if "tool_call_id" in openai_message_dict else None,+ created_at=created_at,+ id=str(id),+ )+ else:+ return Message(+ user_id=user_id,+ agent_id=agent_id,+ model=model,+ # standard fields expected in an OpenAI ChatCompletion message object+ role=MessageRole(openai_message_dict["role"]),+ text=openai_message_dict["content"],+ name=openai_message_dict["name"] if "name" in openai_message_dict else None,+ tool_calls=tool_calls,+ tool_call_id=openai_message_dict["tool_call_id"] if "tool_call_id" in openai_message_dict else None,+ created_at=created_at,+ )def to_openai_dict_search_results(self, max_tool_id_length: int = TOOL_CALL_ID_MAX_LEN) -> dict:result_json = self.to_openai_dict()diff --git a/memgpt/server/rest_api/agents/message.py b/memgpt/server/rest_api/agents/message.pyindex 656b6a6d9..b0da83fc3 100644--- a/memgpt/server/rest_api/agents/message.py+++ b/memgpt/server/rest_api/agents/message.py@@ -30,10 +30,10 @@ async def send_message_to_agent(message: str,stream_steps: bool,stream_tokens: bool,+ return_message_object: bool, # Should be True for Python Client, False for REST APIchat_completion_mode: Optional[bool] = False,timestamp: Optional[datetime] = None,# related to whether or not we return `MemGPTMessage`s or `Message`s- return_message_object: bool = True, # Should be True for Python Client, False for REST API) -> Union[StreamingResponse, MemGPTResponse]:"""Split off into a separate function so that it can be imported in the /chat/completion proxy."""# TODO: @charles is this the correct way to handle?@@ -184,7 +184,7 @@ def setup_agents_message_router(server: SyncServer, interface: QueuingInterface,message=message.text,stream_steps=request.stream_steps,stream_tokens=request.stream_tokens,- return_message_object=False,+ return_message_object=request.return_message_object,)return routerdiff --git a/memgpt/server/rest_api/interface.py b/memgpt/server/rest_api/interface.pyindex 38ceb0553..782d8d3dd 100644--- a/memgpt/server/rest_api/interface.py+++ b/memgpt/server/rest_api/interface.py@@ -2,6 +2,7 @@ import asyncioimport jsonimport queuefrom collections import deque+from datetime import datetimefrom typing import AsyncGenerator, Literal, Optional, Unionfrom memgpt.interface import AgentInterface@@ -9,6 +10,7 @@ from memgpt.schemas.enums import MessageStreamStatusfrom memgpt.schemas.memgpt_message import (AssistantMessage,FunctionCall,+ FunctionCallDelta,FunctionCallMessage,FunctionReturn,InternalMonologue,@@ -355,13 +357,24 @@ class StreamingServerInterface(AgentChunkStreamingInterface):raise StopIteration("The stream has not been started or has been ended.")return self._create_generator()- def _push_to_buffer(self, item: Union[MemGPTMessage, LegacyMemGPTMessage, MessageStreamStatus]):+ def _push_to_buffer(+ self,+ item: Union[+ # signal on SSE stream status [DONE_GEN], [DONE_STEP], [DONE]+ MessageStreamStatus,+ # the non-streaming message types+ MemGPTMessage,+ LegacyMemGPTMessage,+ # the streaming message types+ ChatCompletionChunkResponse,+ ],+ ):"""Add an item to the deque"""assert self._active, "Generator is inactive"- # assert isinstance(item, dict) or isinstance(item, MessageStreamStatus), f"Wrong type: {type(item)}"assert (isinstance(item, MemGPTMessage) or isinstance(item, LegacyMemGPTMessage) or isinstance(item, MessageStreamStatus)), f"Wrong type: {type(item)}"+self._chunks.append(item)self._event.set() # Signal that new data is available@@ -414,7 +427,9 @@ class StreamingServerInterface(AgentChunkStreamingInterface):def clear():return- def _process_chunk_to_memgpt_style(self, chunk: ChatCompletionChunkResponse) -> Optional[dict]:+ def _process_chunk_to_memgpt_style(+ self, chunk: ChatCompletionChunkResponse, message_id: str, message_date: datetime+ ) -> Optional[Union[InternalMonologue, FunctionCallMessage]]:"""Example data from non-streaming response looks like:@@ -429,9 +444,11 @@ class StreamingServerInterface(AgentChunkStreamingInterface):# inner thoughtsif message_delta.content is not None:- processed_chunk = {- "internal_monologue": message_delta.content,- }+ processed_chunk = InternalMonologue(+ id=message_id,+ date=message_date,+ internal_monologue=message_delta.content,+ )elif message_delta.tool_calls is not None and len(message_delta.tool_calls) > 0:tool_call = message_delta.tool_calls[0]@@ -444,17 +461,17 @@ class StreamingServerInterface(AgentChunkStreamingInterface):if tool_call.function.name:tool_call_delta["name"] = tool_call.function.name- processed_chunk = {- "function_call": tool_call_delta,- }+ processed_chunk = FunctionCallMessage(+ id=message_id,+ date=message_date,+ function_call=FunctionCallDelta(name=tool_call_delta.get("name"), arguments=tool_call_delta.get("arguments")),+ )elif choice.finish_reason is not None:# skip if there's a finishreturn Noneelse:raise ValueError(f"Couldn't find delta in chunk: {chunk}")- processed_chunk["date"] = chunk.created.isoformat()-return processed_chunkdef _process_chunk_to_openai_style(self, chunk: ChatCompletionChunkResponse) -> Optional[dict]:@@ -508,11 +525,11 @@ class StreamingServerInterface(AgentChunkStreamingInterface):# Replace with 'content'proxy_chunk.choices[0].delta.content = cleaned_func_args- processed_chunk = proxy_chunk.model_dump_json(exclude_none=True)+ processed_chunk = proxy_chunk.model_dump(exclude_none=True)return processed_chunk- def process_chunk(self, chunk: ChatCompletionChunkResponse, msg_obj: Optional[Message] = None):+ def process_chunk(self, chunk: ChatCompletionChunkResponse, message_id: str, message_date: datetime):"""Process a streaming chunk from an OpenAI-compatible server.Example data from non-streaming response looks like:@@ -529,16 +546,14 @@ class StreamingServerInterface(AgentChunkStreamingInterface):# processed_chunk = chunk.model_dump_json(exclude_none=True)if self.streaming_chat_completion_mode:- processed_chunk = self._process_chunk_to_openai_style(chunk)+ # processed_chunk = self._process_chunk_to_openai_style(chunk)+ raise NotImplementedError("OpenAI proxy streaming temporarily disabled")else:- processed_chunk = self._process_chunk_to_memgpt_style(chunk)+ processed_chunk = self._process_chunk_to_memgpt_style(chunk=chunk, message_id=message_id, message_date=message_date)if processed_chunk is None:return- if msg_obj:- processed_chunk["id"] = str(msg_obj.id)-self._push_to_buffer(processed_chunk)def user_message(self, msg: str, msg_obj: Optional[Message] = None):diff --git a/memgpt/server/server.py b/memgpt/server/server.pyindex 0208e14ee..067c2974f 100644--- a/memgpt/server/server.py+++ b/memgpt/server/server.py@@ -1597,7 +1597,6 @@ class SyncServer(Server):# get available functionsfunctions = [f for f in env if callable(env[f])]- print(functions)except Exception as e:logger.error(f"Failed to execute source code: {e}")diff --git a/memgpt/streaming_interface.py b/memgpt/streaming_interface.pyindex 7b8c7212c..71a212323 100644--- a/memgpt/streaming_interface.py+++ b/memgpt/streaming_interface.py@@ -1,5 +1,6 @@import jsonfrom abc import ABC, abstractmethod+from datetime import datetimefrom typing import List, Optional# from colorama import Fore, Style, init@@ -49,7 +50,7 @@ class AgentChunkStreamingInterface(ABC):raise NotImplementedError@abstractmethod- def process_chunk(self, chunk: ChatCompletionChunkResponse):+ def process_chunk(self, chunk: ChatCompletionChunkResponse, message_id: str, message_date: datetime):"""Process a streaming chunk from an OpenAI-compatible server"""raise NotImplementedError@@ -93,7 +94,7 @@ class StreamingCLIInterface(AgentChunkStreamingInterface):def _flush(self):pass- def process_chunk(self, chunk: ChatCompletionChunkResponse):+ def process_chunk(self, chunk: ChatCompletionChunkResponse, message_id: str, message_date: datetime):assert len(chunk.choices) == 1, chunkmessage_delta = chunk.choices[0].delta@@ -135,10 +136,10 @@ class StreamingCLIInterface(AgentChunkStreamingInterface):# Slightly more complex - want to write parameters in a certain way (paren-style)# function_name(function_args)- if function_call.name:+ if function_call and function_call.name:# NOTE: need to account for closing the brace laterprint(f"{function_call.name}(", end="", flush=True)- if function_call.arguments:+ if function_call and function_call.arguments:print(function_call.arguments, end="", flush=True)def stream_start(self):