Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: Update REST API (#647)
Charles Packer83973ecfc874
diff --git a/memgpt/server/rest_api/agents/command.py b/memgpt/server/rest_api/agents/command.pyindex 5c3ca40f8..381d565ed 100644--- a/memgpt/server/rest_api/agents/command.py+++ b/memgpt/server/rest_api/agents/command.py@@ -1,6 +1,5 @@-from fastapi import APIRouter, HTTPException--from pydantic import BaseModel+from fastapi import APIRouter, Body, HTTPException+from pydantic import BaseModel, Fieldfrom memgpt.server.rest_api.interface import QueuingInterfacefrom memgpt.server.server import SyncServer@@ -8,22 +7,33 @@ from memgpt.server.server import SyncServerrouter = APIRouter()-class Command(BaseModel):- user_id: str- agent_id: str- command: str+class CommandRequest(BaseModel):+ user_id: str = Field(..., description="Unique identifier of the user issuing the command.")+ agent_id: str = Field(..., description="Identifier of the agent on which the command will be executed.")+ command: str = Field(..., description="The command to be executed by the agent.")+++class CommandResponse(BaseModel):+ response: str = Field(..., description="The result of the executed command.")def setup_agents_command_router(server: SyncServer, interface: QueuingInterface):- @router.post("/agents/command")- def run_command(body: Command):+ @router.post("/agents/command", tags=["agents"], response_model=CommandResponse)+ def run_command(request: CommandRequest = Body(...)):+ """+ Execute a command on a specified agent.++ This endpoint receives a command to be executed on an agent. It uses the user and agent identifiers to authenticate and route the command appropriately.++ Raises an HTTPException for any processing errors.+ """interface.clear()try:- response = server.run_command(user_id=body.user_id, agent_id=body.agent_id, command=body.command)+ response = server.run_command(user_id=request.user_id, agent_id=request.agent_id, command=request.command)except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=f"{e}")- return {"response": response}+ return CommandResponse(response=response)return routerdiff --git a/memgpt/server/rest_api/agents/config.py b/memgpt/server/rest_api/agents/config.pyindex 7f38e07e9..5ca17caf4 100644--- a/memgpt/server/rest_api/agents/config.py+++ b/memgpt/server/rest_api/agents/config.py@@ -1,4 +1,5 @@-from fastapi import APIRouter+from fastapi import APIRouter, Depends+from pydantic import BaseModel, Fieldfrom memgpt.server.rest_api.interface import QueuingInterfacefrom memgpt.server.server import SyncServer@@ -6,10 +7,25 @@ from memgpt.server.server import SyncServerrouter = APIRouter()+class AgentConfigRequest(BaseModel):+ user_id: str = Field(..., description="Unique identifier of the user issuing the command.")+ agent_id: str = Field(..., description="Identifier of the agent on which the command will be executed.")+++class AgentConfigResponse(BaseModel):+ config: dict = Field(..., description="The agent configuration object.")++def setup_agents_config_router(server: SyncServer, interface: QueuingInterface):- @router.get("/agents/config")- def get_agent_config(user_id: str, agent_id: str):+ @router.get("/agents/config", tags=["agents"], response_model=AgentConfigResponse)+ def get_agent_config(request: AgentConfigRequest = Depends()):+ """+ Retrieve the configuration for a specific agent.++ This endpoint fetches the configuration details for a given agent, identified by the user and agent IDs.+ """interface.clear()- return server.get_agent_config(user_id=user_id, agent_id=agent_id)+ config = server.get_agent_config(user_id=request.user_id, agent_id=request.agent_id)+ return AgentConfigResponse(config=config)return routerdiff --git a/memgpt/server/rest_api/agents/index.py b/memgpt/server/rest_api/agents/index.pyindex ca00c1bd3..3da201063 100644--- a/memgpt/server/rest_api/agents/index.py+++ b/memgpt/server/rest_api/agents/index.py@@ -1,6 +1,7 @@-from fastapi import APIRouter, HTTPException+from typing import List-from pydantic import BaseModel+from fastapi import APIRouter, Depends, Body, HTTPException+from pydantic import BaseModel, Fieldfrom memgpt.server.rest_api.interface import QueuingInterfacefrom memgpt.server.server import SyncServer@@ -8,24 +9,46 @@ from memgpt.server.server import SyncServerrouter = APIRouter()-class CreateAgentConfig(BaseModel):- user_id: str- config: dict+class ListAgentsRequest(BaseModel):+ user_id: str = Field(..., description="Unique identifier of the user.")+++class ListAgentsResponse(BaseModel):+ num_agents: int = Field(..., description="The number of agents available to the user.")+ agents: List[dict] = Field(..., description="List of agent configurations.")+++class CreateAgentRequest(BaseModel):+ user_id: str = Field(..., description="Unique identifier of the user issuing the command.")+ config: dict = Field(..., description="The agent configuration object.")+++class CreateAgentResponse(BaseModel):+ agent_id: str = Field(..., description="Unique identifier of the newly created agent.")def setup_agents_index_router(server: SyncServer, interface: QueuingInterface):- @router.get("/agents", tags=["agents"])- def list_agents(user_id: str):- interface.clear()- return server.list_agents(user_id=user_id)+ @router.get("/agents", tags=["agents"], response_model=ListAgentsResponse)+ def list_agents(request: ListAgentsRequest = Depends()):+ """+ List all agents associated with a given user.- @router.post("/agents")- def create_agent(body: CreateAgentConfig):+ This endpoint retrieves a list of all agents and their configurations associated with the specified user ID.+ """+ interface.clear()+ agents_data = server.list_agents(user_id=request.user_id)+ return ListAgentsResponse(**agents_data)++ @router.post("/agents", tags=["agents"], response_model=CreateAgentResponse)+ def create_agent(request: CreateAgentRequest = Body(...)):+ """+ Create a new agent with the specified configuration.+ """interface.clear()try:- agent_id = server.create_agent(user_id=body.user_id, agent_config=body.config)+ agent_id = server.create_agent(user_id=request.user_id, agent_config=request.config)+ return CreateAgentResponse(agent_id=agent_id)except Exception as e:- raise HTTPException(status_code=500, detail=f"{e}")- return {"agent_id": agent_id}+ raise HTTPException(status_code=500, detail=str(e))return routerdiff --git a/memgpt/server/rest_api/agents/memory.py b/memgpt/server/rest_api/agents/memory.pyindex d66c0b502..416d109dd 100644--- a/memgpt/server/rest_api/agents/memory.py+++ b/memgpt/server/rest_api/agents/memory.py@@ -1,5 +1,7 @@-from fastapi import APIRouter-from pydantic import BaseModel+from typing import Optional++from fastapi import APIRouter, Depends, Body+from pydantic import BaseModel, Fieldfrom memgpt.server.rest_api.interface import QueuingInterfacefrom memgpt.server.server import SyncServer@@ -8,22 +10,58 @@ router = APIRouter()class CoreMemory(BaseModel):- user_id: str- agent_id: str- human: str | None = None- persona: str | None = None+ human: str | None = Field(None, description="Human element of the core memory.")+ persona: str | None = Field(None, description="Persona element of the core memory.")+++class GetAgentMemoryRequest(BaseModel):+ user_id: str = Field(..., description="The unique identifier of the user.")+ agent_id: str = Field(..., description="The unique identifier of the agent.")+++class GetAgentMemoryResponse(BaseModel):+ core_memory: CoreMemory = Field(..., description="The state of the agent's core memory.")+ recall_memory: int = Field(..., description="Size of the agent's recall memory.")+ archival_memory: int = Field(..., description="Size of the agent's archival memory.")+++# NOTE not subclassing CoreMemory since in the request both field are optional+class UpdateAgentMemoryRequest(BaseModel):+ user_id: str = Field(..., description="The unique identifier of the user.")+ agent_id: str = Field(..., description="The unique identifier of the agent.")+ human: Optional[str] = Field(None, description="Human element of the core memory.")+ persona: Optional[str] = Field(None, description="Persona element of the core memory.")+++class UpdateAgentMemoryResponse(BaseModel):+ old_core_memory: CoreMemory = Field(..., description="The previous state of the agent's core memory.")+ new_core_memory: CoreMemory = Field(..., description="The updated state of the agent's core memory.")def setup_agents_memory_router(server: SyncServer, interface: QueuingInterface):- @router.get("/agents/memory")- def get_agent_memory(user_id: str, agent_id: str):+ @router.get("/agents/memory", tags=["agents"], response_model=GetAgentMemoryResponse)+ def get_agent_memory(request: GetAgentMemoryRequest = Depends()):+ """+ Retrieve the memory state of a specific agent.++ This endpoint fetches the current memory state of the agent identified by the user ID and agent ID.+ """interface.clear()- return server.get_agent_memory(user_id=user_id, agent_id=agent_id)+ memory = server.get_agent_memory(user_id=request.user_id, agent_id=request.agent_id)+ return GetAgentMemoryResponse(**memory)++ @router.post("/agents/memory", tags=["agents"], response_model=UpdateAgentMemoryResponse)+ def update_agent_memory(request: UpdateAgentMemoryRequest = Body(...)):+ """+ Update the core memory of a specific agent.- @router.post("/agents/memory")- def get_agent_memory(body: CoreMemory):+ This endpoint accepts new memory contents (human and persona) and updates the core memory of the agent identified by the user ID and agent ID.+ """interface.clear()- new_memory_contents = {"persona": body.persona, "human": body.human}- return server.update_agent_core_memory(user_id=body.user_id, agent_id=body.agent_id, new_memory_contents=new_memory_contents)+ new_memory_contents = {"persona": request.persona, "human": request.human}+ response = server.update_agent_core_memory(+ user_id=request.user_id, agent_id=request.agent_id, new_memory_contents=new_memory_contents+ )+ return UpdateAgentMemoryResponse(**response)return routerdiff --git a/memgpt/server/rest_api/agents/message.py b/memgpt/server/rest_api/agents/message.pyindex ba1f289d3..f0c6a7ad9 100644--- a/memgpt/server/rest_api/agents/message.py+++ b/memgpt/server/rest_api/agents/message.py@@ -1,8 +1,9 @@import asyncioimport json+from typing import List-from fastapi import APIRouter, HTTPException-from pydantic import BaseModel+from fastapi import APIRouter, Depends, Body, HTTPException+from pydantic import BaseModel, Fieldfrom starlette.responses import StreamingResponsefrom memgpt.server.rest_api.interface import QueuingInterface@@ -11,17 +12,27 @@ from memgpt.server.server import SyncServerrouter = APIRouter()-class UserMessage(BaseModel):- user_id: str- agent_id: str- message: str- stream: bool = False+class UserMessageRequest(BaseModel):+ user_id: str = Field(..., description="The unique identifier of the user.")+ agent_id: str = Field(..., description="The unique identifier of the agent.")+ message: str = Field(..., description="The message content to be processed by the agent.")+ stream: bool = Field(default=False, description="Flag to determine if the response should be streamed. Set to True for streaming.")+++class UserMessageResponse(BaseModel):+ messages: List[str] = Field(..., description="List of messages generated by the agent.")def setup_agents_message_router(server: SyncServer, interface: QueuingInterface):- @router.post("/agents/message")- async def user_message(body: UserMessage):- if body.stream:+ @router.post("/agents/message", tags=["agents"], response_model=UserMessageResponse)+ async def user_message(request: UserMessageRequest = Body(...)):+ """+ Process a user message and return the agent's response.++ 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.stream:# For streaming responsetry:# Start the generation process (similar to the non-streaming case)@@ -30,11 +41,13 @@ def setup_agents_message_router(server: SyncServer, interface: QueuingInterface)# Check if server.user_message is an async functionif asyncio.iscoroutinefunction(server.user_message):# Start the async task- await asyncio.create_task(server.user_message(user_id=body.user_id, agent_id=body.agent_id, message=body.message))+ await asyncio.create_task(+ server.user_message(user_id=request.user_id, agent_id=request.agent_id, message=request.message)+ )else:# Run the synchronous function in a thread poolloop = asyncio.get_event_loop()- loop.run_in_executor(None, server.user_message, body.user_id, body.agent_id, body.message)+ loop.run_in_executor(None, server.user_message, request.user_id, request.agent_id, request.message)async def formatted_message_generator():async for message in interface.message_generator():@@ -52,11 +65,11 @@ def setup_agents_message_router(server: SyncServer, interface: QueuingInterface)else:interface.clear()try:- server.user_message(user_id=body.user_id, agent_id=body.agent_id, message=body.message)+ server.user_message(user_id=request.user_id, agent_id=request.agent_id, message=request.message)except HTTPException:raiseexcept Exception as e:- raise HTTPException(status_code=500, detail=f"{e}")- return {"messages": interface.to_list()}+ raise HTTPException(status_code=500, detail=str(e))+ return UserMessageResponse(messages=interface.to_list())return routerdiff --git a/memgpt/server/rest_api/config/index.py b/memgpt/server/rest_api/config/index.pyindex 30ab835c1..36771bd44 100644--- a/memgpt/server/rest_api/config/index.py+++ b/memgpt/server/rest_api/config/index.py@@ -1,6 +1,6 @@-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, Depends, HTTPException-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom memgpt.server.rest_api.interface import QueuingInterfacefrom memgpt.server.server import SyncServer@@ -8,15 +8,22 @@ from memgpt.server.server import SyncServerrouter = APIRouter()-class CreateAgentConfig(BaseModel):- user_id: str- config: dict+class ConfigRequest(BaseModel):+ user_id: str = Field(..., description="Unique identifier of the user issuing the command.")+++class ConfigResponse(BaseModel):+ config: dict = Field(..., description="The server configuration object.")def setup_config_index_router(server: SyncServer, interface: QueuingInterface):- @router.get("/config")- def get_server_config(user_id: str):+ @router.get("/config", tags=["config"], response_model=ConfigResponse)+ def get_server_config(user_id: ConfigRequest = Depends()):+ """+ Retrieve the base configuration for the server.+ """interface.clear()- return server.get_server_config(user_id=user_id)+ response = server.get_server_config(user_id=user_id)+ return ConfigResponse(config=response)return router