Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

Add `user` field for vLLM endpoint (#531)

Sarah Woodersb05b09439f03
diff --git a/memgpt/agent.py b/memgpt/agent.py
index e24bf6e8d..9ba2ff114 100644
--- a/memgpt/agent.py
+++ b/memgpt/agent.py
@@ -5,7 +5,7 @@ import json
import traceback
from memgpt.persistence_manager import LocalStateManager
-from memgpt.config import AgentConfig
+from memgpt.config import AgentConfig, MemGPTConfig
from .system import get_login_event, package_function_response, package_summarize_message, get_initial_boot_messages
from .memory import CoreMemory as Memory, summarize_messages
from .openai_tools import completions_with_backoff as create
@@ -114,6 +114,7 @@ class Agent(object):
):
# agent config
self.config = config
+
# gpt-4, gpt-3.5-turbo
self.model = model
# Store the system instructions (used to rebuild memory)
@@ -786,7 +787,6 @@ class Agent(object):
try:
response = chat_completion_with_backoff(
agent_config=self.config,
- model=self.model, # TODO: remove (is redundant)
messages=message_sequence,
functions=self.functions,
function_call=function_call,
diff --git a/memgpt/embeddings.py b/memgpt/embeddings.py
index 1445e3db2..6c4a45257 100644
--- a/memgpt/embeddings.py
+++ b/memgpt/embeddings.py
@@ -1,7 +1,93 @@
import typer
+from typing import Optional, List
import os
from llama_index.embeddings import OpenAIEmbedding
from llama_index.embeddings import TextEmbeddingsInference
+from llama_index.bridge.pydantic import PrivateAttr
+
+from llama_index.embeddings.base import BaseEmbedding
+from llama_index.embeddings.huggingface_utils import format_query, format_text
+
+
+class EmbeddingEndpoint(BaseEmbedding):
+
+ """Implementation for OpenAI compatible endpoint"""
+
+ """ Based off llama index https://github.com/run-llama/llama_index/blob/a98bdb8ecee513dc2e880f56674e7fd157d1dc3a/llama_index/embeddings/text_embeddings_inference.py """
+
+ _user: str = PrivateAttr()
+ _timeout: float = PrivateAttr()
+ _base_url: str = PrivateAttr()
+
+ def __init__(
+ self,
+ model: str,
+ base_url: str,
+ user: str,
+ timeout: float = 60.0,
+ ):
+ self._user = user
+ self._base_url = base_url
+ self._timeout = timeout
+ super().__init__(
+ model_name=model,
+ )
+
+ @classmethod
+ def class_name(cls) -> str:
+ return "EmbeddingEndpoint"
+
+ def _call_api(self, text: str) -> List[float]:
+ import httpx
+
+ headers = {"Content-Type": "application/json"}
+ json_data = {"input": text, "model": self.model_name, "user": self._user}
+
+ with httpx.Client() as client:
+ response = client.post(
+ f"{self._base_url}/embeddings",
+ headers=headers,
+ json=json_data,
+ timeout=self._timeout,
+ )
+
+ return response.json()
+
+ async def _acall_api(self, text: str) -> List[float]:
+ import httpx
+
+ headers = {"Content-Type": "application/json"}
+ json_data = {"input": text, "model": self.model_name, "user": self._user}
+
+ async with httpx.AsyncClient() as client:
+ response = await client.post(
+ f"{self._base_url}/embeddings",
+ headers=headers,
+ json=json_data,
+ timeout=self._timeout,
+ )
+
+ return response.json()
+
+ def _get_query_embedding(self, query: str) -> list[float]:
+ """get query embedding."""
+ embedding = self._call_api(query)
+ return embedding
+
+ def _get_text_embedding(self, text: str) -> list[float]:
+ """get text embedding."""
+ embedding = self._call_api(text)
+ return embedding
+
+ def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
+ embeddings = [self._get_text_embedding(text) for text in texts]
+ return embeddings
+
+ async def _aget_query_embedding(self, query: str) -> List[float]:
+ return self._get_query_embedding(query)
+
+ async def _aget_text_embedding(self, text: str) -> List[float]:
+ return self._get_text_embedding(text)
def embedding_model():
@@ -14,7 +100,9 @@ def embedding_model():
endpoint = config.embedding_endpoint_type
if endpoint == "openai":
- model = OpenAIEmbedding(api_base=config.embedding_endpoint, api_key=config.openai_key)
+ model = OpenAIEmbedding(
+ api_base=config.embedding_endpoint, api_key=config.openai_key, additional_kwargs={"user": config.anon_clientid}
+ )
return model
elif endpoint == "azure":
return OpenAIEmbedding(
@@ -26,11 +114,7 @@ def embedding_model():
api_version=config.azure_version,
)
elif endpoint == "hugging-face":
- embed_model = TextEmbeddingsInference(
- base_url=config.embedding_endpoint,
- model_name=config.embedding_model,
- timeout=60, # timeout in seconds
- )
+ embed_model = EmbeddingEndpoint(model=config.embedding_model, base_url=config.embedding_endpoint, user=config.anon_clientid)
return embed_model
else:
# default to hugging face model running local
diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.py
index 9dda26e4d..cfeb718c2 100644
--- a/memgpt/local_llm/chat_completion_proxy.py
+++ b/memgpt/local_llm/chat_completion_proxy.py
@@ -31,6 +31,7 @@ def get_chat_completion(
functions=None,
function_call="auto",
context_window=None,
+ user=None,
# required
wrapper=None,
endpoint=None,
@@ -97,7 +98,7 @@ def get_chat_completion(
elif endpoint_type == "ollama":
result = get_ollama_completion(endpoint, model, prompt, context_window)
elif endpoint_type == "vllm":
- result = get_vllm_completion(endpoint, model, prompt, context_window)
+ result = get_vllm_completion(endpoint, model, prompt, context_window, user)
else:
raise LocalLLMError(
f"BACKEND_TYPE is not set, please set variable depending on your backend (webui, lmstudio, llamacpp, koboldcpp)"
diff --git a/memgpt/local_llm/vllm/api.py b/memgpt/local_llm/vllm/api.py
index 76d638124..a1169f3d4 100644
--- a/memgpt/local_llm/vllm/api.py
+++ b/memgpt/local_llm/vllm/api.py
@@ -8,7 +8,7 @@ WEBUI_API_SUFFIX = "/completions"
DEBUG = False
-def get_vllm_completion(endpoint, model, prompt, context_window, settings={}, grammar=None):
+def get_vllm_completion(endpoint, model, prompt, context_window, user, settings={}, grammar=None):
"""https://github.com/vllm-project/vllm/blob/main/examples/api_client.py"""
prompt_tokens = count_tokens(prompt)
if prompt_tokens > context_window:
@@ -19,6 +19,7 @@ def get_vllm_completion(endpoint, model, prompt, context_window, settings={}, gr
request["prompt"] = prompt
request["max_tokens"] = int(context_window - prompt_tokens)
request["stream"] = False
+ request["user"] = user
# currently hardcoded, since we are only supporting one model with the hosted endpoint
request["model"] = model
diff --git a/memgpt/memory.py b/memgpt/memory.py
index d49ac48c3..38cdcb5ad 100644
--- a/memgpt/memory.py
+++ b/memgpt/memory.py
@@ -496,6 +496,8 @@ class DummyRecallMemory(RecallMemory):
]
# start/count support paging through results
+ start = int(start) if start is None else start
+ count = int(count) if count is None else count
if start is not None and count is not None:
return matches[start : start + count], len(matches)
elif start is None and count is not None:
diff --git a/memgpt/openai_tools.py b/memgpt/openai_tools.py
index cd67f0184..8f5622b6d 100644
--- a/memgpt/openai_tools.py
+++ b/memgpt/openai_tools.py
@@ -81,39 +81,59 @@ def completions_with_backoff(**kwargs):
@retry_with_exponential_backoff
-def chat_completion_with_backoff(agent_config, **kwargs):
+def chat_completion_with_backoff(
+ agent_config,
+ messages,
+ functions,
+ function_call,
+):
from memgpt.utils import printd
- from memgpt.config import AgentConfig, MemGPTConfig
+ from memgpt.config import MemGPTConfig
- # both "model" and "messages" are required for base OpenAI calls
- # also required for local LLM Ollama, but not others
- if "model" not in kwargs:
- kwargs["model"] = agent_config.model
+ config = MemGPTConfig.load() # load credentials (currently not stored in agent config)
printd(f"Using model {agent_config.model_endpoint_type}, endpoint: {agent_config.model_endpoint}")
if agent_config.model_endpoint_type == "openai":
# openai
openai.api_base = agent_config.model_endpoint
- return openai.ChatCompletion.create(**kwargs)
+ return openai.ChatCompletion.create(
+ model=agent_config.model, messages=messages, functions=functions, function_call=function_call, user=config.anon_clientid
+ )
elif agent_config.model_endpoint_type == "azure":
- # configure openai
- config = MemGPTConfig.load() # load credentials (currently not stored in agent config)
+ # azure
openai.api_type = "azure"
openai.api_key = config.azure_key
openai.api_base = config.azure_endpoint
openai.api_version = config.azure_version
if config.azure_deployment is not None:
- kwargs["deployment_id"] = config.azure_deployment
+ deployment_id = config.azure_deployment
+ engine = None
+ model = config.model
else:
- kwargs["engine"] = MODEL_TO_AZURE_ENGINE[config.model]
- del kwargs["model"]
- return openai.ChatCompletion.create(**kwargs)
+ engine = MODEL_TO_AZURE_ENGINE[config.model]
+ model = None
+ deployment_id = None
+ return openai.ChatCompletion.create(
+ model=model,
+ messages=messages,
+ engine=engine,
+ deployment_id=deployment_id,
+ functions=functions,
+ function_call=function_call,
+ user=client_id,
+ )
else: # local model
- kwargs["context_window"] = agent_config.context_window # specify for open LLMs
- kwargs["endpoint"] = agent_config.model_endpoint # specify for open LLMs
- kwargs["endpoint_type"] = agent_config.model_endpoint_type # specify for open LLMs
- kwargs["wrapper"] = agent_config.model_wrapper # specify for open LLMs
- return get_chat_completion(**kwargs)
+ return get_chat_completion(
+ model=agent_config.model,
+ messages=messages,
+ functions=functions,
+ function_call=function_call,
+ context_window=agent_config.context_window,
+ endpoint=agent_config.model_endpoint,
+ endpoint_type=agent_config.model_endpoint_type,
+ wrapper=agent_config.model_wrapper,
+ user=config.anon_clientid,
+ )
# TODO: deprecate