Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add token streaming to the MemGPT API (#1280)
Charles Packera41a5a06693f
diff --git a/memgpt/client/client.py b/memgpt/client/client.pyindex 1c8a47080..30cb4c821 100644--- a/memgpt/client/client.py+++ b/memgpt/client/client.py@@ -649,7 +649,7 @@ class LocalClient(AbstractClient):add_default_presets(self.user_id, ms)self.interface = QueuingInterface(debug=debug)- self.server = SyncServer(default_interface=self.interface)+ self.server = SyncServer(default_interface_factory=lambda: self.interface)# messagesdef send_message(self, agent_id: uuid.UUID, message: str, role: str, stream: Optional[bool] = False) -> UserMessageResponse:diff --git a/memgpt/interface.py b/memgpt/interface.pyindex 5c3bcced9..aa1d27211 100644--- a/memgpt/interface.py+++ b/memgpt/interface.py@@ -309,3 +309,7 @@ class CLIInterface(AgentInterface):@staticmethoddef step_yield():pass++ @staticmethod+ def step_complete():+ passdiff --git a/memgpt/llm_api/llm_api_tools.py b/memgpt/llm_api/llm_api_tools.pyindex 1ab36e266..053ff78a2 100644--- a/memgpt/llm_api/llm_api_tools.py+++ b/memgpt/llm_api/llm_api_tools.py@@ -193,7 +193,7 @@ def create(if "gpt-4o" in llm_config.model or "gpt-4-turbo" in llm_config.model or "gpt-3.5-turbo" in llm_config.model:data.response_format = {"type": "json_object"}- if stream:+ if stream: # Client requested token streamingdata.stream = Trueassert isinstance(stream_inferface, AgentChunkStreamingInterface) or isinstance(stream_inferface, AgentRefreshStreamingInterface@@ -204,16 +204,26 @@ def create(chat_completion_request=data,stream_inferface=stream_inferface,)- else:+ else: # Client did not request token streaming (expect a blocking backend response)data.stream = False- return openai_chat_completions_request(- url=llm_config.model_endpoint, # https://api.openai.com/v1 -> https://api.openai.com/v1/chat/completions- api_key=credentials.openai_key,- chat_completion_request=data,- )+ if isinstance(stream_inferface, AgentChunkStreamingInterface):+ stream_inferface.stream_start()+ try:+ response = openai_chat_completions_request(+ url=llm_config.model_endpoint, # https://api.openai.com/v1 -> https://api.openai.com/v1/chat/completions+ api_key=credentials.openai_key,+ chat_completion_request=data,+ )+ finally:+ if isinstance(stream_inferface, AgentChunkStreamingInterface):+ stream_inferface.stream_end()+ return response# azureelif llm_config.model_endpoint_type == "azure":+ if stream:+ raise NotImplementedError(f"Streaming not yet implemented for {llm_config.model_endpoint_type}")+azure_deployment = (credentials.azure_deployment if credentials.azure_deployment is not None else MODEL_TO_AZURE_ENGINE[llm_config.model])@@ -244,6 +254,8 @@ def create()elif llm_config.model_endpoint_type == "google_ai":+ if stream:+ raise NotImplementedError(f"Streaming not yet implemented for {llm_config.model_endpoint_type}")if not use_tool_naming:raise NotImplementedError("Only tool calling supported on Google AI API requests")@@ -271,6 +283,8 @@ def create()elif llm_config.model_endpoint_type == "anthropic":+ if stream:+ raise NotImplementedError(f"Streaming not yet implemented for {llm_config.model_endpoint_type}")if not use_tool_naming:raise NotImplementedError("Only tool calling supported on Anthropic API requests")@@ -295,6 +309,8 @@ def create()elif llm_config.model_endpoint_type == "cohere":+ if stream:+ raise NotImplementedError(f"Streaming not yet implemented for {llm_config.model_endpoint_type}")if not use_tool_naming:raise NotImplementedError("Only tool calling supported on Cohere API requests")@@ -321,6 +337,8 @@ def create(# local modelelse:+ if stream:+ raise NotImplementedError(f"Streaming not yet implemented for {llm_config.model_endpoint_type}")return get_chat_completion(model=llm_config.model,messages=messages,diff --git a/memgpt/llm_api/openai.py b/memgpt/llm_api/openai.pyindex cbfe98912..279fc8740 100644--- a/memgpt/llm_api/openai.py+++ b/memgpt/llm_api/openai.py@@ -248,6 +248,25 @@ def _sse_post(url: str, data: dict, headers: dict) -> Generator[ChatCompletionChwith httpx.Client() as client:with connect_sse(client, method="POST", url=url, json=data, headers=headers) as event_source:++ # Inspect for errors before iterating (see https://github.com/florimondmanca/httpx-sse/pull/12)+ if not event_source.response.is_success:+ # handle errors+ from utils import printd++ printd("Caught error before iterating SSE request:", vars(event_source.response))+ printd(event_source.response.read())++ try:+ response_bytes = event_source.response.read()+ response_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)+ except:+ print(f"Failed to parse SSE message, throwing SSE HTTP error up the stack")+ event_source.response.raise_for_status()+try:for sse in event_source.iter_sse():# printd(sse.event, sse.data, sse.id, sse.retry)@@ -267,14 +286,17 @@ def _sse_post(url: str, data: dict, headers: dict) -> Generator[ChatCompletionChyield chunk_objectexcept SSEError as e:+ print("Caught an error while iterating the SSE stream:", str(e))if "application/json" in str(e): # Check if the error is because of JSON response+ # TODO figure out a better way to catch the error other than re-trying with a POSTresponse = client.post(url=url, json=data, headers=headers) # Make the request again to get the JSON responseif response.headers["Content-Type"].startswith("application/json"):error_details = response.json() # Parse the JSON to get the error message- print("Error:", error_details)- print("Reqeust:", vars(response.request))+ print("Request:", vars(response.request))+ print("POST Error:", error_details)+ print("Original SSE Error:", str(e))else:- print("Failed to retrieve JSON error message.")+ print("Failed to retrieve JSON error message via retry.")else:print("SSEError not related to 'application/json' content type.")diff --git a/memgpt/metadata.py b/memgpt/metadata.pyindex 33cf9b44e..62a67425d 100644--- a/memgpt/metadata.py+++ b/memgpt/metadata.py@@ -20,7 +20,7 @@ from sqlalchemy import (func,)from sqlalchemy.dialects.postgresql import UUID-from sqlalchemy.exc import InterfaceError+from sqlalchemy.exc import InterfaceError, OperationalErrorfrom sqlalchemy.orm import declarative_base, sessionmakerfrom sqlalchemy.sql import func@@ -360,7 +360,7 @@ class MetadataStore:JobModel.__table__,],)- except InterfaceError as e:+ except (InterfaceError, OperationalError) as e:traceback.print_exc()if config.metadata_storage_type == "postgres":raise ValueError(diff --git a/memgpt/server/rest_api/agents/message.py b/memgpt/server/rest_api/agents/message.pyindex 17d121fff..d68e0b0cf 100644--- a/memgpt/server/rest_api/agents/message.py+++ b/memgpt/server/rest_api/agents/message.py@@ -1,19 +1,17 @@import asyncio-import jsonimport uuid-from asyncio import AbstractEventLoopfrom datetime import datetimefrom enum import Enumfrom functools import partial-from typing import List, Optional+from typing import List, Optional, Unionfrom fastapi import APIRouter, Body, Depends, HTTPException, Queryfrom pydantic import BaseModel, Fieldfrom starlette.responses import StreamingResponse-from memgpt.constants import JSON_ENSURE_ASCIIfrom memgpt.server.rest_api.auth_token import get_current_user-from memgpt.server.rest_api.interface import QueuingInterface+from memgpt.server.rest_api.interface import QueuingInterface, StreamingServerInterface+from memgpt.server.rest_api.utils import sse_async_generatorfrom memgpt.server.server import SyncServerrouter = APIRouter()@@ -26,13 +24,24 @@ class MessageRoleType(str, Enum):class UserMessageRequest(BaseModel):message: str = Field(..., description="The message content to be processed by the agent.")- name: str = Field(default="user", description="Name of the message request sender")- stream: bool = Field(default=False, description="Flag to determine if the response should be streamed. Set to True for streaming.")+ name: Optional[str] = Field(default=None, description="Name of the message request sender")role: MessageRoleType = Field(default=MessageRoleType.user, description="Role of the message sender (either 'user' or 'system')")+ stream_steps: bool = Field(+ default=False, description="Flag to determine if the response should be streamed. Set to True for streaming agent steps."+ )+ stream_tokens: bool = Field(+ default=False,+ description="Flag to determine if individual tokens should be streamed. Set to True for token streaming (requires stream = True).",+ )timestamp: Optional[datetime] = Field(None,description="Timestamp to tag the message with (in ISO format). If null, timestamp will be created server-side on receipt of message.",)+ stream: bool = Field(+ default=False,+ description="Legacy flag for old streaming API, will be deprecrated in the future.",+ deprecated=True,+ )# @validator("timestamp", pre=True, always=True)# def validate_timestamp(cls, value: Optional[datetime]) -> Optional[datetime]:@@ -70,6 +79,86 @@ class GetAgentMessagesResponse(BaseModel):messages: list = Field(..., description="List of message objects.")+async def send_message_to_agent(+ server: SyncServer,+ agent_id: uuid.UUID,+ user_id: uuid.UUID,+ role: str,+ message: str,+ stream_legacy: bool, # legacy+ stream_steps: bool,+ stream_tokens: bool,+ chat_completion_mode: Optional[bool] = False,+) -> Union[StreamingResponse, UserMessageResponse]:+ """Split off into a separate function so that it can be imported in the /chat/completion proxy."""++ # handle the legacy mode streaming+ if stream_legacy:+ # NOTE: override+ stream_steps = True+ stream_tokens = False+ include_final_message = False++ if role == "user" or role is None:+ message_func = server.user_message+ elif role == "system":+ message_func = server.system_message+ else:+ raise HTTPException(status_code=500, detail=f"Bad role {role}")++ if not stream_steps and stream_tokens:+ raise HTTPException(status_code=400, detail="stream_steps must be 'true' if stream_tokens is 'true'")++ # For streaming response+ try:++ # Get the generator object off of the agent's streaming interface+ # This will be attached to the POST SSE request used under-the-hood+ memgpt_agent = server._get_or_load_agent(user_id=user_id, agent_id=agent_id)+ streaming_interface = memgpt_agent.interface+ if not isinstance(streaming_interface, StreamingServerInterface):+ raise ValueError(f"Agent has wrong type of interface: {type(streaming_interface)}")++ # Enable token-streaming within the request if desired+ streaming_interface.streaming_mode = stream_tokens+ # "chatcompletion mode" does some remapping and ignores inner thoughts+ streaming_interface.streaming_chat_completion_mode = chat_completion_mode++ # NOTE: for legacy 'stream' flag+ streaming_interface.nonstreaming_legacy_mode = stream_legacy+ # streaming_interface.allow_assistant_message = stream+ # streaming_interface.function_call_legacy_mode = stream++ # Offload the synchronous message_func to a separate thread+ streaming_interface.stream_start()+ task = asyncio.create_task(asyncio.to_thread(message_func, user_id=user_id, agent_id=agent_id, message=message))++ if stream_steps:+ # return a stream+ return StreamingResponse(+ sse_async_generator(streaming_interface.get_generator(), finish_message=include_final_message),+ media_type="text/event-stream",+ )+ else:+ # buffer the stream, then return the list+ generated_stream = []+ async for message in streaming_interface.get_generator():+ generated_stream.append(message)+ if "data" in message and message["data"] == "[DONE]":+ break+ filtered_stream = [d for d in generated_stream if d not in ["[DONE_GEN]", "[DONE_STEP]", "[DONE]"]]+ return UserMessageResponse(messages=filtered_stream)++ except HTTPException:+ raise+ except Exception as e:+ print(e)+ import traceback++ traceback.print_exc()+ raise HTTPException(status_code=500, detail=f"{e}")++def setup_agents_message_router(server: SyncServer, interface: QueuingInterface, password: str):get_current_user_with_server = partial(partial(get_current_user, server), password)@@ -118,6 +207,7 @@ def setup_agents_message_router(server: SyncServer, interface: QueuingInterface,@router.post("/agents/{agent_id}/messages", tags=["agents"], response_model=UserMessageResponse)async def send_message(+ # background_tasks: BackgroundTasks,agent_id: uuid.UUID,request: UserMessageRequest = Body(...),user_id: uuid.UUID = Depends(get_current_user_with_server),@@ -128,82 +218,16 @@ def setup_agents_message_router(server: SyncServer, interface: QueuingInterface,This endpoint accepts a message from a user and processes it through the agent.It can optionally stream the response if 'stream' is set to True."""-- if request.role == "user" or request.role is None:- message_func = server.user_message- elif request.role == "system":- message_func = server.system_message- else:- raise HTTPException(status_code=500, detail=f"Bad role {request.role}")-- def handle_exception(exception_loop: AbstractEventLoop, context):- # context["message"] will always be there; but context["exception"] may not- error = context.get("exception") or context["message"]- print(f"handling asyncio exception {context}")- interface.error(str(error))-- if request.stream:- # For streaming response- try:- # Start the generation process (similar to the non-streaming case)- # This should be a non-blocking call or run in a background task- # Check if server.user_message is an async function- if asyncio.iscoroutinefunction(message_func):- # Start the async task- await asyncio.create_task(- message_func(- user_id=user_id,- agent_id=agent_id,- message=request.message,- timestamp=request.timestamp,- )- )- else:-- # Run the synchronous function in a thread pool- loop = asyncio.get_event_loop()- loop.set_exception_handler(handle_exception)- loop.run_in_executor(- None,- message_func,- user_id,- agent_id,- request.message,- request.timestamp,- )-- async def formatted_message_generator():- async for message in interface.message_generator():- formatted_message = f"data: {json.dumps(message, ensure_ascii=JSON_ENSURE_ASCII)}\n\n"- yield formatted_message- await asyncio.sleep(1)-- # Return the streaming response using the generator- return StreamingResponse(formatted_message_generator(), media_type="text/event-stream")- except HTTPException:- raise- except Exception as e:- raise HTTPException(status_code=500, detail=f"{e}")-- else:- interface.clear()- try:- # message_func(user_id=user_id, agent_id=agent_id, message=request.message)- # call in thread pool to prevent blocking- loop = asyncio.get_event_loop()- loop.set_exception_handler(handle_exception)- task = loop.run_in_executor(- None,- message_func,- user_id,- agent_id,- request.message,- )- await task- except HTTPException:- raise- except Exception as e:- raise HTTPException(status_code=500, detail=str(e))- return UserMessageResponse(messages=interface.to_list())+ return await send_message_to_agent(+ server=server,+ agent_id=agent_id,+ user_id=user_id,+ role=request.role,+ message=request.message,+ stream_steps=request.stream_steps,+ stream_tokens=request.stream_tokens,+ # legacy+ stream_legacy=request.stream,+ )return routerdiff --git a/memgpt/server/rest_api/interface.py b/memgpt/server/rest_api/interface.pyindex 9edf4a101..f5711109a 100644--- a/memgpt/server/rest_api/interface.py+++ b/memgpt/server/rest_api/interface.py@@ -1,10 +1,14 @@import asyncio+import jsonimport queue-from typing import Optional+from collections import deque+from typing import AsyncGenerator, Optionalfrom memgpt.data_types import Messagefrom memgpt.interface import AgentInterface-from memgpt.utils import is_utc_datetime+from memgpt.models.chat_completion_response import ChatCompletionChunkResponse+from memgpt.streaming_interface import AgentChunkStreamingInterface+from memgpt.utils import get_utc_time, is_utc_datetimeclass QueuingInterface(AgentInterface):@@ -47,6 +51,10 @@ class QueuingInterface(AgentInterface):"""Enqueue a special stop message"""self.buffer.put("STOP")+ @staticmethod+ def step_complete():+ pass+def error(self, error: str):"""Enqueue a special stop message"""self.buffer.put({"internal_error": error})@@ -145,3 +153,413 @@ class QueuingInterface(AgentInterface):new_message["date"] = msg_obj.created_at.isoformat()self.buffer.put(new_message)+++class FunctionArgumentsStreamHandler:+ """State machine that can process a stream of"""++ def __init__(self, json_key="message"):+ self.json_key = json_key+ self.reset()++ def reset(self):+ self.in_message = False+ self.key_buffer = ""+ self.accumulating = False+ self.message_started = False++ def process_json_chunk(self, chunk: str) -> Optional[str]:+ """Process a chunk from the function arguments and return the plaintext version"""++ # Use strip to handle only leading and trailing whitespace in control structures+ if self.accumulating:+ clean_chunk = chunk.strip()+ if self.json_key in self.key_buffer:+ if ":" in clean_chunk:+ self.in_message = True+ self.accumulating = False+ return None+ self.key_buffer += clean_chunk+ return None++ if self.in_message:+ if chunk.strip() == '"' and self.message_started:+ self.in_message = False+ self.message_started = False+ return None+ if not self.message_started and chunk.strip() == '"':+ self.message_started = True+ return None+ if self.message_started:+ if chunk.strip().endswith('"'):+ self.in_message = False+ return chunk.rstrip('"\n')+ return chunk++ if chunk.strip() == "{":+ self.key_buffer = ""+ self.accumulating = True+ return None+ if chunk.strip() == "}":+ self.in_message = False+ self.message_started = False+ return None+ return None+++class StreamingServerInterface(AgentChunkStreamingInterface):+ """Maintain a generator that is a proxy for self.process_chunk()++ Usage:+ - The main POST SSE code that launches the streaming request+ will call .process_chunk with each incoming stream (as a handler)+ -++ NOTE: this interface is SINGLE THREADED, and meant to be used+ with a single agent. A multi-agent implementation of this interface+ should maintain multiple generators and index them with the request ID+ """++ def __init__(self, multi_step=True):+ # If streaming mode, ignores base interface calls like .assistant_message, etc+ self.streaming_mode = False+ # NOTE: flag for supporting legacy 'stream' flag where send_message is treated specially+ self.nonstreaming_legacy_mode = False+ # If chat completion mode, creates a "chatcompletion-style" stream, but with concepts remapped+ self.streaming_chat_completion_mode = False+ self.streaming_chat_completion_mode_function_name = None # NOTE: sadly need to track state during stream+ # If chat completion mode, we need a special stream reader to+ # turn function argument to send_message into a normal text stream+ self.streaming_chat_completion_json_reader = FunctionArgumentsStreamHandler()++ self._chunks = deque()+ self._event = asyncio.Event() # Use an event to notify when chunks are available+ self._active = True # This should be set to False to stop the generator++ # if multi_step = True, the stream ends when the agent yields+ # if multi_step = False, the stream ends when the step ends+ self.multi_step = multi_step+ self.multi_step_indicator = "[DONE_STEP]"+ self.multi_step_gen_indicator = "[DONE_GEN]"++ async def _create_generator(self) -> AsyncGenerator:+ """An asynchronous generator that yields chunks as they become available."""+ while self._active:+ # Wait until there is an item in the deque or the stream is deactivated+ await self._event.wait()++ while self._chunks:+ yield self._chunks.popleft()++ # Reset the event until a new item is pushed+ self._event.clear()++ def stream_start(self):+ """Initialize streaming by activating the generator and clearing any old chunks."""+ self.streaming_chat_completion_mode_function_name = None++ if not self._active:+ self._active = True+ self._chunks.clear()+ self._event.clear()++ def stream_end(self):+ """Clean up the stream by deactivating and clearing chunks."""+ self.streaming_chat_completion_mode_function_name = None++ if not self.streaming_chat_completion_mode and not self.nonstreaming_legacy_mode:+ self._chunks.append(self.multi_step_gen_indicator)+ self._event.set() # Signal that new data is available++ # if not self.multi_step:+ # # end the stream+ # self._active = False+ # self._event.set() # Unblock the generator if it's waiting to allow it to complete+ # else:+ # # signal that a new step has started in the stream+ # self._chunks.append(self.multi_step_indicator)+ # self._event.set() # Signal that new data is available++ def _process_chunk_to_memgpt_style(self, chunk: ChatCompletionChunkResponse) -> Optional[dict]:+ """+ Example data from non-streaming response looks like:++ data: {"function_call": "send_message({'message': \"Ah, the age-old question, Chad. The meaning of life is as subjective as the life itself. 42, as the supercomputer 'Deep Thought' calculated in 'The Hitchhiker's Guide to the Galaxy', is indeed an answer, but maybe not the one we're after. Among other things, perhaps life is about learning, experiencing and connecting. What are your thoughts, Chad? What gives your life meaning?\"})", "date": "2024-02-29T06:07:48.844733+00:00"}++ data: {"assistant_message": "Ah, the age-old question, Chad. The meaning of life is as subjective as the life itself. 42, as the supercomputer 'Deep Thought' calculated in 'The Hitchhiker's Guide to the Galaxy', is indeed an answer, but maybe not the one we're after. Among other things, perhaps life is about learning, experiencing and connecting. What are your thoughts, Chad? What gives your life meaning?", "date": "2024-02-29T06:07:49.846280+00:00"}++ data: {"function_return": "None", "status": "success", "date": "2024-02-29T06:07:50.847262+00:00"}+ """+ choice = chunk.choices[0]+ message_delta = choice.delta++ # inner thoughts+ if message_delta.content is not None:+ processed_chunk = {+ "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]++ tool_call_delta = {}+ if tool_call.id:+ tool_call_delta["id"] = tool_call.id+ if tool_call.function:+ if tool_call.function.arguments:+ tool_call_delta["arguments"] = tool_call.function.arguments+ if tool_call.function.name:+ tool_call_delta["name"] = tool_call.function.name++ processed_chunk = {+ "function_call": tool_call_delta,+ }+ elif choice.finish_reason is not None:+ # skip if there's a finish+ return None+ else:+ raise ValueError(f"Couldn't find delta in chunk: {chunk}")++ processed_chunk["date"] = chunk.created.isoformat()++ return processed_chunk++ def _process_chunk_to_openai_style(self, chunk: ChatCompletionChunkResponse) -> Optional[dict]:+ """Chunks should look like OpenAI, but be remapped from MemGPT-style concepts.++ inner_thoughts are silenced:+ - means that 'content' -> /dev/null+ send_message is a "message"+ - means that tool call to "send_message" should map to 'content'++ TODO handle occurance of multi-step function calling+ TODO handle partial stream of "name" in tool call+ """+ proxy_chunk = chunk.model_copy(deep=True)++ choice = chunk.choices[0]+ message_delta = choice.delta++ # inner thoughts+ if message_delta.content is not None:+ # skip inner monologue+ return None++ # tool call+ elif message_delta.tool_calls is not None and len(message_delta.tool_calls) > 0:+ tool_call = message_delta.tool_calls[0]++ if tool_call.function:++ # Track the function name while streaming+ # If we were previously on a 'send_message', we need to 'toggle' into 'content' mode+ if tool_call.function.name:+ if self.streaming_chat_completion_mode_function_name is None:+ self.streaming_chat_completion_mode_function_name = tool_call.function.name+ else:+ self.streaming_chat_completion_mode_function_name += tool_call.function.name++ if tool_call.function.name == "send_message":+ # early exit to turn into content mode+ self.streaming_chat_completion_json_reader.reset()+ return None++ if tool_call.function.arguments:+ if self.streaming_chat_completion_mode_function_name == "send_message":+ cleaned_func_args = self.streaming_chat_completion_json_reader.process_json_chunk(tool_call.function.arguments)+ if cleaned_func_args is None:+ return None+ else:+ # Wipe tool call+ proxy_chunk.choices[0].delta.tool_calls = None+ # Replace with 'content'+ proxy_chunk.choices[0].delta.content = cleaned_func_args++ processed_chunk = proxy_chunk.model_dump_json(exclude_none=True)++ return processed_chunk++ def process_chunk(self, chunk: ChatCompletionChunkResponse, msg_obj: Optional[Message] = None):+ """Process a streaming chunk from an OpenAI-compatible server.++ Example data from non-streaming response looks like:++ data: {"function_call": "send_message({'message': \"Ah, the age-old question, Chad. The meaning of life is as subjective as the life itself. 42, as the supercomputer 'Deep Thought' calculated in 'The Hitchhiker's Guide to the Galaxy', is indeed an answer, but maybe not the one we're after. Among other things, perhaps life is about learning, experiencing and connecting. What are your thoughts, Chad? What gives your life meaning?\"})", "date": "2024-02-29T06:07:48.844733+00:00"}++ data: {"assistant_message": "Ah, the age-old question, Chad. The meaning of life is as subjective as the life itself. 42, as the supercomputer 'Deep Thought' calculated in 'The Hitchhiker's Guide to the Galaxy', is indeed an answer, but maybe not the one we're after. Among other things, perhaps life is about learning, experiencing and connecting. What are your thoughts, Chad? What gives your life meaning?", "date": "2024-02-29T06:07:49.846280+00:00"}++ data: {"function_return": "None", "status": "success", "date": "2024-02-29T06:07:50.847262+00:00"}+ """+ # print("Processed CHUNK:", chunk)++ # Example where we just pass through the raw stream from the underlying OpenAI SSE stream+ # processed_chunk = chunk.model_dump_json(exclude_none=True)++ if self.streaming_chat_completion_mode:+ processed_chunk = self._process_chunk_to_openai_style(chunk)+ else:+ processed_chunk = self._process_chunk_to_memgpt_style(chunk)++ if processed_chunk is None:+ return++ if msg_obj:+ processed_chunk["id"] = str(msg_obj.id)++ self._chunks.append(processed_chunk)+ self._event.set() # Signal that new data is available++ def get_generator(self) -> AsyncGenerator:+ """Get the generator that yields processed chunks."""+ if not self._active:+ # If the stream is not active, don't return a generator that would produce values+ raise StopIteration("The stream has not been started or has been ended.")+ return self._create_generator()++ def user_message(self, msg: str, msg_obj: Optional[Message] = None):+ """MemGPT receives a user message"""+ return++ def internal_monologue(self, msg: str, msg_obj: Optional[Message] = None):+ """MemGPT generates some internal monologue"""+ if not self.streaming_mode:++ # create a fake "chunk" of a stream+ processed_chunk = {+ "internal_monologue": msg,+ "date": msg_obj.created_at.isoformat() if msg_obj is not None else get_utc_time().isoformat(),+ "id": str(msg_obj.id) if msg_obj is not None else None,+ }++ self._chunks.append(processed_chunk)+ self._event.set() # Signal that new data is available++ return++ def assistant_message(self, msg: str, msg_obj: Optional[Message] = None):+ """MemGPT uses send_message"""++ # if not self.streaming_mode and self.send_message_special_case:++ # # create a fake "chunk" of a stream+ # processed_chunk = {+ # "assistant_message": msg,+ # "date": msg_obj.created_at.isoformat() if msg_obj is not None else get_utc_time().isoformat(),+ # "id": str(msg_obj.id) if msg_obj is not None else None,+ # }++ # self._chunks.append(processed_chunk)+ # self._event.set() # Signal that new data is available++ return++ def function_message(self, msg: str, msg_obj: Optional[Message] = None):+ """MemGPT calls a function"""++ # TODO handle 'function' messages that indicate the start of a function call+ assert msg_obj is not None, "StreamingServerInterface requires msg_obj references for metadata"++ if msg.startswith("Running "):+ if not self.streaming_mode:+ # create a fake "chunk" of a stream+ function_call = msg_obj.tool_calls[0]++ if self.nonstreaming_legacy_mode:+ # Special case where we want to send two chunks - one first for the function call, then for send_message++ # Should be in the following legacy style:+ # data: {+ # "function_call": "send_message({'message': 'Chad, ... ask?'})",+ # "id": "771748ee-120a-453a-960d-746570b22ee5",+ # "date": "2024-06-22T23:04:32.141923+00:00"+ # }+ try:+ func_args = json.loads(function_call.function["arguments"])+ except:+ func_args = function_call.function["arguments"]+ processed_chunk = {+ "function_call": f"{function_call.function['name']}({func_args})",+ "id": str(msg_obj.id),+ "date": msg_obj.created_at.isoformat(),+ }+ self._chunks.append(processed_chunk)+ self._event.set() # Signal that new data is available++ if function_call.function["name"] == "send_message":+ try:+ processed_chunk = {+ "assistant_message": func_args["message"],+ "id": str(msg_obj.id),+ "date": msg_obj.created_at.isoformat(),+ }+ self._chunks.append(processed_chunk)+ self._event.set() # Signal that new data is available+ except Exception as e:+ print(f"Failed to parse function message: {e}")++ else:++ processed_chunk = {+ "function_call": {+ # "id": function_call.id,+ "name": function_call.function["name"],+ "arguments": function_call.function["arguments"],+ },+ "id": str(msg_obj.id),+ "date": msg_obj.created_at.isoformat(),+ }+ self._chunks.append(processed_chunk)+ self._event.set() # Signal that new data is available++ return+ else:+ return+ # msg = msg.replace("Running ", "")+ # new_message = {"function_call": msg}++ elif msg.startswith("Ran "):+ return+ # msg = msg.replace("Ran ", "Function call returned: ")+ # new_message = {"function_call": msg}++ elif msg.startswith("Success: "):+ msg = msg.replace("Success: ", "")+ new_message = {"function_return": msg, "status": "success"}++ elif msg.startswith("Error: "):+ msg = msg.replace("Error: ", "")+ new_message = {"function_return": msg, "status": "error"}++ else:+ # NOTE: generic, should not happen+ new_message = {"function_message": msg}++ # add extra metadata+ if msg_obj is not None:+ new_message["id"] = str(msg_obj.id)+ assert is_utc_datetime(msg_obj.created_at), msg_obj.created_at+ new_message["date"] = msg_obj.created_at.isoformat()++ self._chunks.append(new_message)+ self._event.set() # Signal that new data is available++ def step_complete(self):+ """Signal from the agent that one 'step' finished (step = LLM response + tool execution)"""+ if not self.multi_step:+ # end the stream+ self._active = False+ self._event.set() # Unblock the generator if it's waiting to allow it to complete+ elif not self.streaming_chat_completion_mode and not self.nonstreaming_legacy_mode:+ # signal that a new step has started in the stream+ self._chunks.append(self.multi_step_indicator)+ self._event.set() # Signal that new data is available++ def step_yield(self):+ """If multi_step, this is the true 'stream_end' function."""+ if self.multi_step:+ # end the stream+ self._active = False+ self._event.set() # Unblock the generator if it's waiting to allow it to complete++ @staticmethod+ def clear():+ returndiff --git a/memgpt/server/rest_api/openai_chat_completions/chat_completions.py b/memgpt/server/rest_api/openai_chat_completions/chat_completions.pynew file mode 100644index 000000000..c4cd4ae72--- /dev/null+++ b/memgpt/server/rest_api/openai_chat_completions/chat_completions.py@@ -0,0 +1,127 @@+import json+import uuid+from functools import partial++from fastapi import APIRouter, Body, Depends, HTTPException++# from memgpt.data_types import Message+from memgpt.models.chat_completion_request import ChatCompletionRequest+from memgpt.models.chat_completion_response import (+ ChatCompletionResponse,+ Choice,+ Message,+ UsageStatistics,+)+from memgpt.server.rest_api.agents.message import send_message_to_agent+from memgpt.server.rest_api.auth_token import get_current_user+from memgpt.server.rest_api.interface import QueuingInterface+from memgpt.server.server import SyncServer+from memgpt.utils import get_utc_time++router = APIRouter()+++def setup_openai_chat_completions_router(server: SyncServer, interface: QueuingInterface, password: str):+ get_current_user_with_server = partial(partial(get_current_user, server), password)++ @router.post("/chat/completions", tags=["chat_completions"], response_model=ChatCompletionResponse)+ async def create_chat_completion(+ request: ChatCompletionRequest = Body(...),+ user_id: uuid.UUID = Depends(get_current_user_with_server),+ ):+ """Send a message to a MemGPT agent via a /chat/completions request++ The bearer token will be used to identify the user.+ The 'user' field in the request should be set to the agent ID.+ """+ agent_id = request.user+ if agent_id is None:+ raise HTTPException(status_code=400, detail="Must pass agent_id in the 'user' field")+ try:+ agent_id = uuid.UUID(agent_id)+ except:+ raise HTTPException(status_code=400, detail="agent_id (in the 'user' field) must be a valid UUID")++ messages = request.messages+ if messages is None:+ raise HTTPException(status_code=400, detail="'messages' field must not be empty")+ if len(messages) > 1:+ raise HTTPException(status_code=400, detail="'messages' field must be a list of length 1")+ if messages[0].role != "user":+ raise HTTPException(status_code=400, detail="'messages[0].role' must be a 'user'")++ input_message = request.messages[0]+ if request.stream:+ print("Starting streaming OpenAI proxy response")++ return await send_message_to_agent(+ server=server,+ agent_id=agent_id,+ user_id=user_id,+ role=input_message.role,+ message=input_message.content,+ # Turn streaming ON+ stream_steps=True,+ stream_tokens=True,+ # Turn on ChatCompletion mode (eg remaps send_message to content)+ chat_completion_mode=True,+ )++ else:+ print("Starting non-streaming OpenAI proxy response")++ response_messages = await send_message_to_agent(+ server=server,+ agent_id=agent_id,+ user_id=user_id,+ role=input_message.role,+ message=input_message.content,+ # Turn streaming OFF+ stream_steps=False,+ stream_tokens=False,+ )+ # print(response_messages)++ # Concatenate all send_message outputs together+ id = ""+ visible_message_str = ""+ created_at = None+ for memgpt_msg in response_messages.messages:+ if "function_call" in memgpt_msg:+ memgpt_function_call = memgpt_msg["function_call"]+ if "name" in memgpt_function_call and memgpt_function_call["name"] == "send_message":+ try:+ memgpt_function_call_args = json.loads(memgpt_function_call["arguments"])+ visible_message_str += memgpt_function_call_args["message"]+ id = memgpt_function_call["id"]+ created_at = memgpt_msg["date"]+ except:+ print(f"Failed to parse MemGPT message: {str(memgpt_function_call)}")+ else:+ print(f"Skipping function_call: {str(memgpt_function_call)}")+ else:+ print(f"Skipping message: {str(memgpt_msg)}")++ response = ChatCompletionResponse(+ id=id,+ created=created_at if created_at else get_utc_time(),+ choices=[+ Choice(+ finish_reason="stop",+ index=0,+ message=Message(+ role="assistant",+ content=visible_message_str,+ ),+ )+ ],+ # TODO add real usage+ usage=UsageStatistics(+ completion_tokens=0,+ prompt_tokens=0,+ total_tokens=0,+ ),+ )+ return response++ return routerdiff --git a/memgpt/server/rest_api/server.py b/memgpt/server/rest_api/server.pyindex d4dccf42c..a34be5f46 100644--- a/memgpt/server/rest_api/server.py+++ b/memgpt/server/rest_api/server.py@@ -22,11 +22,14 @@ from memgpt.server.rest_api.agents.message import setup_agents_message_routerfrom memgpt.server.rest_api.auth.index import setup_auth_routerfrom memgpt.server.rest_api.config.index import setup_config_index_routerfrom memgpt.server.rest_api.humans.index import setup_humans_index_router-from memgpt.server.rest_api.interface import QueuingInterface+from memgpt.server.rest_api.interface import StreamingServerInterfacefrom memgpt.server.rest_api.models.index import setup_models_index_routerfrom memgpt.server.rest_api.openai_assistants.assistants import (setup_openai_assistant_router,)+from memgpt.server.rest_api.openai_chat_completions.chat_completions import (+ setup_openai_chat_completions_router,+)from memgpt.server.rest_api.personas.index import setup_personas_index_routerfrom memgpt.server.rest_api.presets.index import setup_presets_index_routerfrom memgpt.server.rest_api.sources.index import setup_sources_index_router@@ -43,8 +46,10 @@ Start the server with:poetry run uvicorn server:app --reload"""-interface: QueuingInterface = QueuingInterface()-server: SyncServer = SyncServer(default_interface=interface)+# interface: QueuingInterface = QueuingInterface()+# interface: StreamingServerInterface = StreamingServerInterface()+interface: StreamingServerInterface = StreamingServerInterface+server: SyncServer = SyncServer(default_interface_factory=lambda: interface())if password := settings.server_pass:# if the pass was specified in the environment, use it@@ -103,6 +108,9 @@ app.include_router(setup_config_index_router(server, interface, password), prefi# /v1/assistants endpointsapp.include_router(setup_openai_assistant_router(server, interface), prefix=OPENAI_API_PREFIX)+# /v1/chat/completions endpoints+app.include_router(setup_openai_chat_completions_router(server, interface, password), prefix=OPENAI_API_PREFIX)+# / static filesmount_static_files(app)diff --git a/memgpt/server/rest_api/utils.py b/memgpt/server/rest_api/utils.pynew file mode 100644index 000000000..45a4ab3ce--- /dev/null+++ b/memgpt/server/rest_api/utils.py@@ -0,0 +1,60 @@+import asyncio+import json+import traceback+from typing import AsyncGenerator, Generator, Union++from memgpt.constants import JSON_ENSURE_ASCII++SSE_FINISH_MSG = "[DONE]" # mimic openai+SSE_ARTIFICIAL_DELAY = 0.1+++def sse_formatter(data: Union[dict, str]) -> str:+ """Prefix with 'data: ', and always include double newlines"""+ assert type(data) in [dict, str], f"Expected type dict or str, got type {type(data)}"+ data_str = json.dumps(data, ensure_ascii=JSON_ENSURE_ASCII) if isinstance(data, dict) else data+ return f"data: {data_str}\n\n"+++async def sse_generator(generator: Generator[dict, None, None]) -> Generator[str, None, None]:+ """Generator that returns 'data: dict' formatted items, e.g.:++ data: {"id":"chatcmpl-9E0PdSZ2IBzAGlQ3SEWHJ5YwzucSP","object":"chat.completion.chunk","created":1713125205,"model":"gpt-4-0613","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"}"}}]},"logprobs":null,"finish_reason":null}]}++ data: {"id":"chatcmpl-9E0PdSZ2IBzAGlQ3SEWHJ5YwzucSP","object":"chat.completion.chunk","created":1713125205,"model":"gpt-4-0613","system_fingerprint":null,"choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]}++ data: [DONE]++ """+ try:+ for msg in generator:+ yield sse_formatter(msg)+ if SSE_ARTIFICIAL_DELAY:+ await asyncio.sleep(SSE_ARTIFICIAL_DELAY) # Sleep to prevent a tight loop, adjust time as needed+ except Exception as e:+ yield sse_formatter({"error": f"{str(e)}"})+ yield sse_formatter(SSE_FINISH_MSG) # Signal that the stream is complete+++async def sse_async_generator(generator: AsyncGenerator, finish_message=True):+ """+ Wraps a generator for use in Server-Sent Events (SSE), handling errors and ensuring a completion message.++ Args:+ - generator: An asynchronous generator yielding data chunks.++ Yields:+ - Formatted Server-Sent Event strings.+ """+ try:+ async for chunk in generator:+ # yield f"data: {json.dumps(chunk)}\n\n"+ yield sse_formatter(chunk)+ except Exception as e:+ print("stream decoder hit error:", e)+ print(traceback.print_stack())+ yield sse_formatter({"error": "stream decoder encountered an error"})+ finally:+ # yield "data: [DONE]\n\n"+ if finish_message:+ yield sse_formatter(SSE_FINISH_MSG) # Signal that the stream is completediff --git a/memgpt/server/server.py b/memgpt/server/server.pyindex 3c491ea8d..1912f1cc9 100644--- a/memgpt/server/server.py+++ b/memgpt/server/server.py@@ -163,8 +163,8 @@ class SyncServer(LockingServer):self,chaining: bool = True,max_chaining_steps: bool = None,- # default_interface_cls: AgentInterface = CLIInterface,- default_interface: AgentInterface = CLIInterface(),+ default_interface_factory: Callable[[], AgentInterface] = lambda: CLIInterface(),+ # default_interface: AgentInterface = CLIInterface(),# default_persistence_manager_cls: PersistenceManager = LocalStateManager,# auth_mode: str = "none", # "none, "jwt", "external"):@@ -201,8 +201,9 @@ class SyncServer(LockingServer):self.max_chaining_steps = max_chaining_steps# The default interface that will get assigned to agents ON LOAD- # self.default_interface_cls = default_interface_cls- self.default_interface = default_interface+ self.default_interface_factory = default_interface_factory+ # self.default_interface = default_interface+ # self.default_interface = default_interface_cls()# The default persistence manager that will get assigned to agents ON CREATION# self.default_persistence_manager_cls = default_persistence_manager_cls@@ -321,7 +322,7 @@ class SyncServer(LockingServer):# If an interface isn't specified, use the defaultif interface is None:- interface = self.default_interface+ interface = self.default_interface_factory()try:logger.info(f"Grabbing agent user_id={user_id} agent_id={agent_id} from database")@@ -365,6 +366,9 @@ class SyncServer(LockingServer):if memgpt_agent is None:raise KeyError(f"Agent (user={user_id}, agent={agent_id}) is not loaded")+ # Determine whether or not to token stream based on the capability of the interface+ token_streaming = memgpt_agent.interface.streaming_mode if hasattr(memgpt_agent.interface, "streaming_mode") else False+logger.debug(f"Starting agent step")no_verify = Truenext_input_message = input_message@@ -375,8 +379,10 @@ class SyncServer(LockingServer):first_message=False,skip_verify=no_verify,return_dicts=False,+ stream=token_streaming,)counter += 1+ memgpt_agent.interface.step_complete()# Chain stopsif not self.chaining:@@ -523,7 +529,11 @@ class SyncServer(LockingServer):# @LockingServer.agent_lock_decoratordef user_message(- self, user_id: uuid.UUID, agent_id: uuid.UUID, message: Union[str, Message], timestamp: Optional[datetime] = None+ self,+ user_id: uuid.UUID,+ agent_id: uuid.UUID,+ message: Union[str, Message],+ timestamp: Optional[datetime] = None,) -> None:"""Process an incoming user message and feed it through the MemGPT agent"""if self.ms.get_user(user_id=user_id) is None:@@ -572,7 +582,11 @@ class SyncServer(LockingServer):# @LockingServer.agent_lock_decoratordef system_message(- self, user_id: uuid.UUID, agent_id: uuid.UUID, message: Union[str, Message], timestamp: Optional[datetime] = None+ self,+ user_id: uuid.UUID,+ agent_id: uuid.UUID,+ message: Union[str, Message],+ timestamp: Optional[datetime] = None,) -> None:"""Process an incoming system message and feed it through the MemGPT agent"""if self.ms.get_user(user_id=user_id) is None:@@ -673,8 +687,8 @@ class SyncServer(LockingServer):raise ValueError(f"User user_id={user_id} does not exist")if interface is None:- # interface = self.default_interface_cls()- interface = self.default_interface+ # interface = self.default_interface+ interface = self.default_interface_factory()# if persistence_manager is None:# persistence_manager = self.default_persistence_manager_cls(agent_config=agent_config)