Spaces:
Build error
Build error
Upload 235 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- litellm/__init__.pyAdded+557
- litellm/_logging.pyAdded+30
- litellm/_redis.pyAdded+93
- litellm/_version.pyAdded+6
- litellm/budget_manager.pyAdded+206
- litellm/caching.pyAdded+678
- litellm/cost.jsonAdded+5
- litellm/deprecated_litellm_server/.env.templateAdded+43
- litellm/deprecated_litellm_server/DockerfileAdded+10
- litellm/deprecated_litellm_server/README.mdAdded+3
- litellm/deprecated_litellm_server/__init__.pyAdded+2
- litellm/deprecated_litellm_server/main.pyAdded+193
- litellm/deprecated_litellm_server/requirements.txtAdded+7
- litellm/deprecated_litellm_server/server_utils.pyAdded+85
- litellm/exceptions.pyAdded+200
- litellm/integrations/__init__.pyAdded+1
- litellm/integrations/aispend.pyAdded+177
- litellm/integrations/berrispend.pyAdded+184
- litellm/integrations/custom_logger.pyAdded+130
- litellm/integrations/dynamodb.pyAdded+92
- litellm/integrations/helicone.pyAdded+114
- litellm/integrations/langfuse.pyAdded+191
- litellm/integrations/langsmith.pyAdded+75
- litellm/integrations/litedebugger.pyAdded+262
- litellm/integrations/llmonitor.pyAdded+127
- litellm/integrations/prompt_layer.pyAdded+72
- litellm/integrations/s3.pyAdded+150
- litellm/integrations/supabase.pyAdded+117
- litellm/integrations/traceloop.pyAdded+114
- litellm/integrations/weights_biases.pyAdded+223
- litellm/llms/__init__.pyAdded+1
- litellm/llms/ai21.pyAdded+212
- litellm/llms/aleph_alpha.pyAdded+304
- litellm/llms/anthropic.pyAdded+215
- litellm/llms/azure.pyAdded+799
- litellm/llms/base.pyAdded+45
- litellm/llms/baseten.pyAdded+164
- litellm/llms/bedrock.pyAdded+799
- litellm/llms/cloudflare.pyAdded+176
- litellm/llms/cohere.pyAdded+293
- litellm/llms/custom_httpx/azure_dall_e_2.pyAdded+136
- litellm/llms/custom_httpx/bedrock_async.pyAdded
- litellm/llms/gemini.pyAdded+222
- litellm/llms/huggingface_llms_metadata/hf_conversational_models.txtAdded+2523
- litellm/llms/huggingface_llms_metadata/hf_text_generation_models.txtAdded
- litellm/llms/huggingface_restapi.pyAdded+750
- litellm/llms/maritalk.pyAdded+189
- litellm/llms/nlp_cloud.pyAdded+243
- litellm/llms/ollama.pyAdded+400
- litellm/llms/ollama_chat.pyAdded+333
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557### INIT VARIABLES ###import threading, requestsfrom typing import Callable, List, Optional, Dict, Union, Anyfrom litellm.caching import Cachefrom litellm._logging import set_verbosefrom litellm.proxy._types import KeyManagementSystemimport httpx
input_callback: List[Union[str, Callable]] = []success_callback: List[Union[str, Callable]] = []failure_callback: List[Union[str, Callable]] = []callbacks: List[Callable] = []_async_input_callback: List[ Callable] = [] # internal variable - async custom callbacks are routed here._async_success_callback: List[ Union[str, Callable]] = [] # internal variable - async custom callbacks are routed here._async_failure_callback: List[ Callable] = [] # internal variable - async custom callbacks are routed here.pre_call_rules: List[Callable] = []post_call_rules: List[Callable] = []email: Optional[ str] = None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648token: Optional[ str] = None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648telemetry = Truemax_tokens = 256 # OpenAI Defaultsdrop_params = Falseretry = Trueapi_key: Optional[str] = Noneopenai_key: Optional[str] = Noneazure_key: Optional[str] = Noneanthropic_key: Optional[str] = Nonereplicate_key: Optional[str] = Nonecohere_key: Optional[str] = Nonemaritalk_key: Optional[str] = Noneai21_key: Optional[str] = Noneopenrouter_key: Optional[str] = Nonehuggingface_key: Optional[str] = Nonevertex_project: Optional[str] = Nonevertex_location: Optional[str] = Nonetogetherai_api_key: Optional[str] = Nonecloudflare_api_key: Optional[str] = Nonebaseten_key: Optional[str] = Nonealeph_alpha_key: Optional[str] = Nonenlp_cloud_key: Optional[str] = Noneuse_client: bool = Falselogging: bool = Truecaching: bool = False # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648caching_with_models: bool = False # # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648cache: Optional[ Cache] = None # cache object <- use this - https://docs.litellm.ai/docs/cachingmodel_alias_map: Dict[str, str] = {}model_group_alias_map: Dict[str, str] = {}max_budget: float = 0.0 # set the max budget across all providers_openai_completion_params = [ "functions", "function_call", "temperature", "temperature", "top_p", "n", "stream", "stop", "max_tokens", "presence_penalty", "frequency_penalty", "logit_bias", "user", "request_timeout", "api_base", "api_version", "api_key", "deployment_id", "organization", "base_url", "default_headers", "timeout", "response_format", "seed", "tools", "tool_choice", "max_retries",]_litellm_completion_params = [ "metadata", "acompletion", "caching", "mock_response", "api_key", "api_version", "api_base", "force_timeout", "logger_fn", "verbose", "custom_llm_provider", "litellm_logging_obj", "litellm_call_id", "use_client", "id", "fallbacks", "azure", "headers", "model_list", "num_retries", "context_window_fallback_dict", "roles", "final_prompt_value", "bos_token", "eos_token", "request_timeout", "complete_response", "self", "client", "rpm", "tpm", "input_cost_per_token", "output_cost_per_token", "hf_model_name", "model_info", "proxy_server_request", "preset_cache_key",]_current_cost = 0 # private variable, used if max budget is seterror_logs: Dict = {}add_function_to_prompt: bool = False # if function calling not supported by api, append function call details to system promptclient_session: Optional[httpx.Client] = Noneaclient_session: Optional[httpx.AsyncClient] = Nonemodel_fallbacks: Optional[List] = None # Deprecated for 'litellm.fallbacks'model_cost_map_url: str = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"suppress_debug_info = Falsedynamodb_table_name: Optional[str] = Nones3_callback_params: Optional[Dict] = None#### RELIABILITY ####request_timeout: Optional[float] = 6000num_retries: Optional[int] = None # per model endpointfallbacks: Optional[List] = Nonecontext_window_fallbacks: Optional[List] = Noneallowed_fails: int = 0num_retries_per_request: Optional[ int] = None # for the request overall (incl. fallbacks + model retries)####### SECRET MANAGERS #####################secret_manager_client: Optional[ Any] = None # list of instantiated key management clients - e.g. azure kv, infisical, etc._google_kms_resource_name: Optional[str] = None_key_management_system: Optional[KeyManagementSystem] = None#############################################
def get_model_cost_map(url: str): try: with requests.get( url, timeout=5 ) as response: # set a 5 second timeout for the get request response.raise_for_status() # Raise an exception if the request is unsuccessful content = response.json() return content except Exception as e: import importlib.resources import json
with importlib.resources.open_text( "litellm", "model_prices_and_context_window_backup.json" ) as f: content = json.load(f) return content
model_cost = get_model_cost_map(url=model_cost_map_url)custom_prompt_dict: Dict[str, dict] = {}
####### THREAD-SPECIFIC DATA ###################class MyLocal(threading.local): def __init__(self): self.user = "Hello World"
_thread_context = MyLocal()
def identify(event_details): # Store user in thread local data if "user" in event_details: _thread_context.user = event_details["user"]
####### ADDITIONAL PARAMS ################### configurable params if you use proxy models like Helicone, map spend to org id, etc.api_base = Noneheaders = Noneapi_version = Noneorganization = Noneconfig_path = None####### COMPLETION MODELS ###################open_ai_chat_completion_models: List = []open_ai_text_completion_models: List = []cohere_models: List = []anthropic_models: List = []openrouter_models: List = []vertex_language_models: List = []vertex_vision_models: List = []vertex_chat_models: List = []vertex_code_chat_models: List = []vertex_text_models: List = []vertex_code_text_models: List = []ai21_models: List = []nlp_cloud_models: List = []aleph_alpha_models: List = []bedrock_models: List = []deepinfra_models: List = []perplexity_models: List = []for key, value in model_cost.items(): if value.get("litellm_provider") == "openai": open_ai_chat_completion_models.append(key) elif value.get("litellm_provider") == "text-completion-openai": open_ai_text_completion_models.append(key) elif value.get("litellm_provider") == "cohere": cohere_models.append(key) elif value.get("litellm_provider") == "anthropic": anthropic_models.append(key) elif value.get("litellm_provider") == "openrouter": openrouter_models.append(key) elif value.get("litellm_provider") == "vertex_ai-text-models": vertex_text_models.append(key) elif value.get("litellm_provider") == "vertex_ai-code-text-models": vertex_code_text_models.append(key) elif value.get("litellm_provider") == "vertex_ai-language-models": vertex_language_models.append(key) elif value.get("litellm_provider") == "vertex_ai-vision-models": vertex_vision_models.append(key) elif value.get("litellm_provider") == "vertex_ai-chat-models": vertex_chat_models.append(key) elif value.get("litellm_provider") == "vertex_ai-code-chat-models": vertex_code_chat_models.append(key) elif value.get("litellm_provider") == "ai21": ai21_models.append(key) elif value.get("litellm_provider") == "nlp_cloud": nlp_cloud_models.append(key) elif value.get("litellm_provider") == "aleph_alpha": aleph_alpha_models.append(key) elif value.get("litellm_provider") == "bedrock": bedrock_models.append(key) elif value.get("litellm_provider") == "deepinfra": deepinfra_models.append(key) elif value.get("litellm_provider") == "perplexity": perplexity_models.append(key)
# known openai compatible endpoints - we'll eventually move this list to the model_prices_and_context_window.json dictionaryopenai_compatible_endpoints: List = [ "api.perplexity.ai", "api.endpoints.anyscale.com/v1", "api.deepinfra.com/v1/openai", "api.mistral.ai/v1",]
# this is maintained for Exception Mappingopenai_compatible_providers: List = [ "anyscale", "mistral", "deepinfra", "perplexity", "xinference",]
# well supported replicate llmsreplicate_models: List = [ # llama replicate supported LLMs "replicate/llama-2-70b-chat:2796ee9483c3fd7aa2e171d38f4ca12251a30609463dcfd4cd76703f22e96cdf", "a16z-infra/llama-2-13b-chat:2a7f981751ec7fdf87b5b91ad4db53683a98082e9ff7bfd12c8cd5ea85980a52", "meta/codellama-13b:1c914d844307b0588599b8393480a3ba917b660c7e9dfae681542b5325f228db", # Vicuna "replicate/vicuna-13b:6282abe6a492de4145d7bb601023762212f9ddbbe78278bd6771c8b3b2f2a13b", "joehoover/instructblip-vicuna13b:c4c54e3c8c97cd50c2d2fec9be3b6065563ccf7d43787fb99f84151b867178fe", # Flan T-5 "daanelson/flan-t5-large:ce962b3f6792a57074a601d3979db5839697add2e4e02696b3ced4c022d4767f" # Others "replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5", "replit/replit-code-v1-3b:b84f4c074b807211cd75e3e8b1589b6399052125b4c27106e43d47189e8415ad",]
huggingface_models: List = [ "meta-llama/Llama-2-7b-hf", "meta-llama/Llama-2-7b-chat-hf", "meta-llama/Llama-2-13b-hf", "meta-llama/Llama-2-13b-chat-hf", "meta-llama/Llama-2-70b-hf", "meta-llama/Llama-2-70b-chat-hf", "meta-llama/Llama-2-7b", "meta-llama/Llama-2-7b-chat", "meta-llama/Llama-2-13b", "meta-llama/Llama-2-13b-chat", "meta-llama/Llama-2-70b", "meta-llama/Llama-2-70b-chat",] # these have been tested on extensively. But by default all text2text-generation and text-generation models are supported by liteLLM. - https://docs.litellm.ai/docs/providers
together_ai_models: List = [ # llama llms - chat "togethercomputer/llama-2-70b-chat", # llama llms - language / instruct "togethercomputer/llama-2-70b", "togethercomputer/LLaMA-2-7B-32K", "togethercomputer/Llama-2-7B-32K-Instruct", "togethercomputer/llama-2-7b", # falcon llms "togethercomputer/falcon-40b-instruct", "togethercomputer/falcon-7b-instruct", # alpaca "togethercomputer/alpaca-7b", # chat llms "HuggingFaceH4/starchat-alpha", # code llms "togethercomputer/CodeLlama-34b", "togethercomputer/CodeLlama-34b-Instruct", "togethercomputer/CodeLlama-34b-Python", "defog/sqlcoder", "NumbersStation/nsql-llama-2-7B", "WizardLM/WizardCoder-15B-V1.0", "WizardLM/WizardCoder-Python-34B-V1.0", # language llms "NousResearch/Nous-Hermes-Llama2-13b", "Austism/chronos-hermes-13b", "upstage/SOLAR-0-70b-16bit", "WizardLM/WizardLM-70B-V1.0",] # supports all together ai models, just pass in the model id e.g. completion(model="together_computer/replit_code_3b",...)
baseten_models: List = [ "qvv0xeq", "q841o8w", "31dxrj3",] # FALCON 7B # WizardLM # Mosaic ML
# used for Cost Tracking & Token counting# https://azure.microsoft.com/en-in/pricing/details/cognitive-services/openai-service/# Azure returns gpt-35-turbo in their responses, we need to map this to azure/gpt-3.5-turbo for token countingazure_llms = { "gpt-35-turbo": "azure/gpt-35-turbo", "gpt-35-turbo-16k": "azure/gpt-35-turbo-16k", "gpt-35-turbo-instruct": "azure/gpt-35-turbo-instruct",}
azure_embedding_models = { "ada": "azure/ada",}
petals_models = [ "petals-team/StableBeluga2",]
ollama_models = ["llama2"]
maritalk_models = ["maritalk"]
model_list = ( open_ai_chat_completion_models + open_ai_text_completion_models + cohere_models + anthropic_models + replicate_models + openrouter_models + huggingface_models + vertex_chat_models + vertex_text_models + ai21_models + together_ai_models + baseten_models + aleph_alpha_models + nlp_cloud_models + ollama_models + bedrock_models + deepinfra_models + perplexity_models + maritalk_models)
provider_list: List = [ "openai", "custom_openai", "text-completion-openai", "cohere", "anthropic", "replicate", "huggingface", "together_ai", "openrouter", "vertex_ai", "palm", "gemini", "ai21", "baseten", "azure", "sagemaker", "bedrock", "vllm", "nlp_cloud", "petals", "oobabooga", "ollama", "ollama_chat", "deepinfra", "perplexity", "anyscale", "mistral", "maritalk", "voyage", "cloudflare", "xinference", "custom", # custom apis]
models_by_provider: dict = { "openai": open_ai_chat_completion_models + open_ai_text_completion_models, "cohere": cohere_models, "anthropic": anthropic_models, "replicate": replicate_models, "huggingface": huggingface_models, "together_ai": together_ai_models, "baseten": baseten_models, "openrouter": openrouter_models, "vertex_ai": vertex_chat_models + vertex_text_models, "ai21": ai21_models, "bedrock": bedrock_models, "petals": petals_models, "ollama": ollama_models, "deepinfra": deepinfra_models, "perplexity": perplexity_models, "maritalk": maritalk_models,}
# mapping for those models which have larger equivalentslonger_context_model_fallback_dict: dict = { # openai chat completion models "gpt-3.5-turbo": "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301": "gpt-3.5-turbo-16k-0301", "gpt-3.5-turbo-0613": "gpt-3.5-turbo-16k-0613", "gpt-4": "gpt-4-32k", "gpt-4-0314": "gpt-4-32k-0314", "gpt-4-0613": "gpt-4-32k-0613", # anthropic "claude-instant-1": "claude-2", "claude-instant-1.2": "claude-2", # vertexai "chat-bison": "chat-bison-32k", "chat-bison@001": "chat-bison-32k", "codechat-bison": "codechat-bison-32k", "codechat-bison@001": "codechat-bison-32k", # openrouter "openrouter/openai/gpt-3.5-turbo": "openrouter/openai/gpt-3.5-turbo-16k", "openrouter/anthropic/claude-instant-v1": "openrouter/anthropic/claude-2",}
####### EMBEDDING MODELS ###################open_ai_embedding_models: List = ["text-embedding-ada-002"]cohere_embedding_models: List = [ "embed-english-v3.0", "embed-english-light-v3.0", "embed-multilingual-v3.0", "embed-english-v2.0", "embed-english-light-v2.0", "embed-multilingual-v2.0",]bedrock_embedding_models: List = [ "amazon.titan-embed-text-v1", "cohere.embed-english-v3", "cohere.embed-multilingual-v3",]
all_embedding_models = ( open_ai_embedding_models + cohere_embedding_models + bedrock_embedding_models)
####### IMAGE GENERATION MODELS ###################openai_image_generation_models = ["dall-e-2", "dall-e-3"]
from .timeout import timeoutfrom .utils import ( client, exception_type, get_optional_params, modify_integration, token_counter, cost_per_token, completion_cost, get_litellm_params, Logging, acreate, get_model_list, get_max_tokens, get_model_info, register_prompt_template, validate_environment, check_valid_key, get_llm_provider, register_model, encode, decode, _calculate_retry_after, _should_retry, get_secret,)from .llms.huggingface_restapi import HuggingfaceConfigfrom .llms.anthropic import AnthropicConfigfrom .llms.replicate import ReplicateConfigfrom .llms.cohere import CohereConfigfrom .llms.ai21 import AI21Configfrom .llms.together_ai import TogetherAIConfigfrom .llms.cloudflare import CloudflareConfigfrom .llms.palm import PalmConfigfrom .llms.gemini import GeminiConfigfrom .llms.nlp_cloud import NLPCloudConfigfrom .llms.aleph_alpha import AlephAlphaConfigfrom .llms.petals import PetalsConfigfrom .llms.vertex_ai import VertexAIConfigfrom .llms.sagemaker import SagemakerConfigfrom .llms.ollama import OllamaConfigfrom .llms.maritalk import MaritTalkConfigfrom .llms.bedrock import ( AmazonTitanConfig, AmazonAI21Config, AmazonAnthropicConfig, AmazonCohereConfig, AmazonLlamaConfig,)from .llms.openai import OpenAIConfig, OpenAITextCompletionConfigfrom .llms.azure import AzureOpenAIConfig, AzureOpenAIErrorfrom .main import * # type: ignorefrom .integrations import *from .exceptions import ( AuthenticationError, InvalidRequestError, BadRequestError, NotFoundError, RateLimitError, ServiceUnavailableError, OpenAIError, ContextWindowExceededError, ContentPolicyViolationError, BudgetExceededError, APIError, Timeout, APIConnectionError, APIResponseValidationError, UnprocessableEntityError,)from .budget_manager import BudgetManagerfrom .proxy.proxy_cli import run_serverfrom .router import Router123456789101112131415161718192021222324252627282930import logging
set_verbose = False
# Create a handler for the logger (you may need to adapt this based on your needs)handler = logging.StreamHandler()handler.setLevel(logging.DEBUG)
# Create a formatter and set it for the handler
formatter = logging.Formatter("\033[92m%(name)s - %(levelname)s\033[0m: %(message)s")
handler.setFormatter(formatter)
def print_verbose(print_statement): try: if set_verbose: print(print_statement) # noqa except: pass
verbose_proxy_logger = logging.getLogger("LiteLLM Proxy")verbose_router_logger = logging.getLogger("LiteLLM Router")verbose_logger = logging.getLogger("LiteLLM")
# Add the handler to the loggerverbose_router_logger.addHandler(handler)verbose_proxy_logger.addHandler(handler)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# +-----------------------------------------------+# | |# | Give Feedback / Get Help |# | https://github.com/BerriAI/litellm/issues/new |# | |# +-----------------------------------------------+## Thank you users! We ❤️ you! - Krrish & Ishaan
# s/o [@Frank Colson](https://www.linkedin.com/in/frank-colson-422b9b183/) for this redis implementationimport osimport inspectimport redis, litellmfrom typing import List, Optional
def _get_redis_kwargs(): arg_spec = inspect.getfullargspec(redis.Redis)
# Only allow primitive arguments exclude_args = { "self", "connection_pool", "retry", }
include_args = ["url"]
available_args = [x for x in arg_spec.args if x not in exclude_args] + include_args
return available_args
def _get_redis_env_kwarg_mapping(): PREFIX = "REDIS_"
return {f"{PREFIX}{x.upper()}": x for x in _get_redis_kwargs()}
def _redis_kwargs_from_environment(): mapping = _get_redis_env_kwarg_mapping()
return_dict = {} for k, v in mapping.items(): value = litellm.get_secret(k, default_value=None) # check os.environ/key vault if value is not None: return_dict[v] = value return return_dict
def get_redis_url_from_environment(): if "REDIS_URL" in os.environ: return os.environ["REDIS_URL"]
if "REDIS_HOST" not in os.environ or "REDIS_PORT" not in os.environ: raise ValueError( "Either 'REDIS_URL' or both 'REDIS_HOST' and 'REDIS_PORT' must be specified for Redis." )
if "REDIS_PASSWORD" in os.environ: redis_password = f":{os.environ['REDIS_PASSWORD']}@" else: redis_password = ""
return ( f"redis://{redis_password}{os.environ['REDIS_HOST']}:{os.environ['REDIS_PORT']}" )
def get_redis_client(**env_overrides): ### check if "os.environ/<key-name>" passed in for k, v in env_overrides.items(): if isinstance(v, str) and v.startswith("os.environ/"): v = v.replace("os.environ/", "") value = litellm.get_secret(v) env_overrides[k] = value
redis_kwargs = { **_redis_kwargs_from_environment(), **env_overrides, }
if "url" in redis_kwargs and redis_kwargs["url"] is not None: redis_kwargs.pop("host", None) redis_kwargs.pop("port", None) redis_kwargs.pop("db", None) redis_kwargs.pop("password", None)
return redis.Redis.from_url(**redis_kwargs) elif "host" not in redis_kwargs or redis_kwargs["host"] is None: raise ValueError("Either 'host' or 'url' must be specified for redis.") litellm.print_verbose(f"redis_kwargs: {redis_kwargs}") return redis.Redis(**redis_kwargs)123456import importlib_metadata
try: version = importlib_metadata.version("litellm")except: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206import os, json, timeimport litellmfrom litellm.utils import ModelResponseimport requests, threadingfrom typing import Optional, Union, Literal
class BudgetManager: def __init__( self, project_name: str, client_type: str = "local", api_base: Optional[str] = None, ): self.client_type = client_type self.project_name = project_name self.api_base = api_base or "https://api.litellm.ai" ## load the data or init the initial dictionaries self.load_data()
def print_verbose(self, print_statement): try: if litellm.set_verbose: import logging
logging.info(print_statement) except: pass
def load_data(self): if self.client_type == "local": # Check if user dict file exists if os.path.isfile("user_cost.json"): # Load the user dict with open("user_cost.json", "r") as json_file: self.user_dict = json.load(json_file) else: self.print_verbose("User Dictionary not found!") self.user_dict = {} self.print_verbose(f"user dict from local: {self.user_dict}") elif self.client_type == "hosted": # Load the user_dict from hosted db url = self.api_base + "/get_budget" headers = {"Content-Type": "application/json"} data = {"project_name": self.project_name} response = requests.post(url, headers=headers, json=data) response = response.json() if response["status"] == "error": self.user_dict = ( {} ) # assume this means the user dict hasn't been stored yet else: self.user_dict = response["data"]
def create_budget( self, total_budget: float, user: str, duration: Optional[Literal["daily", "weekly", "monthly", "yearly"]] = None, created_at: float = time.time(), ): self.user_dict[user] = {"total_budget": total_budget} if duration is None: return self.user_dict[user]
if duration == "daily": duration_in_days = 1 elif duration == "weekly": duration_in_days = 7 elif duration == "monthly": duration_in_days = 28 elif duration == "yearly": duration_in_days = 365 else: raise ValueError( """duration needs to be one of ["daily", "weekly", "monthly", "yearly"]""" ) self.user_dict[user] = { "total_budget": total_budget, "duration": duration_in_days, "created_at": created_at, "last_updated_at": created_at, } self._save_data_thread() # [Non-Blocking] Update persistent storage without blocking execution return self.user_dict[user]
def projected_cost(self, model: str, messages: list, user: str): text = "".join(message["content"] for message in messages) prompt_tokens = litellm.token_counter(model=model, text=text) prompt_cost, _ = litellm.cost_per_token( model=model, prompt_tokens=prompt_tokens, completion_tokens=0 ) current_cost = self.user_dict[user].get("current_cost", 0) projected_cost = prompt_cost + current_cost return projected_cost
def get_total_budget(self, user: str): return self.user_dict[user]["total_budget"]
def update_cost( self, user: str, completion_obj: Optional[ModelResponse] = None, model: Optional[str] = None, input_text: Optional[str] = None, output_text: Optional[str] = None, ): if model and input_text and output_text: prompt_tokens = litellm.token_counter( model=model, messages=[{"role": "user", "content": input_text}] ) completion_tokens = litellm.token_counter( model=model, messages=[{"role": "user", "content": output_text}] ) ( prompt_tokens_cost_usd_dollar, completion_tokens_cost_usd_dollar, ) = litellm.cost_per_token( model=model, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, ) cost = prompt_tokens_cost_usd_dollar + completion_tokens_cost_usd_dollar elif completion_obj: cost = litellm.completion_cost(completion_response=completion_obj) model = completion_obj[ "model" ] # if this throws an error try, model = completion_obj['model'] else: raise ValueError( "Either a chat completion object or the text response needs to be passed in. Learn more - https://docs.litellm.ai/docs/budget_manager" )
self.user_dict[user]["current_cost"] = cost + self.user_dict[user].get( "current_cost", 0 ) if "model_cost" in self.user_dict[user]: self.user_dict[user]["model_cost"][model] = cost + self.user_dict[user][ "model_cost" ].get(model, 0) else: self.user_dict[user]["model_cost"] = {model: cost}
self._save_data_thread() # [Non-Blocking] Update persistent storage without blocking execution return {"user": self.user_dict[user]}
def get_current_cost(self, user): return self.user_dict[user].get("current_cost", 0)
def get_model_cost(self, user): return self.user_dict[user].get("model_cost", 0)
def is_valid_user(self, user: str) -> bool: return user in self.user_dict
def get_users(self): return list(self.user_dict.keys())
def reset_cost(self, user): self.user_dict[user]["current_cost"] = 0 self.user_dict[user]["model_cost"] = {} return {"user": self.user_dict[user]}
def reset_on_duration(self, user: str): # Get current and creation time last_updated_at = self.user_dict[user]["last_updated_at"] current_time = time.time()
# Convert duration from days to seconds duration_in_seconds = self.user_dict[user]["duration"] * 24 * 60 * 60
# Check if duration has elapsed if current_time - last_updated_at >= duration_in_seconds: # Reset cost if duration has elapsed and update the creation time self.reset_cost(user) self.user_dict[user]["last_updated_at"] = current_time self._save_data_thread() # Save the data
def update_budget_all_users(self): for user in self.get_users(): if "duration" in self.user_dict[user]: self.reset_on_duration(user)
def _save_data_thread(self): thread = threading.Thread( target=self.save_data ) # [Non-Blocking]: saves data without blocking execution thread.start()
def save_data(self): if self.client_type == "local": import json
# save the user dict with open("user_cost.json", "w") as json_file: json.dump( self.user_dict, json_file, indent=4 ) # Indent for pretty formatting return {"status": "success"} elif self.client_type == "hosted": url = self.api_base + "/set_budget" headers = {"Content-Type": "application/json"} data = {"project_name": self.project_name, "user_dict": self.user_dict} response = requests.post(url, headers=headers, json=data) response = response.json() return response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678# +-----------------------------------------------+# | |# | Give Feedback / Get Help |# | https://github.com/BerriAI/litellm/issues/new |# | |# +-----------------------------------------------+## Thank you users! We ❤️ you! - Krrish & Ishaan
import litellmimport time, loggingimport json, traceback, ast, hashlibfrom typing import Optional, Literal, List, Union, Anyfrom openai._models import BaseModel as OpenAIObject
def print_verbose(print_statement): try: if litellm.set_verbose: print(print_statement) # noqa except: pass
class BaseCache: def set_cache(self, key, value, **kwargs): raise NotImplementedError
def get_cache(self, key, **kwargs): raise NotImplementedError
class InMemoryCache(BaseCache): def __init__(self): # if users don't provider one, use the default litellm cache self.cache_dict = {} self.ttl_dict = {}
def set_cache(self, key, value, **kwargs): self.cache_dict[key] = value if "ttl" in kwargs: self.ttl_dict[key] = time.time() + kwargs["ttl"]
def get_cache(self, key, **kwargs): if key in self.cache_dict: if key in self.ttl_dict: if time.time() > self.ttl_dict[key]: self.cache_dict.pop(key, None) return None original_cached_response = self.cache_dict[key] try: cached_response = json.loads(original_cached_response) except: cached_response = original_cached_response return cached_response return None
def flush_cache(self): self.cache_dict.clear() self.ttl_dict.clear()
class RedisCache(BaseCache): def __init__(self, host=None, port=None, password=None, **kwargs): import redis
# if users don't provider one, use the default litellm cache from ._redis import get_redis_client
redis_kwargs = {} if host is not None: redis_kwargs["host"] = host if port is not None: redis_kwargs["port"] = port if password is not None: redis_kwargs["password"] = password
redis_kwargs.update(kwargs)
self.redis_client = get_redis_client(**redis_kwargs)
def set_cache(self, key, value, **kwargs): ttl = kwargs.get("ttl", None) print_verbose(f"Set Redis Cache: key: {key}\nValue {value}") try: self.redis_client.set(name=key, value=str(value), ex=ttl) except Exception as e: # NON blocking - notify users Redis is throwing an exception logging.debug("LiteLLM Caching: set() - Got exception from REDIS : ", e)
def get_cache(self, key, **kwargs): try: print_verbose(f"Get Redis Cache: key: {key}") cached_response = self.redis_client.get(key) print_verbose( f"Got Redis Cache: key: {key}, cached_response {cached_response}" ) if cached_response != None: # cached_response is in `b{} convert it to ModelResponse cached_response = cached_response.decode( "utf-8" ) # Convert bytes to string try: cached_response = json.loads( cached_response ) # Convert string to dictionary except: cached_response = ast.literal_eval(cached_response) return cached_response except Exception as e: # NON blocking - notify users Redis is throwing an exception traceback.print_exc() logging.debug("LiteLLM Caching: get() - Got exception from REDIS: ", e)
def flush_cache(self): self.redis_client.flushall()
class S3Cache(BaseCache): def __init__( self, s3_bucket_name, s3_region_name=None, s3_api_version=None, s3_use_ssl=True, s3_verify=None, s3_endpoint_url=None, s3_aws_access_key_id=None, s3_aws_secret_access_key=None, s3_aws_session_token=None, s3_config=None, **kwargs, ): import boto3
self.bucket_name = s3_bucket_name # Create an S3 client with custom endpoint URL self.s3_client = boto3.client( "s3", region_name=s3_region_name, endpoint_url=s3_endpoint_url, api_version=s3_api_version, use_ssl=s3_use_ssl, verify=s3_verify, aws_access_key_id=s3_aws_access_key_id, aws_secret_access_key=s3_aws_secret_access_key, aws_session_token=s3_aws_session_token, config=s3_config, **kwargs, )
def set_cache(self, key, value, **kwargs): try: print_verbose(f"LiteLLM SET Cache - S3. Key={key}. Value={value}") ttl = kwargs.get("ttl", None) # Convert value to JSON before storing in S3 serialized_value = json.dumps(value) if ttl is not None: cache_control = f"immutable, max-age={ttl}, s-maxage={ttl}" import datetime
# Calculate expiration time expiration_time = datetime.datetime.now() + ttl
# Upload the data to S3 with the calculated expiration time self.s3_client.put_object( Bucket=self.bucket_name, Key=key, Body=serialized_value, Expires=expiration_time, CacheControl=cache_control, ContentType="application/json", ContentLanguage="en", ContentDisposition=f"inline; filename=\"{key}.json\"" ) else: cache_control = "immutable, max-age=31536000, s-maxage=31536000" # Upload the data to S3 without specifying Expires self.s3_client.put_object( Bucket=self.bucket_name, Key=key, Body=serialized_value, CacheControl=cache_control, ContentType="application/json", ContentLanguage="en", ContentDisposition=f"inline; filename=\"{key}.json\"" ) except Exception as e: # NON blocking - notify users S3 is throwing an exception print_verbose(f"S3 Caching: set_cache() - Got exception from S3: {e}")
def get_cache(self, key, **kwargs): import boto3, botocore
try: print_verbose(f"Get S3 Cache: key: {key}") # Download the data from S3 cached_response = self.s3_client.get_object( Bucket=self.bucket_name, Key=key )
if cached_response != None: # cached_response is in `b{} convert it to ModelResponse cached_response = ( cached_response["Body"].read().decode("utf-8") ) # Convert bytes to string try: cached_response = json.loads( cached_response ) # Convert string to dictionary except Exception as e: cached_response = ast.literal_eval(cached_response) if type(cached_response) is not dict: cached_response = dict(cached_response) print_verbose( f"Got S3 Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}" )
return cached_response except botocore.exceptions.ClientError as e: if e.response["Error"]["Code"] == "NoSuchKey": print_verbose( f"S3 Cache: The specified key '{key}' does not exist in the S3 bucket." ) return None
except Exception as e: # NON blocking - notify users S3 is throwing an exception traceback.print_exc() print_verbose(f"S3 Caching: get_cache() - Got exception from S3: {e}")
def flush_cache(self): pass
class DualCache(BaseCache): """ This updates both Redis and an in-memory cache simultaneously. When data is updated or inserted, it is written to both the in-memory cache + Redis. This ensures that even if Redis hasn't been updated yet, the in-memory cache reflects the most recent data. """
def __init__( self, in_memory_cache: Optional[InMemoryCache] = None, redis_cache: Optional[RedisCache] = None, ) -> None: super().__init__() # If in_memory_cache is not provided, use the default InMemoryCache self.in_memory_cache = in_memory_cache or InMemoryCache() # If redis_cache is not provided, use the default RedisCache self.redis_cache = redis_cache
def set_cache(self, key, value, local_only: bool = False, **kwargs): # Update both Redis and in-memory cache try: print_verbose(f"set cache: key: {key}; value: {value}") if self.in_memory_cache is not None: self.in_memory_cache.set_cache(key, value, **kwargs)
if self.redis_cache is not None and local_only == False: self.redis_cache.set_cache(key, value, **kwargs) except Exception as e: print_verbose(e)
def get_cache(self, key, local_only: bool = False, **kwargs): # Try to fetch from in-memory cache first try: print_verbose(f"get cache: cache key: {key}; local_only: {local_only}") result = None if self.in_memory_cache is not None: in_memory_result = self.in_memory_cache.get_cache(key, **kwargs)
print_verbose(f"in_memory_result: {in_memory_result}") if in_memory_result is not None: result = in_memory_result
if result is None and self.redis_cache is not None and local_only == False: # If not found in in-memory cache, try fetching from Redis redis_result = self.redis_cache.get_cache(key, **kwargs)
if redis_result is not None: # Update in-memory cache with the value from Redis self.in_memory_cache.set_cache(key, redis_result, **kwargs)
result = redis_result
print_verbose(f"get cache: cache result: {result}") return result except Exception as e: traceback.print_exc()
def flush_cache(self): if self.in_memory_cache is not None: self.in_memory_cache.flush_cache() if self.redis_cache is not None: self.redis_cache.flush_cache()
#### LiteLLM.Completion / Embedding Cache ####class Cache: def __init__( self, type: Optional[Literal["local", "redis", "s3"]] = "local", host: Optional[str] = None, port: Optional[str] = None, password: Optional[str] = None, supported_call_types: Optional[ List[Literal["completion", "acompletion", "embedding", "aembedding"]] ] = ["completion", "acompletion", "embedding", "aembedding"], # s3 Bucket, boto3 configuration s3_bucket_name: Optional[str] = None, s3_region_name: Optional[str] = None, s3_api_version: Optional[str] = None, s3_use_ssl: Optional[bool] = True, s3_verify: Optional[Union[bool, str]] = None, s3_endpoint_url: Optional[str] = None, s3_aws_access_key_id: Optional[str] = None, s3_aws_secret_access_key: Optional[str] = None, s3_aws_session_token: Optional[str] = None, s3_config: Optional[Any] = None, **kwargs, ): """ Initializes the cache based on the given type.
Args: type (str, optional): The type of cache to initialize. Can be "local" or "redis". Defaults to "local". host (str, optional): The host address for the Redis cache. Required if type is "redis". port (int, optional): The port number for the Redis cache. Required if type is "redis". password (str, optional): The password for the Redis cache. Required if type is "redis". supported_call_types (list, optional): List of call types to cache for. Defaults to cache == on for all call types. **kwargs: Additional keyword arguments for redis.Redis() cache
Raises: ValueError: If an invalid cache type is provided.
Returns: None. Cache is set as a litellm param """ if type == "redis": self.cache: BaseCache = RedisCache(host, port, password, **kwargs) if type == "local": self.cache = InMemoryCache() if type == "s3": self.cache = S3Cache( s3_bucket_name=s3_bucket_name, s3_region_name=s3_region_name, s3_api_version=s3_api_version, s3_use_ssl=s3_use_ssl, s3_verify=s3_verify, s3_endpoint_url=s3_endpoint_url, s3_aws_access_key_id=s3_aws_access_key_id, s3_aws_secret_access_key=s3_aws_secret_access_key, s3_aws_session_token=s3_aws_session_token, s3_config=s3_config, **kwargs, ) if "cache" not in litellm.input_callback: litellm.input_callback.append("cache") if "cache" not in litellm.success_callback: litellm.success_callback.append("cache") if "cache" not in litellm._async_success_callback: litellm._async_success_callback.append("cache") self.supported_call_types = supported_call_types # default to ["completion", "acompletion", "embedding", "aembedding"] self.type = type
def get_cache_key(self, *args, **kwargs): """ Get the cache key for the given arguments.
Args: *args: args to litellm.completion() or embedding() **kwargs: kwargs to litellm.completion() or embedding()
Returns: str: The cache key generated from the arguments, or None if no cache key could be generated. """ cache_key = "" print_verbose(f"\nGetting Cache key. Kwargs: {kwargs}")
# for streaming, we use preset_cache_key. It's created in wrapper(), we do this because optional params like max_tokens, get transformed for bedrock -> max_new_tokens if kwargs.get("litellm_params", {}).get("preset_cache_key", None) is not None: print_verbose(f"\nReturning preset cache key: {cache_key}") return kwargs.get("litellm_params", {}).get("preset_cache_key", None)
# sort kwargs by keys, since model: [gpt-4, temperature: 0.2, max_tokens: 200] == [temperature: 0.2, max_tokens: 200, model: gpt-4] completion_kwargs = [ "model", "messages", "temperature", "top_p", "n", "stop", "max_tokens", "presence_penalty", "frequency_penalty", "logit_bias", "user", "response_format", "seed", "tools", "tool_choice", ] embedding_only_kwargs = [ "input", "encoding_format", ] # embedding kwargs = model, input, user, encoding_format. Model, user are checked in completion_kwargs
# combined_kwargs - NEEDS to be ordered across get_cache_key(). Do not use a set() combined_kwargs = completion_kwargs + embedding_only_kwargs for param in combined_kwargs: # ignore litellm params here if param in kwargs: # check if param == model and model_group is passed in, then override model with model_group if param == "model": model_group = None caching_group = None metadata = kwargs.get("metadata", None) litellm_params = kwargs.get("litellm_params", {}) if metadata is not None: model_group = metadata.get("model_group") model_group = metadata.get("model_group", None) caching_groups = metadata.get("caching_groups", None) if caching_groups: for group in caching_groups: if model_group in group: caching_group = group break if litellm_params is not None: metadata = litellm_params.get("metadata", None) if metadata is not None: model_group = metadata.get("model_group", None) caching_groups = metadata.get("caching_groups", None) if caching_groups: for group in caching_groups: if model_group in group: caching_group = group break param_value = ( caching_group or model_group or kwargs[param] ) # use caching_group, if set then model_group if it exists, else use kwargs["model"] else: if kwargs[param] is None: continue # ignore None params param_value = kwargs[param] cache_key += f"{str(param)}: {str(param_value)}" print_verbose(f"\nCreated cache key: {cache_key}") # Use hashlib to create a sha256 hash of the cache key hash_object = hashlib.sha256(cache_key.encode()) # Hexadecimal representation of the hash hash_hex = hash_object.hexdigest() print_verbose(f"Hashed cache key (SHA-256): {hash_hex}") return hash_hex
def generate_streaming_content(self, content): chunk_size = 5 # Adjust the chunk size as needed for i in range(0, len(content), chunk_size): yield { "choices": [ { "delta": { "role": "assistant", "content": content[i : i + chunk_size], } } ] } time.sleep(0.02)
def get_cache(self, *args, **kwargs): """ Retrieves the cached result for the given arguments.
Args: *args: args to litellm.completion() or embedding() **kwargs: kwargs to litellm.completion() or embedding()
Returns: The cached result if it exists, otherwise None. """ try: # never block execution if "cache_key" in kwargs: cache_key = kwargs["cache_key"] else: cache_key = self.get_cache_key(*args, **kwargs) if cache_key is not None: cache_control_args = kwargs.get("cache", {}) max_age = cache_control_args.get( "s-max-age", cache_control_args.get("s-maxage", float("inf")) ) cached_result = self.cache.get_cache(cache_key) # Check if a timestamp was stored with the cached response if ( cached_result is not None and isinstance(cached_result, dict) and "timestamp" in cached_result and max_age is not None ): timestamp = cached_result["timestamp"] current_time = time.time()
# Calculate age of the cached response response_age = current_time - timestamp
# Check if the cached response is older than the max-age if response_age > max_age: print_verbose( f"Cached response for key {cache_key} is too old. Max-age: {max_age}s, Age: {response_age}s" ) return None # Cached response is too old
# If the response is fresh, or there's no max-age requirement, return the cached response # cached_response is in `b{} convert it to ModelResponse cached_response = cached_result.get("response") try: if isinstance(cached_response, dict): pass else: cached_response = json.loads( cached_response ) # Convert string to dictionary except: cached_response = ast.literal_eval(cached_response) return cached_response return cached_result except Exception as e: print_verbose(f"An exception occurred: {traceback.format_exc()}") return None
def add_cache(self, result, *args, **kwargs): """ Adds a result to the cache.
Args: *args: args to litellm.completion() or embedding() **kwargs: kwargs to litellm.completion() or embedding()
Returns: None """ try: if "cache_key" in kwargs: cache_key = kwargs["cache_key"] else: cache_key = self.get_cache_key(*args, **kwargs) if cache_key is not None: if isinstance(result, OpenAIObject): result = result.model_dump_json()
## Get Cache-Controls ## if kwargs.get("cache", None) is not None and isinstance( kwargs.get("cache"), dict ): for k, v in kwargs.get("cache").items(): if k == "ttl": kwargs["ttl"] = v cached_data = {"timestamp": time.time(), "response": result} self.cache.set_cache(cache_key, cached_data, **kwargs) except Exception as e: print_verbose(f"LiteLLM Cache: Excepton add_cache: {str(e)}") traceback.print_exc() pass
async def _async_add_cache(self, result, *args, **kwargs): self.add_cache(result, *args, **kwargs)
def enable_cache( type: Optional[Literal["local", "redis", "s3"]] = "local", host: Optional[str] = None, port: Optional[str] = None, password: Optional[str] = None, supported_call_types: Optional[ List[Literal["completion", "acompletion", "embedding", "aembedding"]] ] = ["completion", "acompletion", "embedding", "aembedding"], **kwargs,): """ Enable cache with the specified configuration.
Args: type (Optional[Literal["local", "redis"]]): The type of cache to enable. Defaults to "local". host (Optional[str]): The host address of the cache server. Defaults to None. port (Optional[str]): The port number of the cache server. Defaults to None. password (Optional[str]): The password for the cache server. Defaults to None. supported_call_types (Optional[List[Literal["completion", "acompletion", "embedding", "aembedding"]]]): The supported call types for the cache. Defaults to ["completion", "acompletion", "embedding", "aembedding"]. **kwargs: Additional keyword arguments.
Returns: None
Raises: None """ print_verbose("LiteLLM: Enabling Cache") if "cache" not in litellm.input_callback: litellm.input_callback.append("cache") if "cache" not in litellm.success_callback: litellm.success_callback.append("cache") if "cache" not in litellm._async_success_callback: litellm._async_success_callback.append("cache")
if litellm.cache == None: litellm.cache = Cache( type=type, host=host, port=port, password=password, supported_call_types=supported_call_types, **kwargs, ) print_verbose(f"LiteLLM: Cache enabled, litellm.cache={litellm.cache}") print_verbose(f"LiteLLM Cache: {vars(litellm.cache)}")
def update_cache( type: Optional[Literal["local", "redis"]] = "local", host: Optional[str] = None, port: Optional[str] = None, password: Optional[str] = None, supported_call_types: Optional[ List[Literal["completion", "acompletion", "embedding", "aembedding"]] ] = ["completion", "acompletion", "embedding", "aembedding"], **kwargs,): """ Update the cache for LiteLLM.
Args: type (Optional[Literal["local", "redis"]]): The type of cache. Defaults to "local". host (Optional[str]): The host of the cache. Defaults to None. port (Optional[str]): The port of the cache. Defaults to None. password (Optional[str]): The password for the cache. Defaults to None. supported_call_types (Optional[List[Literal["completion", "acompletion", "embedding", "aembedding"]]]): The supported call types for the cache. Defaults to ["completion", "acompletion", "embedding", "aembedding"]. **kwargs: Additional keyword arguments for the cache.
Returns: None
""" print_verbose("LiteLLM: Updating Cache") litellm.cache = Cache( type=type, host=host, port=port, password=password, supported_call_types=supported_call_types, **kwargs, ) print_verbose(f"LiteLLM: Cache Updated, litellm.cache={litellm.cache}") print_verbose(f"LiteLLM Cache: {vars(litellm.cache)}")
def disable_cache(): """ Disable the cache used by LiteLLM.
This function disables the cache used by the LiteLLM module. It removes the cache-related callbacks from the input_callback, success_callback, and _async_success_callback lists. It also sets the litellm.cache attribute to None.
Parameters: None
Returns: None """ from contextlib import suppress
print_verbose("LiteLLM: Disabling Cache") with suppress(ValueError): litellm.input_callback.remove("cache") litellm.success_callback.remove("cache") litellm._async_success_callback.remove("cache")
litellm.cache = None print_verbose(f"LiteLLM: Cache disabled, litellm.cache={litellm.cache}")12345{ "gpt-3.5-turbo-0613": 0.00015000000000000001, "claude-2": 0.00016454, "gpt-4-0613": 0.015408}12345678910111213141516171819202122232425262728293031323334353637383940414243# # set AUTH STRATEGY FOR LLM APIs - Defaults to using Environment Variables# AUTH_STRATEGY = "ENV" # ENV or DYNAMIC, ENV always reads from environment variables, DYNAMIC reads request headers to set LLM api keys
# OPENAI_API_KEY = ""
# HUGGINGFACE_API_KEY=""
# TOGETHERAI_API_KEY=""
# REPLICATE_API_KEY=""
# ## bedrock / sagemaker# AWS_ACCESS_KEY_ID = "" # AWS_SECRET_ACCESS_KEY = ""
# AZURE_API_KEY = ""# AZURE_API_BASE = ""# AZURE_API_VERSION = ""
# ANTHROPIC_API_KEY = ""
# COHERE_API_KEY = ""
# ## CONFIG FILE ## # # CONFIG_FILE_PATH = "" # uncomment to point to config file
# ## LOGGING ##
# SET_VERBOSE = "False" # set to 'True' to see detailed input/output logs
# ### LANGFUSE# LANGFUSE_PUBLIC_KEY = ""# LANGFUSE_SECRET_KEY = ""# # Optional, defaults to https://cloud.langfuse.com# LANGFUSE_HOST = "" # optional
# ## CACHING ##
# ### REDIS# REDIS_HOST = "" # REDIS_PORT = "" # REDIS_PASSWORD = "" 12345678910# FROM python:3.10
# ENV LITELLM_CONFIG_PATH="/litellm.secrets.toml"# COPY . /app# WORKDIR /app# RUN pip install -r requirements.txt
# EXPOSE $PORT
# CMD exec uvicorn main:app --host 0.0.0.0 --port $PORT --workers 10 123# litellm-server [experimental]
Deprecated. See litellm/proxy12# from .main import *# from .server_utils import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193# import os, traceback# from fastapi import FastAPI, Request, HTTPException# from fastapi.routing import APIRouter# from fastapi.responses import StreamingResponse, FileResponse# from fastapi.middleware.cors import CORSMiddleware# import json, sys# from typing import Optional# sys.path.insert(# 0, os.path.abspath("../")# ) # Adds the parent directory to the system path - for litellm local dev# import litellm
# try:# from litellm.deprecated_litellm_server.server_utils import set_callbacks, load_router_config, print_verbose# except ImportError:# from litellm.deprecated_litellm_server.server_utils import set_callbacks, load_router_config, print_verbose# import dotenv# dotenv.load_dotenv() # load env variables
# app = FastAPI(docs_url="/", title="LiteLLM API")# router = APIRouter()# origins = ["*"]
# app.add_middleware(# CORSMiddleware,# allow_origins=origins,# allow_credentials=True,# allow_methods=["*"],# allow_headers=["*"],# )# #### GLOBAL VARIABLES ##### llm_router: Optional[litellm.Router] = None# llm_model_list: Optional[list] = None# server_settings: Optional[dict] = None
# set_callbacks() # sets litellm callbacks for logging if they exist in the environment
# if "CONFIG_FILE_PATH" in os.environ:# llm_router, llm_model_list, server_settings = load_router_config(router=llm_router, config_file_path=os.getenv("CONFIG_FILE_PATH"))# else:# llm_router, llm_model_list, server_settings = load_router_config(router=llm_router)# #### API ENDPOINTS ##### @router.get("/v1/models")# @router.get("/models") # if project requires model list# def model_list():# all_models = litellm.utils.get_valid_models()# if llm_model_list:# all_models += llm_model_list# return dict(# data=[# {# "id": model,# "object": "model",# "created": 1677610602,# "owned_by": "openai",# }# for model in all_models# ],# object="list",# )# # for streaming# def data_generator(response):
# for chunk in response:
# yield f"data: {json.dumps(chunk)}\n\n"
# @router.post("/v1/completions")# @router.post("/completions")# async def completion(request: Request):# data = await request.json()# response = litellm.completion(# **data# )# if 'stream' in data and data['stream'] == True: # use generate_responses to stream responses# return StreamingResponse(data_generator(response), media_type='text/event-stream')# return response
# @router.post("/v1/embeddings")# @router.post("/embeddings")# async def embedding(request: Request):# try:# data = await request.json()# # default to always using the "ENV" variables, only if AUTH_STRATEGY==DYNAMIC then reads headers# if os.getenv("AUTH_STRATEGY", None) == "DYNAMIC" and "authorization" in request.headers: # if users pass LLM api keys as part of header# api_key = request.headers.get("authorization")# api_key = api_key.replace("Bearer", "").strip() # type: ignore# if len(api_key.strip()) > 0:# api_key = api_key# data["api_key"] = api_key# response = litellm.embedding(# **data# )# return response# except Exception as e:# error_traceback = traceback.format_exc()# error_msg = f"{str(e)}\n\n{error_traceback}"# return {"error": error_msg}
# @router.post("/v1/chat/completions")# @router.post("/chat/completions")# @router.post("/openai/deployments/{model:path}/chat/completions") # azure compatible endpoint# async def chat_completion(request: Request, model: Optional[str] = None):# global llm_model_list, server_settings# try:# data = await request.json()# server_model = server_settings.get("completion_model", None) if server_settings else None# data["model"] = server_model or model or data["model"]# ## CHECK KEYS ### # default to always using the "ENV" variables, only if AUTH_STRATEGY==DYNAMIC then reads headers# # env_validation = litellm.validate_environment(model=data["model"])# # if (env_validation['keys_in_environment'] is False or os.getenv("AUTH_STRATEGY", None) == "DYNAMIC") and ("authorization" in request.headers or "api-key" in request.headers): # if users pass LLM api keys as part of header# # if "authorization" in request.headers:# # api_key = request.headers.get("authorization")# # elif "api-key" in request.headers:# # api_key = request.headers.get("api-key")# # print(f"api_key in headers: {api_key}")# # if " " in api_key:# # api_key = api_key.split(" ")[1]# # print(f"api_key split: {api_key}")# # if len(api_key) > 0:# # api_key = api_key# # data["api_key"] = api_key# # print(f"api_key in data: {api_key}")# ## CHECK CONFIG ### if llm_model_list and data["model"] in [m["model_name"] for m in llm_model_list]:# for m in llm_model_list:# if data["model"] == m["model_name"]:# for key, value in m["litellm_params"].items():# data[key] = value# break# response = litellm.completion(# **data# )# if 'stream' in data and data['stream'] == True: # use generate_responses to stream responses# return StreamingResponse(data_generator(response), media_type='text/event-stream')# return response# except Exception as e:# error_traceback = traceback.format_exc()
# error_msg = f"{str(e)}\n\n{error_traceback}"# # return {"error": error_msg}# raise HTTPException(status_code=500, detail=error_msg)
# @router.post("/router/completions")# async def router_completion(request: Request):# global llm_router# try:# data = await request.json()# if "model_list" in data:# llm_router = litellm.Router(model_list=data.pop("model_list"))# if llm_router is None:# raise Exception("Save model list via config.yaml. Eg.: ` docker build -t myapp --build-arg CONFIG_FILE=myconfig.yaml .` or pass it in as model_list=[..] as part of the request body")
# # openai.ChatCompletion.create replacement# response = await llm_router.acompletion(model="gpt-3.5-turbo",# messages=[{"role": "user", "content": "Hey, how's it going?"}])
# if 'stream' in data and data['stream'] == True: # use generate_responses to stream responses# return StreamingResponse(data_generator(response), media_type='text/event-stream')# return response# except Exception as e:# error_traceback = traceback.format_exc()# error_msg = f"{str(e)}\n\n{error_traceback}"# return {"error": error_msg}
# @router.post("/router/embedding")# async def router_embedding(request: Request):# global llm_router# try:# data = await request.json()# if "model_list" in data:# llm_router = litellm.Router(model_list=data.pop("model_list"))# if llm_router is None:# raise Exception("Save model list via config.yaml. Eg.: ` docker build -t myapp --build-arg CONFIG_FILE=myconfig.yaml .` or pass it in as model_list=[..] as part of the request body")
# response = await llm_router.aembedding(model="gpt-3.5-turbo", # type: ignore# messages=[{"role": "user", "content": "Hey, how's it going?"}])
# if 'stream' in data and data['stream'] == True: # use generate_responses to stream responses# return StreamingResponse(data_generator(response), media_type='text/event-stream')# return response# except Exception as e:# error_traceback = traceback.format_exc()# error_msg = f"{str(e)}\n\n{error_traceback}"# return {"error": error_msg}
# @router.get("/")# async def home(request: Request):# return "LiteLLM: RUNNING"
# app.include_router(router)1234567# openai# fastapi# uvicorn# boto3# litellm# python-dotenv# redis12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# import os, litellm# import pkg_resources# import dotenv# dotenv.load_dotenv() # load env variables
# def print_verbose(print_statement):# pass
# def get_package_version(package_name):# try:# package = pkg_resources.get_distribution(package_name)# return package.version# except pkg_resources.DistributionNotFound:# return None
# # Usage example# package_name = "litellm"# version = get_package_version(package_name)# if version:# print_verbose(f"The version of {package_name} is {version}")# else:# print_verbose(f"{package_name} is not installed")# import yaml# import dotenv# from typing import Optional# dotenv.load_dotenv() # load env variables
# def set_callbacks():# ## LOGGING# if len(os.getenv("SET_VERBOSE", "")) > 0:# if os.getenv("SET_VERBOSE") == "True":# litellm.set_verbose = True# print_verbose("\033[92mLiteLLM: Switched on verbose logging\033[0m")# else:# litellm.set_verbose = False
# ### LANGFUSE# if (len(os.getenv("LANGFUSE_PUBLIC_KEY", "")) > 0 and len(os.getenv("LANGFUSE_SECRET_KEY", ""))) > 0 or len(os.getenv("LANGFUSE_HOST", "")) > 0:# litellm.success_callback = ["langfuse"]# print_verbose("\033[92mLiteLLM: Switched on Langfuse feature\033[0m")
# ## CACHING# ### REDIS# # if len(os.getenv("REDIS_HOST", "")) > 0 and len(os.getenv("REDIS_PORT", "")) > 0 and len(os.getenv("REDIS_PASSWORD", "")) > 0:# # print(f"redis host: {os.getenv('REDIS_HOST')}; redis port: {os.getenv('REDIS_PORT')}; password: {os.getenv('REDIS_PASSWORD')}")# # from litellm.caching import Cache# # litellm.cache = Cache(type="redis", host=os.getenv("REDIS_HOST"), port=os.getenv("REDIS_PORT"), password=os.getenv("REDIS_PASSWORD"))# # print("\033[92mLiteLLM: Switched on Redis caching\033[0m")
# def load_router_config(router: Optional[litellm.Router], config_file_path: Optional[str]='/app/config.yaml'):# config = {}# server_settings = {}# try:# if os.path.exists(config_file_path): # type: ignore# with open(config_file_path, 'r') as file: # type: ignore# config = yaml.safe_load(file)# else:# pass# except:# pass
# ## SERVER SETTINGS (e.g. default completion model = 'ollama/mistral')# server_settings = config.get("server_settings", None)# if server_settings:# server_settings = server_settings
# ## LITELLM MODULE SETTINGS (e.g. litellm.drop_params=True,..)# litellm_settings = config.get('litellm_settings', None)# if litellm_settings:# for key, value in litellm_settings.items():# setattr(litellm, key, value)
# ## MODEL LIST# model_list = config.get('model_list', None)# if model_list:# router = litellm.Router(model_list=model_list)
# ## ENVIRONMENT VARIABLES# environment_variables = config.get('environment_variables', None)# if environment_variables:# for key, value in environment_variables.items():# os.environ[key] = value
# return router, model_list, server_settings123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200# +-----------------------------------------------+# | |# | Give Feedback / Get Help |# | https://github.com/BerriAI/litellm/issues/new |# | |# +-----------------------------------------------+## Thank you users! We ❤️ you! - Krrish & Ishaan
## LiteLLM versions of the OpenAI Exception Types
from openai import ( AuthenticationError, BadRequestError, NotFoundError, RateLimitError, APIStatusError, OpenAIError, APIError, APITimeoutError, APIConnectionError, APIResponseValidationError, UnprocessableEntityError,)import httpx
class AuthenticationError(AuthenticationError): # type: ignore def __init__(self, message, llm_provider, model, response: httpx.Response): self.status_code = 401 self.message = message self.llm_provider = llm_provider self.model = model super().__init__( self.message, response=response, body=None ) # Call the base class constructor with the parameters it needs
# raise when invalid models passed, example gpt-8class NotFoundError(NotFoundError): # type: ignore def __init__(self, message, model, llm_provider, response: httpx.Response): self.status_code = 404 self.message = message self.model = model self.llm_provider = llm_provider super().__init__( self.message, response=response, body=None ) # Call the base class constructor with the parameters it needs
class BadRequestError(BadRequestError): # type: ignore def __init__(self, message, model, llm_provider, response: httpx.Response): self.status_code = 400 self.message = message self.model = model self.llm_provider = llm_provider super().__init__( self.message, response=response, body=None ) # Call the base class constructor with the parameters it needs
class UnprocessableEntityError(UnprocessableEntityError): # type: ignore def __init__(self, message, model, llm_provider, response: httpx.Response): self.status_code = 422 self.message = message self.model = model self.llm_provider = llm_provider super().__init__( self.message, response=response, body=None ) # Call the base class constructor with the parameters it needs
class Timeout(APITimeoutError): # type: ignore def __init__(self, message, model, llm_provider): self.status_code = 408 self.message = message self.model = model self.llm_provider = llm_provider request = httpx.Request(method="POST", url="https://api.openai.com/v1") super().__init__( request=request ) # Call the base class constructor with the parameters it needs
class RateLimitError(RateLimitError): # type: ignore def __init__(self, message, llm_provider, model, response: httpx.Response): self.status_code = 429 self.message = message self.llm_provider = llm_provider self.modle = model super().__init__( self.message, response=response, body=None ) # Call the base class constructor with the parameters it needs
# sub class of rate limit error - meant to give more granularity for error handling context window exceeded errorsclass ContextWindowExceededError(BadRequestError): # type: ignore def __init__(self, message, model, llm_provider, response: httpx.Response): self.status_code = 400 self.message = message self.model = model self.llm_provider = llm_provider super().__init__( message=self.message, model=self.model, # type: ignore llm_provider=self.llm_provider, # type: ignore response=response, ) # Call the base class constructor with the parameters it needs
class ContentPolicyViolationError(BadRequestError): # type: ignore # Error code: 400 - {'error': {'code': 'content_policy_violation', 'message': 'Your request was rejected as a result of our safety system. Image descriptions generated from your prompt may contain text that is not allowed by our safety system. If you believe this was done in error, your request may succeed if retried, or by adjusting your prompt.', 'param': None, 'type': 'invalid_request_error'}} def __init__(self, message, model, llm_provider, response: httpx.Response): self.status_code = 400 self.message = message self.model = model self.llm_provider = llm_provider super().__init__( message=self.message, model=self.model, # type: ignore llm_provider=self.llm_provider, # type: ignore response=response, ) # Call the base class constructor with the parameters it needs
class ServiceUnavailableError(APIStatusError): # type: ignore def __init__(self, message, llm_provider, model, response: httpx.Response): self.status_code = 503 self.message = message self.llm_provider = llm_provider self.model = model super().__init__( self.message, response=response, body=None ) # Call the base class constructor with the parameters it needs
# raise this when the API returns an invalid response object - https://github.com/openai/openai-python/blob/1be14ee34a0f8e42d3f9aa5451aa4cb161f1781f/openai/api_requestor.py#L401class APIError(APIError): # type: ignore def __init__( self, status_code, message, llm_provider, model, request: httpx.Request ): self.status_code = status_code self.message = message self.llm_provider = llm_provider self.model = model super().__init__(self.message, request=request, body=None) # type: ignore
# raised if an invalid request (not get, delete, put, post) is madeclass APIConnectionError(APIConnectionError): # type: ignore def __init__(self, message, llm_provider, model, request: httpx.Request): self.message = message self.llm_provider = llm_provider self.model = model self.status_code = 500 super().__init__(message=self.message, request=request)
# raised if an invalid request (not get, delete, put, post) is madeclass APIResponseValidationError(APIResponseValidationError): # type: ignore def __init__(self, message, llm_provider, model): self.message = message self.llm_provider = llm_provider self.model = model request = httpx.Request(method="POST", url="https://api.openai.com/v1") response = httpx.Response(status_code=500, request=request) super().__init__(response=response, body=None, message=message)
class OpenAIError(OpenAIError): # type: ignore def __init__(self, original_exception): self.status_code = original_exception.http_status super().__init__( http_body=original_exception.http_body, http_status=original_exception.http_status, json_body=original_exception.json_body, headers=original_exception.headers, code=original_exception.code, ) self.llm_provider = "openai"
class BudgetExceededError(Exception): def __init__(self, current_cost, max_budget): self.current_cost = current_cost self.max_budget = max_budget message = f"Budget has been exceeded! Current cost: {current_cost}, Max budget: {max_budget}" super().__init__(message)
## DEPRECATED ##class InvalidRequestError(BadRequestError): # type: ignore def __init__(self, message, model, llm_provider): self.status_code = 400 self.message = message self.model = model self.llm_provider = llm_provider super().__init__( self.message, f"{self.model}" ) # Call the base class constructor with the parameters it needs1from . import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177#### What this does ##### On success + failure, log events to aispend.ioimport dotenv, osimport requests
dotenv.load_dotenv() # Loading env variables using dotenvimport tracebackimport datetime
model_cost = { "gpt-3.5-turbo": { "max_tokens": 4000, "input_cost_per_token": 0.0000015, "output_cost_per_token": 0.000002, }, "gpt-35-turbo": { "max_tokens": 4000, "input_cost_per_token": 0.0000015, "output_cost_per_token": 0.000002, }, # azure model name "gpt-3.5-turbo-0613": { "max_tokens": 4000, "input_cost_per_token": 0.0000015, "output_cost_per_token": 0.000002, }, "gpt-3.5-turbo-0301": { "max_tokens": 4000, "input_cost_per_token": 0.0000015, "output_cost_per_token": 0.000002, }, "gpt-3.5-turbo-16k": { "max_tokens": 16000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.000004, }, "gpt-35-turbo-16k": { "max_tokens": 16000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.000004, }, # azure model name "gpt-3.5-turbo-16k-0613": { "max_tokens": 16000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.000004, }, "gpt-4": { "max_tokens": 8000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.00006, }, "gpt-4-0613": { "max_tokens": 8000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.00006, }, "gpt-4-32k": { "max_tokens": 8000, "input_cost_per_token": 0.00006, "output_cost_per_token": 0.00012, }, "claude-instant-1": { "max_tokens": 100000, "input_cost_per_token": 0.00000163, "output_cost_per_token": 0.00000551, }, "claude-2": { "max_tokens": 100000, "input_cost_per_token": 0.00001102, "output_cost_per_token": 0.00003268, }, "text-bison-001": { "max_tokens": 8192, "input_cost_per_token": 0.000004, "output_cost_per_token": 0.000004, }, "chat-bison-001": { "max_tokens": 4096, "input_cost_per_token": 0.000002, "output_cost_per_token": 0.000002, }, "command-nightly": { "max_tokens": 4096, "input_cost_per_token": 0.000015, "output_cost_per_token": 0.000015, },}
class AISpendLogger: # Class variables or attributes def __init__(self): # Instance variables self.account_id = os.getenv("AISPEND_ACCOUNT_ID") self.api_key = os.getenv("AISPEND_API_KEY")
def price_calculator(self, model, response_obj, start_time, end_time): # try and find if the model is in the model_cost map # else default to the average of the costs prompt_tokens_cost_usd_dollar = 0 completion_tokens_cost_usd_dollar = 0 if model in model_cost: prompt_tokens_cost_usd_dollar = ( model_cost[model]["input_cost_per_token"] * response_obj["usage"]["prompt_tokens"] ) completion_tokens_cost_usd_dollar = ( model_cost[model]["output_cost_per_token"] * response_obj["usage"]["completion_tokens"] ) elif "replicate" in model: # replicate models are charged based on time # llama 2 runs on an nvidia a100 which costs $0.0032 per second - https://replicate.com/replicate/llama-2-70b-chat model_run_time = end_time - start_time # assuming time in seconds cost_usd_dollar = model_run_time * 0.0032 prompt_tokens_cost_usd_dollar = cost_usd_dollar / 2 completion_tokens_cost_usd_dollar = cost_usd_dollar / 2 else: # calculate average input cost input_cost_sum = 0 output_cost_sum = 0 for model in model_cost: input_cost_sum += model_cost[model]["input_cost_per_token"] output_cost_sum += model_cost[model]["output_cost_per_token"] avg_input_cost = input_cost_sum / len(model_cost.keys()) avg_output_cost = output_cost_sum / len(model_cost.keys()) prompt_tokens_cost_usd_dollar = ( model_cost[model]["input_cost_per_token"] * response_obj["usage"]["prompt_tokens"] ) completion_tokens_cost_usd_dollar = ( model_cost[model]["output_cost_per_token"] * response_obj["usage"]["completion_tokens"] ) return prompt_tokens_cost_usd_dollar, completion_tokens_cost_usd_dollar
def log_event(self, model, response_obj, start_time, end_time, print_verbose): # Method definition try: print_verbose( f"AISpend Logging - Enters logging function for model {model}" )
url = f"https://aispend.io/api/v1/accounts/{self.account_id}/data" headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", }
response_timestamp = datetime.datetime.fromtimestamp( int(response_obj["created"]) ).strftime("%Y-%m-%d")
( prompt_tokens_cost_usd_dollar, completion_tokens_cost_usd_dollar, ) = self.price_calculator(model, response_obj, start_time, end_time) prompt_tokens_cost_usd_cent = prompt_tokens_cost_usd_dollar * 100 completion_tokens_cost_usd_cent = completion_tokens_cost_usd_dollar * 100 data = [ { "requests": 1, "requests_context": 1, "context_tokens": response_obj["usage"]["prompt_tokens"], "requests_generated": 1, "generated_tokens": response_obj["usage"]["completion_tokens"], "recorded_date": response_timestamp, "model_id": response_obj["model"], "generated_tokens_cost_usd_cent": prompt_tokens_cost_usd_cent, "context_tokens_cost_usd_cent": completion_tokens_cost_usd_cent, } ]
print_verbose(f"AISpend Logging - final data object: {data}") except: # traceback.print_exc() print_verbose(f"AISpend Logging Error - {traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184#### What this does ##### On success + failure, log events to aispend.ioimport dotenv, osimport requests
dotenv.load_dotenv() # Loading env variables using dotenvimport tracebackimport datetime
model_cost = { "gpt-3.5-turbo": { "max_tokens": 4000, "input_cost_per_token": 0.0000015, "output_cost_per_token": 0.000002, }, "gpt-35-turbo": { "max_tokens": 4000, "input_cost_per_token": 0.0000015, "output_cost_per_token": 0.000002, }, # azure model name "gpt-3.5-turbo-0613": { "max_tokens": 4000, "input_cost_per_token": 0.0000015, "output_cost_per_token": 0.000002, }, "gpt-3.5-turbo-0301": { "max_tokens": 4000, "input_cost_per_token": 0.0000015, "output_cost_per_token": 0.000002, }, "gpt-3.5-turbo-16k": { "max_tokens": 16000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.000004, }, "gpt-35-turbo-16k": { "max_tokens": 16000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.000004, }, # azure model name "gpt-3.5-turbo-16k-0613": { "max_tokens": 16000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.000004, }, "gpt-4": { "max_tokens": 8000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.00006, }, "gpt-4-0613": { "max_tokens": 8000, "input_cost_per_token": 0.000003, "output_cost_per_token": 0.00006, }, "gpt-4-32k": { "max_tokens": 8000, "input_cost_per_token": 0.00006, "output_cost_per_token": 0.00012, }, "claude-instant-1": { "max_tokens": 100000, "input_cost_per_token": 0.00000163, "output_cost_per_token": 0.00000551, }, "claude-2": { "max_tokens": 100000, "input_cost_per_token": 0.00001102, "output_cost_per_token": 0.00003268, }, "text-bison-001": { "max_tokens": 8192, "input_cost_per_token": 0.000004, "output_cost_per_token": 0.000004, }, "chat-bison-001": { "max_tokens": 4096, "input_cost_per_token": 0.000002, "output_cost_per_token": 0.000002, }, "command-nightly": { "max_tokens": 4096, "input_cost_per_token": 0.000015, "output_cost_per_token": 0.000015, },}
class BerriSpendLogger: # Class variables or attributes def __init__(self): # Instance variables self.account_id = os.getenv("BERRISPEND_ACCOUNT_ID")
def price_calculator(self, model, response_obj, start_time, end_time): # try and find if the model is in the model_cost map # else default to the average of the costs prompt_tokens_cost_usd_dollar = 0 completion_tokens_cost_usd_dollar = 0 if model in model_cost: prompt_tokens_cost_usd_dollar = ( model_cost[model]["input_cost_per_token"] * response_obj["usage"]["prompt_tokens"] ) completion_tokens_cost_usd_dollar = ( model_cost[model]["output_cost_per_token"] * response_obj["usage"]["completion_tokens"] ) elif "replicate" in model: # replicate models are charged based on time # llama 2 runs on an nvidia a100 which costs $0.0032 per second - https://replicate.com/replicate/llama-2-70b-chat model_run_time = end_time - start_time # assuming time in seconds cost_usd_dollar = model_run_time * 0.0032 prompt_tokens_cost_usd_dollar = cost_usd_dollar / 2 completion_tokens_cost_usd_dollar = cost_usd_dollar / 2 else: # calculate average input cost input_cost_sum = 0 output_cost_sum = 0 for model in model_cost: input_cost_sum += model_cost[model]["input_cost_per_token"] output_cost_sum += model_cost[model]["output_cost_per_token"] avg_input_cost = input_cost_sum / len(model_cost.keys()) avg_output_cost = output_cost_sum / len(model_cost.keys()) prompt_tokens_cost_usd_dollar = ( model_cost[model]["input_cost_per_token"] * response_obj["usage"]["prompt_tokens"] ) completion_tokens_cost_usd_dollar = ( model_cost[model]["output_cost_per_token"] * response_obj["usage"]["completion_tokens"] ) return prompt_tokens_cost_usd_dollar, completion_tokens_cost_usd_dollar
def log_event( self, model, messages, response_obj, start_time, end_time, print_verbose ): # Method definition try: print_verbose( f"BerriSpend Logging - Enters logging function for model {model}" )
url = f"https://berrispend.berri.ai/spend" headers = {"Content-Type": "application/json"}
( prompt_tokens_cost_usd_dollar, completion_tokens_cost_usd_dollar, ) = self.price_calculator(model, response_obj, start_time, end_time) total_cost = ( prompt_tokens_cost_usd_dollar + completion_tokens_cost_usd_dollar )
response_time = (end_time - start_time).total_seconds() if "response" in response_obj: data = [ { "response_time": response_time, "model_id": response_obj["model"], "total_cost": total_cost, "messages": messages, "response": response_obj["choices"][0]["message"]["content"], "account_id": self.account_id, } ] elif "error" in response_obj: data = [ { "response_time": response_time, "model_id": response_obj["model"], "total_cost": total_cost, "messages": messages, "error": response_obj["error"], "account_id": self.account_id, } ]
print_verbose(f"BerriSpend Logging - final data object: {data}") response = requests.post(url, headers=headers, json=data) except: # traceback.print_exc() print_verbose(f"BerriSpend Logging Error - {traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130#### What this does ##### On success, logs events to Promptlayerimport dotenv, osimport requestsfrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.caching import DualCachefrom typing import Literal
dotenv.load_dotenv() # Loading env variables using dotenvimport traceback
class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callback#callback-class # Class variables or attributes def __init__(self): pass
def log_pre_api_call(self, model, messages, kwargs): pass
def log_post_api_call(self, kwargs, response_obj, start_time, end_time): pass
def log_stream_event(self, kwargs, response_obj, start_time, end_time): pass
def log_success_event(self, kwargs, response_obj, start_time, end_time): pass
def log_failure_event(self, kwargs, response_obj, start_time, end_time): pass
#### ASYNC ####
async def async_log_stream_event(self, kwargs, response_obj, start_time, end_time): pass
async def async_log_pre_api_call(self, model, messages, kwargs): pass
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): pass
async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): pass
#### CALL HOOKS - proxy only #### """ Control the modify incoming / outgoung data before calling the model """
async def async_pre_call_hook( self, user_api_key_dict: UserAPIKeyAuth, cache: DualCache, data: dict, call_type: Literal["completion", "embeddings"], ): pass
async def async_post_call_failure_hook( self, original_exception: Exception, user_api_key_dict: UserAPIKeyAuth ): pass
#### SINGLE-USE #### - https://docs.litellm.ai/docs/observability/custom_callback#using-your-custom-callback-function
def log_input_event(self, model, messages, kwargs, print_verbose, callback_func): try: kwargs["model"] = model kwargs["messages"] = messages kwargs["log_event_type"] = "pre_api_call" callback_func( kwargs, ) print_verbose(f"Custom Logger - model call details: {kwargs}") except: traceback.print_exc() print_verbose(f"Custom Logger Error - {traceback.format_exc()}")
async def async_log_input_event( self, model, messages, kwargs, print_verbose, callback_func ): try: kwargs["model"] = model kwargs["messages"] = messages kwargs["log_event_type"] = "pre_api_call" await callback_func( kwargs, ) print_verbose(f"Custom Logger - model call details: {kwargs}") except: traceback.print_exc() print_verbose(f"Custom Logger Error - {traceback.format_exc()}")
def log_event( self, kwargs, response_obj, start_time, end_time, print_verbose, callback_func ): # Method definition try: kwargs["log_event_type"] = "post_api_call" callback_func( kwargs, # kwargs to func response_obj, start_time, end_time, ) print_verbose(f"Custom Logger - final response object: {response_obj}") except: # traceback.print_exc() print_verbose(f"Custom Logger Error - {traceback.format_exc()}") pass
async def async_log_event( self, kwargs, response_obj, start_time, end_time, print_verbose, callback_func ): # Method definition try: kwargs["log_event_type"] = "post_api_call" await callback_func( kwargs, # kwargs to func response_obj, start_time, end_time, ) print_verbose(f"Custom Logger - final response object: {response_obj}") except: # traceback.print_exc() print_verbose(f"Custom Logger Error - {traceback.format_exc()}") pass1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#### What this does ##### On success + failure, log events to Supabase
import dotenv, osimport requests
dotenv.load_dotenv() # Loading env variables using dotenvimport tracebackimport datetime, subprocess, sysimport litellm, uuidfrom litellm._logging import print_verbose
class DyanmoDBLogger: # Class variables or attributes
def __init__(self): # Instance variables import boto3
self.dynamodb = boto3.resource( "dynamodb", region_name=os.environ["AWS_REGION_NAME"] ) if litellm.dynamodb_table_name is None: raise ValueError( "LiteLLM Error, trying to use DynamoDB but not table name passed. Create a table and set `litellm.dynamodb_table_name=<your-table>`" ) self.table_name = litellm.dynamodb_table_name
async def _async_log_event( self, kwargs, response_obj, start_time, end_time, print_verbose ): self.log_event(kwargs, response_obj, start_time, end_time, print_verbose)
def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): try: print_verbose( f"DynamoDB Logging - Enters logging function for model {kwargs}" )
# construct payload to send to DynamoDB # follows the same params as langfuse.py litellm_params = kwargs.get("litellm_params", {}) metadata = ( litellm_params.get("metadata", {}) or {} ) # if litellm_params['metadata'] == None messages = kwargs.get("messages") optional_params = kwargs.get("optional_params", {}) call_type = kwargs.get("call_type", "litellm.completion") usage = response_obj["usage"] id = response_obj.get("id", str(uuid.uuid4()))
# Build the initial payload payload = { "id": id, "call_type": call_type, "startTime": start_time, "endTime": end_time, "model": kwargs.get("model", ""), "user": kwargs.get("user", ""), "modelParameters": optional_params, "messages": messages, "response": response_obj, "usage": usage, "metadata": metadata, }
# Ensure everything in the payload is converted to str for key, value in payload.items(): try: payload[key] = str(value) except: # non blocking if it can't cast to a str pass
print_verbose(f"\nDynamoDB Logger - Logging payload = {payload}")
# put data in dyanmo DB table = self.dynamodb.Table(self.table_name) # Assuming log_data is a dictionary with log information response = table.put_item(Item=payload)
print_verbose(f"Response from DynamoDB:{str(response)}")
print_verbose( f"DynamoDB Layer Logging - final response object: {response_obj}" ) return response except: traceback.print_exc() print_verbose(f"DynamoDB Layer Error - {traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114#### What this does ##### On success, logs events to Heliconeimport dotenv, osimport requests
dotenv.load_dotenv() # Loading env variables using dotenvimport traceback
class HeliconeLogger: # Class variables or attributes helicone_model_list = ["gpt", "claude"]
def __init__(self): # Instance variables self.provider_url = "https://api.openai.com/v1" self.key = os.getenv("HELICONE_API_KEY")
def claude_mapping(self, model, messages, response_obj): from anthropic import HUMAN_PROMPT, AI_PROMPT
prompt = f"{HUMAN_PROMPT}" for message in messages: if "role" in message: if message["role"] == "user": prompt += f"{HUMAN_PROMPT}{message['content']}" else: prompt += f"{AI_PROMPT}{message['content']}" else: prompt += f"{HUMAN_PROMPT}{message['content']}" prompt += f"{AI_PROMPT}" claude_provider_request = {"model": model, "prompt": prompt}
claude_response_obj = { "completion": response_obj["choices"][0]["message"]["content"], "model": model, "stop_reason": "stop_sequence", }
return claude_provider_request, claude_response_obj
def log_success( self, model, messages, response_obj, start_time, end_time, print_verbose ): # Method definition try: print_verbose( f"Helicone Logging - Enters logging function for model {model}" ) model = ( model if any( accepted_model in model for accepted_model in self.helicone_model_list ) else "gpt-3.5-turbo" ) provider_request = {"model": model, "messages": messages}
if "claude" in model: provider_request, response_obj = self.claude_mapping( model=model, messages=messages, response_obj=response_obj )
providerResponse = { "json": response_obj, "headers": {"openai-version": "2020-10-01"}, "status": 200, }
# Code to be executed url = "https://api.hconeai.com/oai/v1/log" headers = { "Authorization": f"Bearer {self.key}", "Content-Type": "application/json", } start_time_seconds = int(start_time.timestamp()) start_time_milliseconds = int( (start_time.timestamp() - start_time_seconds) * 1000 ) end_time_seconds = int(end_time.timestamp()) end_time_milliseconds = int( (end_time.timestamp() - end_time_seconds) * 1000 ) data = { "providerRequest": { "url": self.provider_url, "json": provider_request, "meta": {"Helicone-Auth": f"Bearer {self.key}"}, }, "providerResponse": providerResponse, "timing": { "startTime": { "seconds": start_time_seconds, "milliseconds": start_time_milliseconds, }, "endTime": { "seconds": end_time_seconds, "milliseconds": end_time_milliseconds, }, }, # {"seconds": .., "milliseconds": ..} } response = requests.post(url, headers=headers, json=data) if response.status_code == 200: print_verbose("Helicone Logging - Success!") else: print_verbose( f"Helicone Logging - Error Request was not successful. Status Code: {response.status_code}" ) print_verbose(f"Helicone Logging - Error {response.text}") except: # traceback.print_exc() print_verbose(f"Helicone Logging Error - {traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191#### What this does ##### On success, logs events to Langfuseimport dotenv, osimport requestsimport requestsfrom datetime import datetime
dotenv.load_dotenv() # Loading env variables using dotenvimport tracebackfrom packaging.version import Version
class LangFuseLogger: # Class variables or attributes def __init__(self): try: from langfuse import Langfuse except Exception as e: raise Exception( f"\033[91mLangfuse not installed, try running 'pip install langfuse' to fix this error: {e}\033[0m" ) # Instance variables self.secret_key = os.getenv("LANGFUSE_SECRET_KEY") self.public_key = os.getenv("LANGFUSE_PUBLIC_KEY") self.langfuse_host = os.getenv("LANGFUSE_HOST", "https://cloud.langfuse.com") self.langfuse_release = os.getenv("LANGFUSE_RELEASE") self.langfuse_debug = os.getenv("LANGFUSE_DEBUG") self.Langfuse = Langfuse( public_key=self.public_key, secret_key=self.secret_key, host=self.langfuse_host, release=self.langfuse_release, debug=self.langfuse_debug, )
def log_event( self, kwargs, response_obj, start_time, end_time, user_id, print_verbose ): # Method definition
try: print_verbose( f"Langfuse Logging - Enters logging function for model {kwargs}" ) litellm_params = kwargs.get("litellm_params", {}) metadata = ( litellm_params.get("metadata", {}) or {} ) # if litellm_params['metadata'] == None prompt = [kwargs.get("messages")] optional_params = kwargs.get("optional_params", {})
optional_params.pop("functions", None) optional_params.pop("tools", None)
# langfuse only accepts str, int, bool, float for logging for param, value in optional_params.items(): if not isinstance(value, (str, int, bool, float)): try: optional_params[param] = str(value) except: # if casting value to str fails don't block logging pass
# end of processing langfuse ######################## input = prompt output = response_obj["choices"][0]["message"].json() print_verbose( f"OUTPUT IN LANGFUSE: {output}; original: {response_obj['choices'][0]['message']}" ) self._log_langfuse_v2( user_id, metadata, output, start_time, end_time, kwargs, optional_params, input, response_obj, ) if self._is_langfuse_v2() else self._log_langfuse_v1( user_id, metadata, output, start_time, end_time, kwargs, optional_params, input, response_obj, )
self.Langfuse.flush() print_verbose( f"Langfuse Layer Logging - final response object: {response_obj}" ) except: traceback.print_exc() print_verbose(f"Langfuse Layer Error - {traceback.format_exc()}") pass
async def _async_log_event( self, kwargs, response_obj, start_time, end_time, user_id, print_verbose ): self.log_event( kwargs, response_obj, start_time, end_time, user_id, print_verbose )
def _is_langfuse_v2(self): import langfuse
return Version(langfuse.version.__version__) >= Version("2.0.0")
def _log_langfuse_v1( self, user_id, metadata, output, start_time, end_time, kwargs, optional_params, input, response_obj, ): from langfuse.model import CreateTrace, CreateGeneration
print( "Please upgrade langfuse to v2.0.0 or higher: https://github.com/langfuse/langfuse-python/releases/tag/v2.0.1" )
trace = self.Langfuse.trace( CreateTrace( name=metadata.get("generation_name", "litellm-completion"), input=input, output=output, userId=user_id, ) )
trace.generation( CreateGeneration( name=metadata.get("generation_name", "litellm-completion"), startTime=start_time, endTime=end_time, model=kwargs["model"], modelParameters=optional_params, input=input, output=output, usage={ "prompt_tokens": response_obj["usage"]["prompt_tokens"], "completion_tokens": response_obj["usage"]["completion_tokens"], }, metadata=metadata, ) )
def _log_langfuse_v2( self, user_id, metadata, output, start_time, end_time, kwargs, optional_params, input, response_obj, ): trace = self.Langfuse.trace( name=metadata.get("generation_name", "litellm-completion"), input=input, output=output, user_id=metadata.get("trace_user_id", user_id), id=metadata.get("trace_id", None), )
trace.generation( name=metadata.get("generation_name", "litellm-completion"), id=metadata.get("generation_id", None), startTime=start_time, endTime=end_time, model=kwargs["model"], modelParameters=optional_params, input=input, output=output, usage={ "prompt_tokens": response_obj["usage"]["prompt_tokens"], "completion_tokens": response_obj["usage"]["completion_tokens"], }, metadata=metadata, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475#### What this does ##### On success, logs events to Langsmithimport dotenv, osimport requestsimport requestsfrom datetime import datetime
dotenv.load_dotenv() # Loading env variables using dotenvimport traceback
class LangsmithLogger: # Class variables or attributes def __init__(self): self.langsmith_api_key = os.getenv("LANGSMITH_API_KEY")
def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): # Method definition # inspired by Langsmith http api here: https://github.com/langchain-ai/langsmith-cookbook/blob/main/tracing-examples/rest/rest.ipynb metadata = {} if "litellm_params" in kwargs: metadata = kwargs["litellm_params"].get("metadata", {}) # set project name and run_name for langsmith logging # users can pass project_name and run name to litellm.completion() # Example: litellm.completion(model, messages, metadata={"project_name": "my-litellm-project", "run_name": "my-langsmith-run"}) # if not set litellm will use default project_name = litellm-completion, run_name = LLMRun project_name = metadata.get("project_name", "litellm-completion") run_name = metadata.get("run_name", "LLMRun") print_verbose( f"Langsmith Logging - project_name: {project_name}, run_name {run_name}" ) try: print_verbose( f"Langsmith Logging - Enters logging function for model {kwargs}" ) import requests import datetime from datetime import timezone
try: start_time = kwargs["start_time"].astimezone(timezone.utc).isoformat() end_time = kwargs["end_time"].astimezone(timezone.utc).isoformat() except: start_time = datetime.datetime.utcnow().isoformat() end_time = datetime.datetime.utcnow().isoformat()
# filter out kwargs to not include any dicts, langsmith throws an erros when trying to log kwargs new_kwargs = {} for key in kwargs: value = kwargs[key] if key == "start_time" or key == "end_time": pass elif type(value) != dict: new_kwargs[key] = value
requests.post( "https://api.smith.langchain.com/runs", json={ "name": run_name, "run_type": "llm", # this should always be llm, since litellm always logs llm calls. Langsmith allow us to log "chain" "inputs": {**new_kwargs}, "outputs": response_obj.json(), "session_name": project_name, "start_time": start_time, "end_time": end_time, }, headers={"x-api-key": self.langsmith_api_key}, ) print_verbose( f"Langsmith Layer Logging - final response object: {response_obj}" ) except: # traceback.print_exc() print_verbose(f"Langsmith Layer Error - {traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262import requests, traceback, json, osimport types
class LiteDebugger: user_email = None dashboard_url = None
def __init__(self, email=None): self.api_url = "https://api.litellm.ai/debugger" self.validate_environment(email) pass
def validate_environment(self, email): try: self.user_email = ( email or os.getenv("LITELLM_TOKEN") or os.getenv("LITELLM_EMAIL") ) if ( self.user_email == None ): # if users are trying to use_client=True but token not set raise ValueError( "litellm.use_client = True but no token or email passed. Please set it in litellm.token" ) self.dashboard_url = "https://admin.litellm.ai/" + self.user_email try: print( f"\033[92mHere's your LiteLLM Dashboard 👉 \033[94m\033[4m{self.dashboard_url}\033[0m" ) except: print(f"Here's your LiteLLM Dashboard 👉 {self.dashboard_url}") if self.user_email == None: raise ValueError( "[Non-Blocking Error] LiteLLMDebugger: Missing LITELLM_TOKEN. Set it in your environment. Eg.: os.environ['LITELLM_TOKEN']= <your_email>" ) except Exception as e: raise ValueError( "[Non-Blocking Error] LiteLLMDebugger: Missing LITELLM_TOKEN. Set it in your environment. Eg.: os.environ['LITELLM_TOKEN']= <your_email>" )
def input_log_event( self, model, messages, end_user, litellm_call_id, call_type, print_verbose, litellm_params, optional_params, ): print_verbose( f"LiteDebugger: Pre-API Call Logging for call id {litellm_call_id}" ) try: print_verbose( f"LiteLLMDebugger: Logging - Enters input logging function for model {model}" )
def remove_key_value(dictionary, key): new_dict = dictionary.copy() # Create a copy of the original dictionary new_dict.pop(key) # Remove the specified key-value pair from the copy return new_dict
updated_litellm_params = remove_key_value(litellm_params, "logger_fn")
if call_type == "embedding": for ( message ) in ( messages ): # assuming the input is a list as required by the embedding function litellm_data_obj = { "model": model, "messages": [{"role": "user", "content": message}], "end_user": end_user, "status": "initiated", "litellm_call_id": litellm_call_id, "user_email": self.user_email, "litellm_params": updated_litellm_params, "optional_params": optional_params, } print_verbose( f"LiteLLMDebugger: Logging - logged data obj {litellm_data_obj}" ) response = requests.post( url=self.api_url, headers={"content-type": "application/json"}, data=json.dumps(litellm_data_obj), ) print_verbose(f"LiteDebugger: embedding api response - {response.text}") elif call_type == "completion": litellm_data_obj = { "model": model, "messages": messages if isinstance(messages, list) else [{"role": "user", "content": messages}], "end_user": end_user, "status": "initiated", "litellm_call_id": litellm_call_id, "user_email": self.user_email, "litellm_params": updated_litellm_params, "optional_params": optional_params, } print_verbose( f"LiteLLMDebugger: Logging - logged data obj {litellm_data_obj}" ) response = requests.post( url=self.api_url, headers={"content-type": "application/json"}, data=json.dumps(litellm_data_obj), ) print_verbose( f"LiteDebugger: completion api response - {response.text}" ) except: print_verbose( f"[Non-Blocking Error] LiteDebugger: Logging Error - {traceback.format_exc()}" ) pass
def post_call_log_event( self, original_response, litellm_call_id, print_verbose, call_type, stream ): print_verbose( f"LiteDebugger: Post-API Call Logging for call id {litellm_call_id}" ) try: if call_type == "embedding": litellm_data_obj = { "status": "received", "additional_details": { "original_response": str( original_response["data"][0]["embedding"][:5] ) }, # don't store the entire vector "litellm_call_id": litellm_call_id, "user_email": self.user_email, } elif call_type == "completion" and not stream: litellm_data_obj = { "status": "received", "additional_details": {"original_response": original_response}, "litellm_call_id": litellm_call_id, "user_email": self.user_email, } elif call_type == "completion" and stream: litellm_data_obj = { "status": "received", "additional_details": { "original_response": "Streamed response" if isinstance(original_response, types.GeneratorType) else original_response }, "litellm_call_id": litellm_call_id, "user_email": self.user_email, } print_verbose(f"litedebugger post-call data object - {litellm_data_obj}") response = requests.post( url=self.api_url, headers={"content-type": "application/json"}, data=json.dumps(litellm_data_obj), ) print_verbose(f"LiteDebugger: api response - {response.text}") except: print_verbose( f"[Non-Blocking Error] LiteDebugger: Logging Error - {traceback.format_exc()}" )
def log_event( self, end_user, response_obj, start_time, end_time, litellm_call_id, print_verbose, call_type, stream=False, ): print_verbose( f"LiteDebugger: Success/Failure Call Logging for call id {litellm_call_id}" ) try: print_verbose( f"LiteLLMDebugger: Success/Failure Logging - Enters handler logging function for function {call_type} and stream set to {stream} with response object {response_obj}" ) total_cost = 0 # [TODO] implement cost tracking response_time = (end_time - start_time).total_seconds() if call_type == "completion" and stream == False: litellm_data_obj = { "response_time": response_time, "total_cost": total_cost, "response": response_obj["choices"][0]["message"]["content"], "litellm_call_id": litellm_call_id, "status": "success", } print_verbose( f"LiteDebugger: Logging - final data object: {litellm_data_obj}" ) response = requests.post( url=self.api_url, headers={"content-type": "application/json"}, data=json.dumps(litellm_data_obj), ) elif call_type == "embedding": litellm_data_obj = { "response_time": response_time, "total_cost": total_cost, "response": str(response_obj["data"][0]["embedding"][:5]), "litellm_call_id": litellm_call_id, "status": "success", } response = requests.post( url=self.api_url, headers={"content-type": "application/json"}, data=json.dumps(litellm_data_obj), ) elif call_type == "completion" and stream == True: if len(response_obj["content"]) > 0: # don't log the empty strings litellm_data_obj = { "response_time": response_time, "total_cost": total_cost, "response": response_obj["content"], "litellm_call_id": litellm_call_id, "status": "success", } print_verbose( f"LiteDebugger: Logging - final data object: {litellm_data_obj}" ) response = requests.post( url=self.api_url, headers={"content-type": "application/json"}, data=json.dumps(litellm_data_obj), ) elif "error" in response_obj: if "Unable to map your input to a model." in response_obj["error"]: total_cost = 0 litellm_data_obj = { "response_time": response_time, "model": response_obj["model"], "total_cost": total_cost, "error": response_obj["error"], "end_user": end_user, "litellm_call_id": litellm_call_id, "status": "failure", "user_email": self.user_email, } print_verbose( f"LiteDebugger: Logging - final data object: {litellm_data_obj}" ) response = requests.post( url=self.api_url, headers={"content-type": "application/json"}, data=json.dumps(litellm_data_obj), ) print_verbose(f"LiteDebugger: api response - {response.text}") except: print_verbose( f"[Non-Blocking Error] LiteDebugger: Logging Error - {traceback.format_exc()}" ) pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127#### What this does ##### On success + failure, log events to aispend.ioimport datetimeimport tracebackimport dotenvimport osimport requests
dotenv.load_dotenv() # Loading env variables using dotenv
# convert to {completion: xx, tokens: xx}def parse_usage(usage): return { "completion": usage["completion_tokens"] if "completion_tokens" in usage else 0, "prompt": usage["prompt_tokens"] if "prompt_tokens" in usage else 0, }
def parse_messages(input): if input is None: return None
def clean_message(message): # if is strin, return as is if isinstance(message, str): return message
if "message" in message: return clean_message(message["message"]) text = message["content"] if text == None: text = message.get("function_call", None)
return { "role": message["role"], "text": text, }
if isinstance(input, list): if len(input) == 1: return clean_message(input[0]) else: return [clean_message(msg) for msg in input] else: return clean_message(input)
class LLMonitorLogger: # Class variables or attributes def __init__(self): # Instance variables self.api_url = os.getenv("LLMONITOR_API_URL") or "https://app.llmonitor.com" self.app_id = os.getenv("LLMONITOR_APP_ID")
def log_event( self, type, event, run_id, model, print_verbose, input=None, user_id=None, response_obj=None, start_time=datetime.datetime.now(), end_time=datetime.datetime.now(), error=None, ): # Method definition try: print_verbose(f"LLMonitor Logging - Logging request for model {model}")
if response_obj: usage = ( parse_usage(response_obj["usage"]) if "usage" in response_obj else None ) output = response_obj["choices"] if "choices" in response_obj else None else: usage = None output = None
if error: error_obj = {"stack": error}
else: error_obj = None
data = [ { "type": type, "name": model, "runId": run_id, "app": self.app_id, "event": "start", "timestamp": start_time.isoformat(), "userId": user_id, "input": parse_messages(input), }, { "type": type, "runId": run_id, "app": self.app_id, "event": event, "error": error_obj, "timestamp": end_time.isoformat(), "userId": user_id, "output": parse_messages(output), "tokensUsage": usage, }, ]
print_verbose(f"LLMonitor Logging - final data object: {data}")
response = requests.post( self.api_url + "/api/report", headers={"Content-Type": "application/json"}, json={"events": data}, )
print_verbose(f"LLMonitor Logging - response: {response}") except: # traceback.print_exc() print_verbose(f"LLMonitor Logging Error - {traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172#### What this does ##### On success, logs events to Promptlayerimport dotenv, osimport requestsimport requests
dotenv.load_dotenv() # Loading env variables using dotenvimport traceback
class PromptLayerLogger: # Class variables or attributes def __init__(self): # Instance variables self.key = os.getenv("PROMPTLAYER_API_KEY")
def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): # Method definition try: new_kwargs = {} new_kwargs["model"] = kwargs["model"] new_kwargs["messages"] = kwargs["messages"]
# add kwargs["optional_params"] to new_kwargs for optional_param in kwargs["optional_params"]: new_kwargs[optional_param] = kwargs["optional_params"][optional_param]
print_verbose( f"Prompt Layer Logging - Enters logging function for model kwargs: {new_kwargs}\n, response: {response_obj}" )
request_response = requests.post( "https://api.promptlayer.com/rest/track-request", json={ "function_name": "openai.ChatCompletion.create", "kwargs": new_kwargs, "tags": ["hello", "world"], "request_response": dict(response_obj), "request_start_time": int(start_time.timestamp()), "request_end_time": int(end_time.timestamp()), "api_key": self.key, # Optional params for PromptLayer # "prompt_id": "<PROMPT ID>", # "prompt_input_variables": "<Dictionary of variables for prompt>", # "prompt_version":1, }, ) print_verbose( f"Prompt Layer Logging: success - final response object: {request_response.text}" ) response_json = request_response.json() if "success" not in request_response.json(): raise Exception("Promptlayer did not successfully log the response!")
if "request_id" in response_json: print(kwargs["litellm_params"]["metadata"]) if kwargs["litellm_params"]["metadata"] is not None: response = requests.post( "https://api.promptlayer.com/rest/track-metadata", json={ "request_id": response_json["request_id"], "api_key": self.key, "metadata": kwargs["litellm_params"]["metadata"], }, ) print_verbose( f"Prompt Layer Logging: success - metadata post response object: {response.text}" )
except: print_verbose(f"error: Prompt Layer Error - {traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150#### What this does ##### On success + failure, log events to Supabase
import dotenv, osimport requests
dotenv.load_dotenv() # Loading env variables using dotenvimport tracebackimport datetime, subprocess, sysimport litellm, uuidfrom litellm._logging import print_verbose
class S3Logger: # Class variables or attributes def __init__( self, s3_bucket_name=None, s3_region_name=None, s3_api_version=None, s3_use_ssl=True, s3_verify=None, s3_endpoint_url=None, s3_aws_access_key_id=None, s3_aws_secret_access_key=None, s3_aws_session_token=None, s3_config=None, **kwargs, ): import boto3
try: print_verbose("in init s3 logger")
if litellm.s3_callback_params is not None: # read in .env variables - example os.environ/AWS_BUCKET_NAME for key, value in litellm.s3_callback_params.items(): if type(value) is str and value.startswith("os.environ/"): litellm.s3_callback_params[key] = litellm.get_secret(value) # now set s3 params from litellm.s3_logger_params s3_bucket_name = litellm.s3_callback_params.get("s3_bucket_name") s3_region_name = litellm.s3_callback_params.get("s3_region_name") s3_api_version = litellm.s3_callback_params.get("s3_api_version") s3_use_ssl = litellm.s3_callback_params.get("s3_use_ssl") s3_verify = litellm.s3_callback_params.get("s3_verify") s3_endpoint_url = litellm.s3_callback_params.get("s3_endpoint_url") s3_aws_access_key_id = litellm.s3_callback_params.get( "s3_aws_access_key_id" ) s3_aws_secret_access_key = litellm.s3_callback_params.get( "s3_aws_secret_access_key" ) s3_aws_session_token = litellm.s3_callback_params.get( "s3_aws_session_token" ) s3_config = litellm.s3_callback_params.get("s3_config") # done reading litellm.s3_callback_params
self.bucket_name = s3_bucket_name # Create an S3 client with custom endpoint URL self.s3_client = boto3.client( "s3", region_name=s3_region_name, endpoint_url=s3_endpoint_url, api_version=s3_api_version, use_ssl=s3_use_ssl, verify=s3_verify, aws_access_key_id=s3_aws_access_key_id, aws_secret_access_key=s3_aws_secret_access_key, aws_session_token=s3_aws_session_token, config=s3_config, **kwargs, ) except Exception as e: print_verbose(f"Got exception on init s3 client {str(e)}") raise e
async def _async_log_event( self, kwargs, response_obj, start_time, end_time, print_verbose ): self.log_event(kwargs, response_obj, start_time, end_time, print_verbose)
def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): try: print_verbose(f"s3 Logging - Enters logging function for model {kwargs}")
# construct payload to send to s3 # follows the same params as langfuse.py litellm_params = kwargs.get("litellm_params", {}) metadata = ( litellm_params.get("metadata", {}) or {} ) # if litellm_params['metadata'] == None messages = kwargs.get("messages") optional_params = kwargs.get("optional_params", {}) call_type = kwargs.get("call_type", "litellm.completion") cache_hit = kwargs.get("cache_hit", False) usage = response_obj["usage"] id = response_obj.get("id", str(uuid.uuid4()))
# Build the initial payload payload = { "id": id, "call_type": call_type, "cache_hit": cache_hit, "startTime": start_time, "endTime": end_time, "model": kwargs.get("model", ""), "user": kwargs.get("user", ""), "modelParameters": optional_params, "messages": messages, "response": response_obj, "usage": usage, "metadata": metadata, }
# Ensure everything in the payload is converted to str for key, value in payload.items(): try: payload[key] = str(value) except: # non blocking if it can't cast to a str pass
s3_object_key = ( payload["id"] + "-time=" + str(start_time) ) # we need the s3 key to include the time, so we log cache hits too
import json
payload = json.dumps(payload)
print_verbose(f"\ns3 Logger - Logging payload = {payload}")
response = self.s3_client.put_object( Bucket=self.bucket_name, Key=s3_object_key, Body=payload, ContentType="application/json", ContentLanguage="en", ContentDisposition=f'inline; filename="{key}.json"', )
print_verbose(f"Response from s3:{str(response)}")
print_verbose(f"s3 Layer Logging - final response object: {response_obj}") return response except Exception as e: traceback.print_exc() print_verbose(f"s3 Layer Error - {str(e)}\n{traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117#### What this does ##### On success + failure, log events to Supabase
import dotenv, osimport requests
dotenv.load_dotenv() # Loading env variables using dotenvimport tracebackimport datetime, subprocess, sysimport litellm
class Supabase: # Class variables or attributes supabase_table_name = "request_logs"
def __init__(self): # Instance variables self.supabase_url = os.getenv("SUPABASE_URL") self.supabase_key = os.getenv("SUPABASE_KEY") try: import supabase except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", "supabase"]) import supabase self.supabase_client = supabase.create_client( self.supabase_url, self.supabase_key )
def input_log_event( self, model, messages, end_user, litellm_call_id, print_verbose ): try: print_verbose( f"Supabase Logging - Enters input logging function for model {model}" ) supabase_data_obj = { "model": model, "messages": messages, "end_user": end_user, "status": "initiated", "litellm_call_id": litellm_call_id, } data, count = ( self.supabase_client.table(self.supabase_table_name) .insert(supabase_data_obj) .execute() ) print_verbose(f"data: {data}") except: print_verbose(f"Supabase Logging Error - {traceback.format_exc()}") pass
def log_event( self, model, messages, end_user, response_obj, start_time, end_time, litellm_call_id, print_verbose, ): try: print_verbose( f"Supabase Logging - Enters logging function for model {model}, response_obj: {response_obj}" )
total_cost = litellm.completion_cost(completion_response=response_obj)
response_time = (end_time - start_time).total_seconds() if "choices" in response_obj: supabase_data_obj = { "response_time": response_time, "model": response_obj["model"], "total_cost": total_cost, "messages": messages, "response": response_obj["choices"][0]["message"]["content"], "end_user": end_user, "litellm_call_id": litellm_call_id, "status": "success", } print_verbose( f"Supabase Logging - final data object: {supabase_data_obj}" ) data, count = ( self.supabase_client.table(self.supabase_table_name) .upsert(supabase_data_obj, on_conflict="litellm_call_id") .execute() ) elif "error" in response_obj: if "Unable to map your input to a model." in response_obj["error"]: total_cost = 0 supabase_data_obj = { "response_time": response_time, "model": response_obj["model"], "total_cost": total_cost, "messages": messages, "error": response_obj["error"], "end_user": end_user, "litellm_call_id": litellm_call_id, "status": "failure", } print_verbose( f"Supabase Logging - final data object: {supabase_data_obj}" ) data, count = ( self.supabase_client.table(self.supabase_table_name) .upsert(supabase_data_obj, on_conflict="litellm_call_id") .execute() )
except: # traceback.print_exc() print_verbose(f"Supabase Logging Error - {traceback.format_exc()}") pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114class TraceloopLogger: def __init__(self): from traceloop.sdk.tracing.tracing import TracerWrapper from traceloop.sdk import Traceloop
Traceloop.init(app_name="Litellm-Server", disable_batch=True) self.tracer_wrapper = TracerWrapper()
def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): from opentelemetry.trace import SpanKind from opentelemetry.semconv.ai import SpanAttributes
try: tracer = self.tracer_wrapper.get_tracer()
model = kwargs.get("model")
# LiteLLM uses the standard OpenAI library, so it's already handled by Traceloop SDK if kwargs.get("litellm_params").get("custom_llm_provider") == "openai": return
optional_params = kwargs.get("optional_params", {}) with tracer.start_as_current_span( "litellm.completion", kind=SpanKind.CLIENT, ) as span: if span.is_recording(): span.set_attribute( SpanAttributes.LLM_REQUEST_MODEL, kwargs.get("model") ) if "stop" in optional_params: span.set_attribute( SpanAttributes.LLM_CHAT_STOP_SEQUENCES, optional_params.get("stop"), ) if "frequency_penalty" in optional_params: span.set_attribute( SpanAttributes.LLM_FREQUENCY_PENALTY, optional_params.get("frequency_penalty"), ) if "presence_penalty" in optional_params: span.set_attribute( SpanAttributes.LLM_PRESENCE_PENALTY, optional_params.get("presence_penalty"), ) if "top_p" in optional_params: span.set_attribute( SpanAttributes.LLM_TOP_P, optional_params.get("top_p") ) if "tools" in optional_params or "functions" in optional_params: span.set_attribute( SpanAttributes.LLM_REQUEST_FUNCTIONS, optional_params.get( "tools", optional_params.get("functions") ), ) if "user" in optional_params: span.set_attribute( SpanAttributes.LLM_USER, optional_params.get("user") ) if "max_tokens" in optional_params: span.set_attribute( SpanAttributes.LLM_REQUEST_MAX_TOKENS, kwargs.get("max_tokens"), ) if "temperature" in optional_params: span.set_attribute( SpanAttributes.LLM_TEMPERATURE, kwargs.get("temperature") )
for idx, prompt in enumerate(kwargs.get("messages")): span.set_attribute( f"{SpanAttributes.LLM_PROMPTS}.{idx}.role", prompt.get("role"), ) span.set_attribute( f"{SpanAttributes.LLM_PROMPTS}.{idx}.content", prompt.get("content"), )
span.set_attribute( SpanAttributes.LLM_RESPONSE_MODEL, response_obj.get("model") ) usage = response_obj.get("usage") if usage: span.set_attribute( SpanAttributes.LLM_USAGE_TOTAL_TOKENS, usage.get("total_tokens"), ) span.set_attribute( SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, usage.get("completion_tokens"), ) span.set_attribute( SpanAttributes.LLM_USAGE_PROMPT_TOKENS, usage.get("prompt_tokens"), )
for idx, choice in enumerate(response_obj.get("choices")): span.set_attribute( f"{SpanAttributes.LLM_COMPLETIONS}.{idx}.finish_reason", choice.get("finish_reason"), ) span.set_attribute( f"{SpanAttributes.LLM_COMPLETIONS}.{idx}.role", choice.get("message").get("role"), ) span.set_attribute( f"{SpanAttributes.LLM_COMPLETIONS}.{idx}.content", choice.get("message").get("content"), )
except Exception as e: print_verbose(f"Traceloop Layer Error - {e}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223imported_openAIResponse = Truetry: import io import logging import sys from typing import Any, Dict, List, Optional, TypeVar
from wandb.sdk.data_types import trace_tree
if sys.version_info >= (3, 8): from typing import Literal, Protocol else: from typing_extensions import Literal, Protocol
logger = logging.getLogger(__name__)
K = TypeVar("K", bound=str) V = TypeVar("V")
class OpenAIResponse(Protocol[K, V]): # type: ignore # contains a (known) object attribute object: Literal["chat.completion", "edit", "text_completion"]
def __getitem__(self, key: K) -> V: ... # pragma: no cover
def get(self, key: K, default: Optional[V] = None) -> Optional[V]: ... # pragma: no cover
class OpenAIRequestResponseResolver: def __call__( self, request: Dict[str, Any], response: OpenAIResponse, time_elapsed: float, ) -> Optional[trace_tree.WBTraceTree]: try: if response["object"] == "edit": return self._resolve_edit(request, response, time_elapsed) elif response["object"] == "text_completion": return self._resolve_completion(request, response, time_elapsed) elif response["object"] == "chat.completion": return self._resolve_chat_completion( request, response, time_elapsed ) else: logger.info(f"Unknown OpenAI response object: {response['object']}") except Exception as e: logger.warning(f"Failed to resolve request/response: {e}") return None
@staticmethod def results_to_trace_tree( request: Dict[str, Any], response: OpenAIResponse, results: List[trace_tree.Result], time_elapsed: float, ) -> trace_tree.WBTraceTree: """Converts the request, response, and results into a trace tree.
params: request: The request dictionary response: The response object results: A list of results object time_elapsed: The time elapsed in seconds returns: A wandb trace tree object. """ start_time_ms = int(round(response["created"] * 1000)) end_time_ms = start_time_ms + int(round(time_elapsed * 1000)) span = trace_tree.Span( name=f"{response.get('model', 'openai')}_{response['object']}_{response.get('created')}", attributes=dict(response), # type: ignore start_time_ms=start_time_ms, end_time_ms=end_time_ms, span_kind=trace_tree.SpanKind.LLM, results=results, ) model_obj = {"request": request, "response": response, "_kind": "openai"} return trace_tree.WBTraceTree(root_span=span, model_dict=model_obj)
def _resolve_edit( self, request: Dict[str, Any], response: OpenAIResponse, time_elapsed: float, ) -> trace_tree.WBTraceTree: """Resolves the request and response objects for `openai.Edit`.""" request_str = ( f"\n\n**Instruction**: {request['instruction']}\n\n" f"**Input**: {request['input']}\n" ) choices = [ f"\n\n**Edited**: {choice['text']}\n" for choice in response["choices"] ]
return self._request_response_result_to_trace( request=request, response=response, request_str=request_str, choices=choices, time_elapsed=time_elapsed, )
def _resolve_completion( self, request: Dict[str, Any], response: OpenAIResponse, time_elapsed: float, ) -> trace_tree.WBTraceTree: """Resolves the request and response objects for `openai.Completion`.""" request_str = f"\n\n**Prompt**: {request['prompt']}\n" choices = [ f"\n\n**Completion**: {choice['text']}\n" for choice in response["choices"] ]
return self._request_response_result_to_trace( request=request, response=response, request_str=request_str, choices=choices, time_elapsed=time_elapsed, )
def _resolve_chat_completion( self, request: Dict[str, Any], response: OpenAIResponse, time_elapsed: float, ) -> trace_tree.WBTraceTree: """Resolves the request and response objects for `openai.Completion`.""" prompt = io.StringIO() for message in request["messages"]: prompt.write(f"\n\n**{message['role']}**: {message['content']}\n") request_str = prompt.getvalue()
choices = [ f"\n\n**{choice['message']['role']}**: {choice['message']['content']}\n" for choice in response["choices"] ]
return self._request_response_result_to_trace( request=request, response=response, request_str=request_str, choices=choices, time_elapsed=time_elapsed, )
def _request_response_result_to_trace( self, request: Dict[str, Any], response: OpenAIResponse, request_str: str, choices: List[str], time_elapsed: float, ) -> trace_tree.WBTraceTree: """Resolves the request and response objects for `openai.Completion`.""" results = [ trace_tree.Result( inputs={"request": request_str}, outputs={"response": choice}, ) for choice in choices ] trace = self.results_to_trace_tree(request, response, results, time_elapsed) return trace
except: imported_openAIResponse = False
#### What this does ##### On success, logs events to Langfuseimport dotenv, osimport requestsimport requestsfrom datetime import datetime
dotenv.load_dotenv() # Loading env variables using dotenvimport traceback
class WeightsBiasesLogger: # Class variables or attributes def __init__(self): try: import wandb except: raise Exception( "\033[91m wandb not installed, try running 'pip install wandb' to fix this error\033[0m" ) if imported_openAIResponse == False: raise Exception( "\033[91m wandb not installed, try running 'pip install wandb' to fix this error\033[0m" ) self.resolver = OpenAIRequestResponseResolver()
def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): # Method definition import wandb
try: print_verbose(f"W&B Logging - Enters logging function for model {kwargs}") run = wandb.init() print_verbose(response_obj)
trace = self.resolver( kwargs, response_obj, (end_time - start_time).total_seconds() )
if trace is not None: run.log({"trace": trace})
run.finish() print_verbose( f"W&B Logging Logging - final response object: {response_obj}" ) except: # traceback.print_exc() print_verbose(f"W&B Logging Layer Error - {traceback.format_exc()}") pass1from . import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212import os, types, tracebackimport jsonfrom enum import Enumimport requestsimport time, httpxfrom typing import Callable, Optionalfrom litellm.utils import ModelResponse, Choices, Messageimport litellm
class AI21Error(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request( method="POST", url="https://api.ai21.com/studio/v1/" ) self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class AI21Config: """ Reference: https://docs.ai21.com/reference/j2-complete-ref
The class `AI21Config` provides configuration for the AI21's API interface. Below are the parameters:
- `numResults` (int32): Number of completions to sample and return. Optional, default is 1. If the temperature is greater than 0 (non-greedy decoding), a value greater than 1 can be meaningful.
- `maxTokens` (int32): The maximum number of tokens to generate per result. Optional, default is 16. If no `stopSequences` are given, generation stops after producing `maxTokens`.
- `minTokens` (int32): The minimum number of tokens to generate per result. Optional, default is 0. If `stopSequences` are given, they are ignored until `minTokens` are generated.
- `temperature` (float): Modifies the distribution from which tokens are sampled. Optional, default is 0.7. A value of 0 essentially disables sampling and results in greedy decoding.
- `topP` (float): Used for sampling tokens from the corresponding top percentile of probability mass. Optional, default is 1. For instance, a value of 0.9 considers only tokens comprising the top 90% probability mass.
- `stopSequences` (array of strings): Stops decoding if any of the input strings is generated. Optional.
- `topKReturn` (int32): Range between 0 to 10, including both. Optional, default is 0. Specifies the top-K alternative tokens to return. A non-zero value includes the string representations and log-probabilities for each of the top-K alternatives at each position.
- `frequencyPenalty` (object): Placeholder for frequency penalty object.
- `presencePenalty` (object): Placeholder for presence penalty object.
- `countPenalty` (object): Placeholder for count penalty object. """
numResults: Optional[int] = None maxTokens: Optional[int] = None minTokens: Optional[int] = None temperature: Optional[float] = None topP: Optional[float] = None stopSequences: Optional[list] = None topKReturn: Optional[int] = None frequencePenalty: Optional[dict] = None presencePenalty: Optional[dict] = None countPenalty: Optional[dict] = None
def __init__( self, numResults: Optional[int] = None, maxTokens: Optional[int] = None, minTokens: Optional[int] = None, temperature: Optional[float] = None, topP: Optional[float] = None, stopSequences: Optional[list] = None, topKReturn: Optional[int] = None, frequencePenalty: Optional[dict] = None, presencePenalty: Optional[dict] = None, countPenalty: Optional[dict] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def validate_environment(api_key): if api_key is None: raise ValueError( "Missing AI21 API Key - A call is being made to ai21 but no key is set either in the environment variables or via params" ) headers = { "accept": "application/json", "content-type": "application/json", "Authorization": "Bearer " + api_key, } return headers
def completion( model: str, messages: list, api_base: str, model_response: ModelResponse, print_verbose: Callable, encoding, api_key, logging_obj, optional_params=None, litellm_params=None, logger_fn=None,): headers = validate_environment(api_key) model = model prompt = "" for message in messages: if "role" in message: if message["role"] == "user": prompt += f"{message['content']}" else: prompt += f"{message['content']}" else: prompt += f"{message['content']}"
## Load Config config = litellm.AI21Config.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > ai21_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
data = { "prompt": prompt, # "instruction": prompt, # some baseten models require the prompt to be passed in via the 'instruction' kwarg **optional_params, }
## LOGGING logging_obj.pre_call( input=prompt, api_key=api_key, additional_args={"complete_input_dict": data}, ) ## COMPLETION CALL response = requests.post( api_base + model + "/complete", headers=headers, data=json.dumps(data) ) if response.status_code != 200: raise AI21Error(status_code=response.status_code, message=response.text) if "stream" in optional_params and optional_params["stream"] == True: return response.iter_lines() else: ## LOGGING logging_obj.post_call( input=prompt, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data}, ) ## RESPONSE OBJECT completion_response = response.json() try: choices_list = [] for idx, item in enumerate(completion_response["completions"]): if len(item["data"]["text"]) > 0: message_obj = Message(content=item["data"]["text"]) else: message_obj = Message(content=None) choice_obj = Choices( finish_reason=item["finishReason"]["reason"], index=idx + 1, message=message_obj, ) choices_list.append(choice_obj) model_response["choices"] = choices_list except Exception as e: raise AI21Error( message=traceback.format_exc(), status_code=response.status_code )
## CALCULATING USAGE - baseten charges on time, not tokens - have some mapping of cost here. prompt_tokens = len(encoding.encode(prompt)) completion_tokens = len( encoding.encode(model_response["choices"][0]["message"].get("content")) )
model_response["created"] = int(time.time()) model_response["model"] = model model_response["usage"] = { "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": prompt_tokens + completion_tokens, } return model_response
def embedding(): # logic for parsing in - calling - parsing out model embedding calls pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304import os, typesimport jsonfrom enum import Enumimport requestsimport timefrom typing import Callable, Optionalimport litellmfrom litellm.utils import ModelResponse, Choices, Message, Usageimport httpx
class AlephAlphaError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request( method="POST", url="https://api.aleph-alpha.com/complete" ) self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class AlephAlphaConfig: """ Reference: https://docs.aleph-alpha.com/api/complete/
The `AlephAlphaConfig` class represents the configuration for the Aleph Alpha API. Here are the properties:
- `maximum_tokens` (integer, required): The maximum number of tokens to be generated by the completion. The sum of input tokens and maximum tokens may not exceed 2048.
- `minimum_tokens` (integer, optional; default value: 0): Generate at least this number of tokens before an end-of-text token is generated.
- `echo` (boolean, optional; default value: false): Whether to echo the prompt in the completion.
- `temperature` (number, nullable; default value: 0): Adjusts how creatively the model generates outputs. Use combinations of temperature, top_k, and top_p sensibly.
- `top_k` (integer, nullable; default value: 0): Introduces randomness into token generation by considering the top k most likely options.
- `top_p` (number, nullable; default value: 0): Adds randomness by considering the smallest set of tokens whose cumulative probability exceeds top_p.
- `presence_penalty`, `frequency_penalty`, `sequence_penalty` (number, nullable; default value: 0): Various penalties that can reduce repetition.
- `sequence_penalty_min_length` (integer; default value: 2): Minimum number of tokens to be considered as a sequence.
- `repetition_penalties_include_prompt`, `repetition_penalties_include_completion`, `use_multiplicative_presence_penalty`,`use_multiplicative_frequency_penalty`,`use_multiplicative_sequence_penalty` (boolean, nullable; default value: false): Various settings that adjust how the repetition penalties are applied.
- `penalty_bias` (string, nullable): Text used in addition to the penalized tokens for repetition penalties.
- `penalty_exceptions` (string[], nullable): Strings that may be generated without penalty.
- `penalty_exceptions_include_stop_sequences` (boolean, nullable; default value: true): Include all stop_sequences in penalty_exceptions.
- `best_of` (integer, nullable; default value: 1): The number of completions will be generated on the server side.
- `n` (integer, nullable; default value: 1): The number of completions to return.
- `logit_bias` (object, nullable): Adjust the logit scores before sampling.
- `log_probs` (integer, nullable): Number of top log probabilities for each token generated.
- `stop_sequences` (string[], nullable): List of strings that will stop generation if they're generated.
- `tokens` (boolean, nullable; default value: false): Flag indicating whether individual tokens of the completion should be returned or not.
- `raw_completion` (boolean; default value: false): if True, the raw completion of the model will be returned.
- `disable_optimizations` (boolean, nullable; default value: false): Disables any applied optimizations to both your prompt and completion.
- `completion_bias_inclusion`, `completion_bias_exclusion` (string[], default value: []): Set of strings to bias the generation of tokens.
- `completion_bias_inclusion_first_token_only`, `completion_bias_exclusion_first_token_only` (boolean; default value: false): Consider only the first token for the completion_bias_inclusion/exclusion.
- `contextual_control_threshold` (number, nullable): Control over how similar tokens are controlled.
- `control_log_additive` (boolean; default value: true): Method of applying control to attention scores. """
maximum_tokens: Optional[ int ] = litellm.max_tokens # aleph alpha requires max tokens minimum_tokens: Optional[int] = None echo: Optional[bool] = None temperature: Optional[int] = None top_k: Optional[int] = None top_p: Optional[int] = None presence_penalty: Optional[int] = None frequency_penalty: Optional[int] = None sequence_penalty: Optional[int] = None sequence_penalty_min_length: Optional[int] = None repetition_penalties_include_prompt: Optional[bool] = None repetition_penalties_include_completion: Optional[bool] = None use_multiplicative_presence_penalty: Optional[bool] = None use_multiplicative_frequency_penalty: Optional[bool] = None use_multiplicative_sequence_penalty: Optional[bool] = None penalty_bias: Optional[str] = None penalty_exceptions_include_stop_sequences: Optional[bool] = None best_of: Optional[int] = None n: Optional[int] = None logit_bias: Optional[dict] = None log_probs: Optional[int] = None stop_sequences: Optional[list] = None tokens: Optional[bool] = None raw_completion: Optional[bool] = None disable_optimizations: Optional[bool] = None completion_bias_inclusion: Optional[list] = None completion_bias_exclusion: Optional[list] = None completion_bias_inclusion_first_token_only: Optional[bool] = None completion_bias_exclusion_first_token_only: Optional[bool] = None contextual_control_threshold: Optional[int] = None control_log_additive: Optional[bool] = None
def __init__( self, maximum_tokens: Optional[int] = None, minimum_tokens: Optional[int] = None, echo: Optional[bool] = None, temperature: Optional[int] = None, top_k: Optional[int] = None, top_p: Optional[int] = None, presence_penalty: Optional[int] = None, frequency_penalty: Optional[int] = None, sequence_penalty: Optional[int] = None, sequence_penalty_min_length: Optional[int] = None, repetition_penalties_include_prompt: Optional[bool] = None, repetition_penalties_include_completion: Optional[bool] = None, use_multiplicative_presence_penalty: Optional[bool] = None, use_multiplicative_frequency_penalty: Optional[bool] = None, use_multiplicative_sequence_penalty: Optional[bool] = None, penalty_bias: Optional[str] = None, penalty_exceptions_include_stop_sequences: Optional[bool] = None, best_of: Optional[int] = None, n: Optional[int] = None, logit_bias: Optional[dict] = None, log_probs: Optional[int] = None, stop_sequences: Optional[list] = None, tokens: Optional[bool] = None, raw_completion: Optional[bool] = None, disable_optimizations: Optional[bool] = None, completion_bias_inclusion: Optional[list] = None, completion_bias_exclusion: Optional[list] = None, completion_bias_inclusion_first_token_only: Optional[bool] = None, completion_bias_exclusion_first_token_only: Optional[bool] = None, contextual_control_threshold: Optional[int] = None, control_log_additive: Optional[bool] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def validate_environment(api_key): headers = { "accept": "application/json", "content-type": "application/json", } if api_key: headers["Authorization"] = f"Bearer {api_key}" return headers
def completion( model: str, messages: list, api_base: str, model_response: ModelResponse, print_verbose: Callable, encoding, api_key, logging_obj, optional_params=None, litellm_params=None, logger_fn=None, default_max_tokens_to_sample=None,): headers = validate_environment(api_key)
## Load Config config = litellm.AlephAlphaConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > aleph_alpha_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
completion_url = api_base model = model prompt = "" if "control" in model: # follow the ###Instruction / ###Response format for idx, message in enumerate(messages): if "role" in message: if ( idx == 0 ): # set first message as instruction (required), let later user messages be input prompt += f"###Instruction: {message['content']}" else: if message["role"] == "system": prompt += f"###Instruction: {message['content']}" elif message["role"] == "user": prompt += f"###Input: {message['content']}" else: prompt += f"###Response: {message['content']}" else: prompt += f"{message['content']}" else: prompt = " ".join(message["content"] for message in messages) data = { "model": model, "prompt": prompt, **optional_params, }
## LOGGING logging_obj.pre_call( input=prompt, api_key=api_key, additional_args={"complete_input_dict": data}, ) ## COMPLETION CALL response = requests.post( completion_url, headers=headers, data=json.dumps(data), stream=optional_params["stream"] if "stream" in optional_params else False, ) if "stream" in optional_params and optional_params["stream"] == True: return response.iter_lines() else: ## LOGGING logging_obj.post_call( input=prompt, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data}, ) print_verbose(f"raw model_response: {response.text}") ## RESPONSE OBJECT completion_response = response.json() if "error" in completion_response: raise AlephAlphaError( message=completion_response["error"], status_code=response.status_code, ) else: try: choices_list = [] for idx, item in enumerate(completion_response["completions"]): if len(item["completion"]) > 0: message_obj = Message(content=item["completion"]) else: message_obj = Message(content=None) choice_obj = Choices( finish_reason=item["finish_reason"], index=idx + 1, message=message_obj, ) choices_list.append(choice_obj) model_response["choices"] = choices_list except: raise AlephAlphaError( message=json.dumps(completion_response), status_code=response.status_code, )
## CALCULATING USAGE - baseten charges on time, not tokens - have some mapping of cost here. prompt_tokens = len(encoding.encode(prompt)) completion_tokens = len( encoding.encode(model_response["choices"][0]["message"]["content"]) )
model_response["created"] = int(time.time()) model_response["model"] = model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response
def embedding(): # logic for parsing in - calling - parsing out model embedding calls pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215import os, typesimport jsonfrom enum import Enumimport requestsimport timefrom typing import Callable, Optionalfrom litellm.utils import ModelResponse, Usageimport litellmfrom .prompt_templates.factory import prompt_factory, custom_promptimport httpx
class AnthropicConstants(Enum): HUMAN_PROMPT = "\n\nHuman: " AI_PROMPT = "\n\nAssistant: "
class AnthropicError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request( method="POST", url="https://api.anthropic.com/v1/complete" ) self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class AnthropicConfig: """ Reference: https://docs.anthropic.com/claude/reference/complete_post
to pass metadata to anthropic, it's {"user_id": "any-relevant-information"} """
max_tokens_to_sample: Optional[ int ] = litellm.max_tokens # anthropic requires a default stop_sequences: Optional[list] = None temperature: Optional[int] = None top_p: Optional[int] = None top_k: Optional[int] = None metadata: Optional[dict] = None
def __init__( self, max_tokens_to_sample: Optional[int] = 256, # anthropic requires a default stop_sequences: Optional[list] = None, temperature: Optional[int] = None, top_p: Optional[int] = None, top_k: Optional[int] = None, metadata: Optional[dict] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
# makes headers for API calldef validate_environment(api_key): if api_key is None: raise ValueError( "Missing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via params" ) headers = { "accept": "application/json", "anthropic-version": "2023-06-01", "content-type": "application/json", "x-api-key": api_key, } return headers
def completion( model: str, messages: list, api_base: str, custom_prompt_dict: dict, model_response: ModelResponse, print_verbose: Callable, encoding, api_key, logging_obj, optional_params=None, litellm_params=None, logger_fn=None,): headers = validate_environment(api_key) if model in custom_prompt_dict: # check if the model has a registered custom prompt model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details["roles"], initial_prompt_value=model_prompt_details["initial_prompt_value"], final_prompt_value=model_prompt_details["final_prompt_value"], messages=messages, ) else: prompt = prompt_factory( model=model, messages=messages, custom_llm_provider="anthropic" )
## Load Config config = litellm.AnthropicConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > anthropic_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
data = { "model": model, "prompt": prompt, **optional_params, }
## LOGGING logging_obj.pre_call( input=prompt, api_key=api_key, additional_args={"complete_input_dict": data, "api_base": api_base}, )
## COMPLETION CALL if "stream" in optional_params and optional_params["stream"] == True: response = requests.post( api_base, headers=headers, data=json.dumps(data), stream=optional_params["stream"], )
if response.status_code != 200: raise AnthropicError( status_code=response.status_code, message=response.text )
return response.iter_lines() else: response = requests.post(api_base, headers=headers, data=json.dumps(data)) if response.status_code != 200: raise AnthropicError( status_code=response.status_code, message=response.text )
## LOGGING logging_obj.post_call( input=prompt, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data}, ) print_verbose(f"raw model_response: {response.text}") ## RESPONSE OBJECT try: completion_response = response.json() except: raise AnthropicError( message=response.text, status_code=response.status_code ) if "error" in completion_response: raise AnthropicError( message=str(completion_response["error"]), status_code=response.status_code, ) else: if len(completion_response["completion"]) > 0: model_response["choices"][0]["message"][ "content" ] = completion_response["completion"] model_response.choices[0].finish_reason = completion_response["stop_reason"]
## CALCULATING USAGE prompt_tokens = len( encoding.encode(prompt) ) ##[TODO] use the anthropic tokenizer here completion_tokens = len( encoding.encode(model_response["choices"][0]["message"].get("content", "")) ) ##[TODO] use the anthropic tokenizer here
model_response["created"] = int(time.time()) model_response["model"] = model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response
def embedding(): # logic for parsing in - calling - parsing out model embedding calls pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799from typing import Optional, Union, Anyimport types, requestsfrom .base import BaseLLMfrom litellm.utils import ( ModelResponse, Choices, Message, CustomStreamWrapper, convert_to_model_response_object,)from typing import Callable, Optionalfrom litellm import OpenAIConfigimport litellm, jsonimport httpxfrom .custom_httpx.azure_dall_e_2 import CustomHTTPTransport, AsyncCustomHTTPTransportfrom openai import AzureOpenAI, AsyncAzureOpenAI
class AzureOpenAIError(Exception): def __init__( self, status_code, message, request: Optional[httpx.Request] = None, response: Optional[httpx.Response] = None, ): self.status_code = status_code self.message = message if request: self.request = request else: self.request = httpx.Request(method="POST", url="https://api.openai.com/v1") if response: self.response = response else: self.response = httpx.Response( status_code=status_code, request=self.request ) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class AzureOpenAIConfig(OpenAIConfig): """ Reference: https://platform.openai.com/docs/api-reference/chat/create
The class `AzureOpenAIConfig` provides configuration for the OpenAI's Chat API interface, for use with Azure. It inherits from `OpenAIConfig`. Below are the parameters::
- `frequency_penalty` (number or null): Defaults to 0. Allows a value between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, thereby minimizing repetition.
- `function_call` (string or object): This optional parameter controls how the model calls functions.
- `functions` (array): An optional parameter. It is a list of functions for which the model may generate JSON inputs.
- `logit_bias` (map): This optional parameter modifies the likelihood of specified tokens appearing in the completion.
- `max_tokens` (integer or null): This optional parameter helps to set the maximum number of tokens to generate in the chat completion.
- `n` (integer or null): This optional parameter helps to set how many chat completion choices to generate for each input message.
- `presence_penalty` (number or null): Defaults to 0. It penalizes new tokens based on if they appear in the text so far, hence increasing the model's likelihood to talk about new topics.
- `stop` (string / array / null): Specifies up to 4 sequences where the API will stop generating further tokens.
- `temperature` (number or null): Defines the sampling temperature to use, varying between 0 and 2.
- `top_p` (number or null): An alternative to sampling with temperature, used for nucleus sampling. """
def __init__( self, frequency_penalty: Optional[int] = None, function_call: Optional[Union[str, dict]] = None, functions: Optional[list] = None, logit_bias: Optional[dict] = None, max_tokens: Optional[int] = None, n: Optional[int] = None, presence_penalty: Optional[int] = None, stop: Optional[Union[str, list]] = None, temperature: Optional[int] = None, top_p: Optional[int] = None, ) -> None: super().__init__( frequency_penalty, function_call, functions, logit_bias, max_tokens, n, presence_penalty, stop, temperature, top_p, )
class AzureChatCompletion(BaseLLM): def __init__(self) -> None: super().__init__()
def validate_environment(self, api_key, azure_ad_token): headers = { "content-type": "application/json", } if api_key is not None: headers["api-key"] = api_key elif azure_ad_token is not None: headers["Authorization"] = f"Bearer {azure_ad_token}" return headers
def completion( self, model: str, messages: list, model_response: ModelResponse, api_key: str, api_base: str, api_version: str, api_type: str, azure_ad_token: str, print_verbose: Callable, timeout, logging_obj, optional_params, litellm_params, logger_fn, acompletion: bool = False, headers: Optional[dict] = None, client=None, ): super().completion() exception_mapping_worked = False try: if model is None or messages is None: raise AzureOpenAIError( status_code=422, message=f"Missing model or messages" )
max_retries = optional_params.pop("max_retries", 2)
### CHECK IF CLOUDFLARE AI GATEWAY ### ### if so - set the model as part of the base url if "gateway.ai.cloudflare.com" in api_base: ## build base url - assume api base includes resource name if client is None: if not api_base.endswith("/"): api_base += "/" api_base += f"{model}"
azure_client_params = { "api_version": api_version, "base_url": f"{api_base}", "http_client": litellm.client_session, "max_retries": max_retries, "timeout": timeout, } if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: azure_client_params["azure_ad_token"] = azure_ad_token
if acompletion is True: client = AsyncAzureOpenAI(**azure_client_params) else: client = AzureOpenAI(**azure_client_params)
data = {"model": None, "messages": messages, **optional_params} else: data = { "model": model, # type: ignore "messages": messages, **optional_params, }
if acompletion is True: if optional_params.get("stream", False): return self.async_streaming( logging_obj=logging_obj, api_base=api_base, data=data, model=model, api_key=api_key, api_version=api_version, azure_ad_token=azure_ad_token, timeout=timeout, client=client, ) else: return self.acompletion( api_base=api_base, data=data, model_response=model_response, api_key=api_key, api_version=api_version, model=model, azure_ad_token=azure_ad_token, timeout=timeout, client=client, logging_obj=logging_obj, ) elif "stream" in optional_params and optional_params["stream"] == True: return self.streaming( logging_obj=logging_obj, api_base=api_base, data=data, model=model, api_key=api_key, api_version=api_version, azure_ad_token=azure_ad_token, timeout=timeout, client=client, ) else: ## LOGGING logging_obj.pre_call( input=messages, api_key=api_key, additional_args={ "headers": { "api_key": api_key, "azure_ad_token": azure_ad_token, }, "api_version": api_version, "api_base": api_base, "complete_input_dict": data, }, ) if not isinstance(max_retries, int): raise AzureOpenAIError( status_code=422, message="max retries must be an int" ) # init AzureOpenAI Client azure_client_params = { "api_version": api_version, "azure_endpoint": api_base, "azure_deployment": model, "http_client": litellm.client_session, "max_retries": max_retries, "timeout": timeout, } if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: azure_client_params["azure_ad_token"] = azure_ad_token if client is None: azure_client = AzureOpenAI(**azure_client_params) else: azure_client = client response = azure_client.chat.completions.create(**data, timeout=timeout) # type: ignore stringified_response = response.model_dump() ## LOGGING logging_obj.post_call( input=messages, api_key=api_key, original_response=stringified_response, additional_args={ "headers": headers, "api_version": api_version, "api_base": api_base, }, ) return convert_to_model_response_object( response_object=stringified_response, model_response_object=model_response, ) except AzureOpenAIError as e: exception_mapping_worked = True raise e except Exception as e: if hasattr(e, "status_code"): raise AzureOpenAIError(status_code=e.status_code, message=str(e)) else: raise AzureOpenAIError(status_code=500, message=str(e))
async def acompletion( self, api_key: str, api_version: str, model: str, api_base: str, data: dict, timeout: Any, model_response: ModelResponse, azure_ad_token: Optional[str] = None, client=None, # this is the AsyncAzureOpenAI logging_obj=None, ): response = None try: max_retries = data.pop("max_retries", 2) if not isinstance(max_retries, int): raise AzureOpenAIError( status_code=422, message="max retries must be an int" )
# init AzureOpenAI Client azure_client_params = { "api_version": api_version, "azure_endpoint": api_base, "azure_deployment": model, "http_client": litellm.client_session, "max_retries": max_retries, "timeout": timeout, } if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: azure_client_params["azure_ad_token"] = azure_ad_token if client is None: azure_client = AsyncAzureOpenAI(**azure_client_params) else: azure_client = client ## LOGGING logging_obj.pre_call( input=data["messages"], api_key=azure_client.api_key, additional_args={ "headers": {"Authorization": f"Bearer {azure_client.api_key}"}, "api_base": azure_client._base_url._uri_reference, "acompletion": True, "complete_input_dict": data, }, ) response = await azure_client.chat.completions.create( **data, timeout=timeout ) return convert_to_model_response_object( response_object=response.model_dump(), model_response_object=model_response, ) except AzureOpenAIError as e: exception_mapping_worked = True raise e except Exception as e: if hasattr(e, "status_code"): raise e else: raise AzureOpenAIError(status_code=500, message=str(e))
def streaming( self, logging_obj, api_base: str, api_key: str, api_version: str, data: dict, model: str, timeout: Any, azure_ad_token: Optional[str] = None, client=None, ): max_retries = data.pop("max_retries", 2) if not isinstance(max_retries, int): raise AzureOpenAIError( status_code=422, message="max retries must be an int" ) # init AzureOpenAI Client azure_client_params = { "api_version": api_version, "azure_endpoint": api_base, "azure_deployment": model, "http_client": litellm.client_session, "max_retries": max_retries, "timeout": timeout, } if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: azure_client_params["azure_ad_token"] = azure_ad_token if client is None: azure_client = AzureOpenAI(**azure_client_params) else: azure_client = client ## LOGGING logging_obj.pre_call( input=data["messages"], api_key=azure_client.api_key, additional_args={ "headers": {"Authorization": f"Bearer {azure_client.api_key}"}, "api_base": azure_client._base_url._uri_reference, "acompletion": True, "complete_input_dict": data, }, ) response = azure_client.chat.completions.create(**data, timeout=timeout) streamwrapper = CustomStreamWrapper( completion_stream=response, model=model, custom_llm_provider="azure", logging_obj=logging_obj, ) return streamwrapper
async def async_streaming( self, logging_obj, api_base: str, api_key: str, api_version: str, data: dict, model: str, timeout: Any, azure_ad_token: Optional[str] = None, client=None, ): try: # init AzureOpenAI Client azure_client_params = { "api_version": api_version, "azure_endpoint": api_base, "azure_deployment": model, "http_client": litellm.client_session, "max_retries": data.pop("max_retries", 2), "timeout": timeout, } if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: azure_client_params["azure_ad_token"] = azure_ad_token if client is None: azure_client = AsyncAzureOpenAI(**azure_client_params) else: azure_client = client ## LOGGING logging_obj.pre_call( input=data["messages"], api_key=azure_client.api_key, additional_args={ "headers": {"Authorization": f"Bearer {azure_client.api_key}"}, "api_base": azure_client._base_url._uri_reference, "acompletion": True, "complete_input_dict": data, }, ) response = await azure_client.chat.completions.create( **data, timeout=timeout ) # return response streamwrapper = CustomStreamWrapper( completion_stream=response, model=model, custom_llm_provider="azure", logging_obj=logging_obj, ) return streamwrapper ## DO NOT make this into an async for ... loop, it will yield an async generator, which won't raise errors if the response fails except Exception as e: if hasattr(e, "status_code"): raise AzureOpenAIError(status_code=e.status_code, message=str(e)) else: raise AzureOpenAIError(status_code=500, message=str(e))
async def aembedding( self, data: dict, model_response: ModelResponse, azure_client_params: dict, api_key: str, input: list, client=None, logging_obj=None, timeout=None, ): response = None try: if client is None: openai_aclient = AsyncAzureOpenAI(**azure_client_params) else: openai_aclient = client response = await openai_aclient.embeddings.create(**data, timeout=timeout) stringified_response = response.model_dump() ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=stringified_response, ) return convert_to_model_response_object( response_object=stringified_response, model_response_object=model_response, response_type="embedding", ) except Exception as e: ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=str(e), ) raise e
def embedding( self, model: str, input: list, api_key: str, api_base: str, api_version: str, timeout: float, logging_obj=None, model_response=None, optional_params=None, azure_ad_token: Optional[str] = None, client=None, aembedding=None, ): super().embedding() exception_mapping_worked = False if self._client_session is None: self._client_session = self.create_client_session() try: data = {"model": model, "input": input, **optional_params} max_retries = data.pop("max_retries", 2) if not isinstance(max_retries, int): raise AzureOpenAIError( status_code=422, message="max retries must be an int" )
# init AzureOpenAI Client azure_client_params = { "api_version": api_version, "azure_endpoint": api_base, "azure_deployment": model, "http_client": litellm.client_session, "max_retries": max_retries, "timeout": timeout, } if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: azure_client_params["azure_ad_token"] = azure_ad_token
## LOGGING logging_obj.pre_call( input=input, api_key=api_key, additional_args={ "complete_input_dict": data, "headers": {"api_key": api_key, "azure_ad_token": azure_ad_token}, }, )
if aembedding == True: response = self.aembedding( data=data, input=input, logging_obj=logging_obj, api_key=api_key, model_response=model_response, azure_client_params=azure_client_params, timeout=timeout, ) return response if client is None: azure_client = AzureOpenAI(**azure_client_params) # type: ignore else: azure_client = client ## COMPLETION CALL response = azure_client.embeddings.create(**data, timeout=timeout) # type: ignore ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data, "api_base": api_base}, original_response=response, )
return convert_to_model_response_object(response_object=response.model_dump(), model_response_object=model_response, response_type="embedding") # type: ignore except AzureOpenAIError as e: exception_mapping_worked = True raise e except Exception as e: if hasattr(e, "status_code"): raise AzureOpenAIError(status_code=e.status_code, message=str(e)) else: raise AzureOpenAIError(status_code=500, message=str(e))
async def aimage_generation( self, data: dict, model_response: ModelResponse, azure_client_params: dict, api_key: str, input: list, client=None, logging_obj=None, timeout=None, ): response = None try: if client is None: client_session = litellm.aclient_session or httpx.AsyncClient( transport=AsyncCustomHTTPTransport(), ) openai_aclient = AsyncAzureOpenAI( http_client=client_session, **azure_client_params ) else: openai_aclient = client response = await openai_aclient.images.generate(**data, timeout=timeout) stringified_response = response.model_dump() ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=stringified_response, ) return convert_to_model_response_object( response_object=stringified_response, model_response_object=model_response, response_type="image_generation", ) except Exception as e: ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=str(e), ) raise e
def image_generation( self, prompt: str, timeout: float, model: Optional[str] = None, api_key: Optional[str] = None, api_base: Optional[str] = None, api_version: Optional[str] = None, model_response: Optional[litellm.utils.ImageResponse] = None, azure_ad_token: Optional[str] = None, logging_obj=None, optional_params=None, client=None, aimg_generation=None, ): exception_mapping_worked = False try: if model and len(model) > 0: model = model else: model = None data = {"model": model, "prompt": prompt, **optional_params} max_retries = data.pop("max_retries", 2) if not isinstance(max_retries, int): raise AzureOpenAIError( status_code=422, message="max retries must be an int" )
# init AzureOpenAI Client azure_client_params = { "api_version": api_version, "azure_endpoint": api_base, "azure_deployment": model, "max_retries": max_retries, "timeout": timeout, } if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: azure_client_params["azure_ad_token"] = azure_ad_token
if aimg_generation == True: response = self.aimage_generation(data=data, input=input, logging_obj=logging_obj, model_response=model_response, api_key=api_key, client=client, azure_client_params=azure_client_params, timeout=timeout) # type: ignore return response
if client is None: client_session = litellm.client_session or httpx.Client( transport=CustomHTTPTransport(), ) azure_client = AzureOpenAI(http_client=client_session, **azure_client_params) # type: ignore else: azure_client = client
## LOGGING logging_obj.pre_call( input=prompt, api_key=azure_client.api_key, additional_args={ "headers": {"Authorization": f"Bearer {azure_client.api_key}"}, "api_base": azure_client._base_url._uri_reference, "acompletion": False, "complete_input_dict": data, }, )
## COMPLETION CALL response = azure_client.images.generate(**data, timeout=timeout) # type: ignore ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=response, ) # return response return convert_to_model_response_object(response_object=response.model_dump(), model_response_object=model_response, response_type="image_generation") # type: ignore except AzureOpenAIError as e: exception_mapping_worked = True raise e except Exception as e: if hasattr(e, "status_code"): raise AzureOpenAIError(status_code=e.status_code, message=str(e)) else: raise AzureOpenAIError(status_code=500, message=str(e))
async def ahealth_check( self, model: Optional[str], api_key: str, api_base: str, api_version: str, timeout: float, mode: str, messages: Optional[list] = None, input: Optional[list] = None, prompt: Optional[str] = None, ): client_session = litellm.aclient_session or httpx.AsyncClient( transport=AsyncCustomHTTPTransport(), # handle dall-e-2 calls ) if "gateway.ai.cloudflare.com" in api_base: ## build base url - assume api base includes resource name if not api_base.endswith("/"): api_base += "/" api_base += f"{model}" client = AsyncAzureOpenAI( base_url=api_base, api_version=api_version, api_key=api_key, timeout=timeout, http_client=client_session, ) model = None # cloudflare ai gateway, needs model=None else: client = AsyncAzureOpenAI( api_version=api_version, azure_endpoint=api_base, api_key=api_key, timeout=timeout, http_client=client_session, )
# only run this check if it's not cloudflare ai gateway if model is None and mode != "image_generation": raise Exception("model is not set")
completion = None
if mode == "completion": completion = await client.completions.with_raw_response.create( model=model, # type: ignore prompt=prompt, # type: ignore ) elif mode == "chat": if messages is None: raise Exception("messages is not set") completion = await client.chat.completions.with_raw_response.create( model=model, # type: ignore messages=messages, # type: ignore ) elif mode == "embedding": if input is None: raise Exception("input is not set") completion = await client.embeddings.with_raw_response.create( model=model, # type: ignore input=input, # type: ignore ) elif mode == "image_generation": if prompt is None: raise Exception("prompt is not set") completion = await client.images.with_raw_response.generate( model=model, # type: ignore prompt=prompt, # type: ignore ) else: raise Exception("mode not set") response = {}
if completion is None or not hasattr(completion, "headers"): raise Exception("invalid completion response")
if ( completion.headers.get("x-ratelimit-remaining-requests", None) is not None ): # not provided for dall-e requests response["x-ratelimit-remaining-requests"] = completion.headers[ "x-ratelimit-remaining-requests" ]
if completion.headers.get("x-ratelimit-remaining-tokens", None) is not None: response["x-ratelimit-remaining-tokens"] = completion.headers[ "x-ratelimit-remaining-tokens" ] return response123456789101112131415161718192021222324252627282930313233343536373839404142434445## This is a template base class to be used for adding new LLM providers via API callsimport litellmimport httpxfrom typing import Optional
class BaseLLM: _client_session: Optional[httpx.Client] = None
def create_client_session(self): if litellm.client_session: _client_session = litellm.client_session else: _client_session = httpx.Client()
return _client_session
def create_aclient_session(self): if litellm.aclient_session: _aclient_session = litellm.aclient_session else: _aclient_session = httpx.AsyncClient()
return _aclient_session
def __exit__(self): if hasattr(self, "_client_session"): self._client_session.close()
async def __aexit__(self, exc_type, exc_val, exc_tb): if hasattr(self, "_aclient_session"): await self._aclient_session.aclose()
def validate_environment(self): # set up the environment required to run the model pass
def completion( self, *args, **kwargs ): # logic for parsing in - calling - parsing out model completion calls pass
def embedding( self, *args, **kwargs ): # logic for parsing in - calling - parsing out model embedding calls pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164import osimport jsonfrom enum import Enumimport requestsimport timefrom typing import Callablefrom litellm.utils import ModelResponse, Usage
class BasetenError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message super().__init__( self.message ) # Call the base class constructor with the parameters it needs
def validate_environment(api_key): headers = { "accept": "application/json", "content-type": "application/json", } if api_key: headers["Authorization"] = f"Api-Key {api_key}" return headers
def completion( model: str, messages: list, model_response: ModelResponse, print_verbose: Callable, encoding, api_key, logging_obj, optional_params=None, litellm_params=None, logger_fn=None,): headers = validate_environment(api_key) completion_url_fragment_1 = "https://app.baseten.co/models/" completion_url_fragment_2 = "/predict" model = model prompt = "" for message in messages: if "role" in message: if message["role"] == "user": prompt += f"{message['content']}" else: prompt += f"{message['content']}" else: prompt += f"{message['content']}" data = { "inputs": prompt, "prompt": prompt, "parameters": optional_params, "stream": True if "stream" in optional_params and optional_params["stream"] == True else False, }
## LOGGING logging_obj.pre_call( input=prompt, api_key=api_key, additional_args={"complete_input_dict": data}, ) ## COMPLETION CALL response = requests.post( completion_url_fragment_1 + model + completion_url_fragment_2, headers=headers, data=json.dumps(data), stream=True if "stream" in optional_params and optional_params["stream"] == True else False, ) if "text/event-stream" in response.headers["Content-Type"] or ( "stream" in optional_params and optional_params["stream"] == True ): return response.iter_lines() else: ## LOGGING logging_obj.post_call( input=prompt, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data}, ) print_verbose(f"raw model_response: {response.text}") ## RESPONSE OBJECT completion_response = response.json() if "error" in completion_response: raise BasetenError( message=completion_response["error"], status_code=response.status_code, ) else: if "model_output" in completion_response: if ( isinstance(completion_response["model_output"], dict) and "data" in completion_response["model_output"] and isinstance(completion_response["model_output"]["data"], list) ): model_response["choices"][0]["message"][ "content" ] = completion_response["model_output"]["data"][0] elif isinstance(completion_response["model_output"], str): model_response["choices"][0]["message"][ "content" ] = completion_response["model_output"] elif "completion" in completion_response and isinstance( completion_response["completion"], str ): model_response["choices"][0]["message"][ "content" ] = completion_response["completion"] elif isinstance(completion_response, list) and len(completion_response) > 0: if "generated_text" not in completion_response: raise BasetenError( message=f"Unable to parse response. Original response: {response.text}", status_code=response.status_code, ) model_response["choices"][0]["message"][ "content" ] = completion_response[0]["generated_text"] ## GETTING LOGPROBS if ( "details" in completion_response[0] and "tokens" in completion_response[0]["details"] ): model_response.choices[0].finish_reason = completion_response[0][ "details" ]["finish_reason"] sum_logprob = 0 for token in completion_response[0]["details"]["tokens"]: sum_logprob += token["logprob"] model_response["choices"][0]["message"]._logprobs = sum_logprob else: raise BasetenError( message=f"Unable to parse response. Original response: {response.text}", status_code=response.status_code, )
## CALCULATING USAGE - baseten charges on time, not tokens - have some mapping of cost here. prompt_tokens = len(encoding.encode(prompt)) completion_tokens = len( encoding.encode(model_response["choices"][0]["message"]["content"]) )
model_response["created"] = int(time.time()) model_response["model"] = model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response
def embedding(): # logic for parsing in - calling - parsing out model embedding calls pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799import json, copy, typesimport osfrom enum import Enumimport timefrom typing import Callable, Optional, Any, Unionimport litellmfrom litellm.utils import ModelResponse, get_secret, Usagefrom .prompt_templates.factory import prompt_factory, custom_promptimport httpx
class BedrockError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request( method="POST", url="https://us-west-2.console.aws.amazon.com/bedrock" ) self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class AmazonTitanConfig: """ Reference: https://us-west-2.console.aws.amazon.com/bedrock/home?region=us-west-2#/providers?model=titan-text-express-v1
Supported Params for the Amazon Titan models:
- `maxTokenCount` (integer) max tokens, - `stopSequences` (string[]) list of stop sequence strings - `temperature` (float) temperature for model, - `topP` (int) top p for model """
maxTokenCount: Optional[int] = None stopSequences: Optional[list] = None temperature: Optional[float] = None topP: Optional[int] = None
def __init__( self, maxTokenCount: Optional[int] = None, stopSequences: Optional[list] = None, temperature: Optional[float] = None, topP: Optional[int] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
class AmazonAnthropicConfig: """ Reference: https://us-west-2.console.aws.amazon.com/bedrock/home?region=us-west-2#/providers?model=claude
Supported Params for the Amazon / Anthropic models:
- `max_tokens_to_sample` (integer) max tokens, - `temperature` (float) model temperature, - `top_k` (integer) top k, - `top_p` (integer) top p, - `stop_sequences` (string[]) list of stop sequences - e.g. ["\\n\\nHuman:"], - `anthropic_version` (string) version of anthropic for bedrock - e.g. "bedrock-2023-05-31" """
max_tokens_to_sample: Optional[int] = litellm.max_tokens stop_sequences: Optional[list] = None temperature: Optional[float] = None top_k: Optional[int] = None top_p: Optional[int] = None anthropic_version: Optional[str] = None
def __init__( self, max_tokens_to_sample: Optional[int] = None, stop_sequences: Optional[list] = None, temperature: Optional[float] = None, top_k: Optional[int] = None, top_p: Optional[int] = None, anthropic_version: Optional[str] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
class AmazonCohereConfig: """ Reference: https://us-west-2.console.aws.amazon.com/bedrock/home?region=us-west-2#/providers?model=command
Supported Params for the Amazon / Cohere models:
- `max_tokens` (integer) max tokens, - `temperature` (float) model temperature, - `return_likelihood` (string) n/a """
max_tokens: Optional[int] = None temperature: Optional[float] = None return_likelihood: Optional[str] = None
def __init__( self, max_tokens: Optional[int] = None, temperature: Optional[float] = None, return_likelihood: Optional[str] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
class AmazonAI21Config: """ Reference: https://us-west-2.console.aws.amazon.com/bedrock/home?region=us-west-2#/providers?model=j2-ultra
Supported Params for the Amazon / AI21 models:
- `maxTokens` (int32): The maximum number of tokens to generate per result. Optional, default is 16. If no `stopSequences` are given, generation stops after producing `maxTokens`.
- `temperature` (float): Modifies the distribution from which tokens are sampled. Optional, default is 0.7. A value of 0 essentially disables sampling and results in greedy decoding.
- `topP` (float): Used for sampling tokens from the corresponding top percentile of probability mass. Optional, default is 1. For instance, a value of 0.9 considers only tokens comprising the top 90% probability mass.
- `stopSequences` (array of strings): Stops decoding if any of the input strings is generated. Optional.
- `frequencyPenalty` (object): Placeholder for frequency penalty object.
- `presencePenalty` (object): Placeholder for presence penalty object.
- `countPenalty` (object): Placeholder for count penalty object. """
maxTokens: Optional[int] = None temperature: Optional[float] = None topP: Optional[float] = None stopSequences: Optional[list] = None frequencePenalty: Optional[dict] = None presencePenalty: Optional[dict] = None countPenalty: Optional[dict] = None
def __init__( self, maxTokens: Optional[int] = None, temperature: Optional[float] = None, topP: Optional[float] = None, stopSequences: Optional[list] = None, frequencePenalty: Optional[dict] = None, presencePenalty: Optional[dict] = None, countPenalty: Optional[dict] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
class AnthropicConstants(Enum): HUMAN_PROMPT = "\n\nHuman: " AI_PROMPT = "\n\nAssistant: "
class AmazonLlamaConfig: """ Reference: https://us-west-2.console.aws.amazon.com/bedrock/home?region=us-west-2#/providers?model=meta.llama2-13b-chat-v1
Supported Params for the Amazon / Meta Llama models:
- `max_gen_len` (integer) max tokens, - `temperature` (float) temperature for model, - `top_p` (float) top p for model """
max_gen_len: Optional[int] = None temperature: Optional[float] = None topP: Optional[float] = None
def __init__( self, maxTokenCount: Optional[int] = None, temperature: Optional[float] = None, topP: Optional[int] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def init_bedrock_client( region_name=None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_region_name: Optional[str] = None, aws_bedrock_runtime_endpoint: Optional[str] = None,): # check for custom AWS_REGION_NAME and use it if not passed to init_bedrock_client litellm_aws_region_name = get_secret("AWS_REGION_NAME", None) standard_aws_region_name = get_secret("AWS_REGION", None)
## CHECK IS 'os.environ/' passed in # Define the list of parameters to check params_to_check = [ aws_access_key_id, aws_secret_access_key, aws_region_name, aws_bedrock_runtime_endpoint, ]
# Iterate over parameters and update if needed for i, param in enumerate(params_to_check): if param and param.startswith("os.environ/"): params_to_check[i] = get_secret(param) # Assign updated values back to parameters ( aws_access_key_id, aws_secret_access_key, aws_region_name, aws_bedrock_runtime_endpoint, ) = params_to_check if region_name: pass elif aws_region_name: region_name = aws_region_name elif litellm_aws_region_name: region_name = litellm_aws_region_name elif standard_aws_region_name: region_name = standard_aws_region_name else: raise BedrockError( message="AWS region not set: set AWS_REGION_NAME or AWS_REGION env variable or in .env file", status_code=401, )
# check for custom AWS_BEDROCK_RUNTIME_ENDPOINT and use it if not passed to init_bedrock_client env_aws_bedrock_runtime_endpoint = get_secret("AWS_BEDROCK_RUNTIME_ENDPOINT") if aws_bedrock_runtime_endpoint: endpoint_url = aws_bedrock_runtime_endpoint elif env_aws_bedrock_runtime_endpoint: endpoint_url = env_aws_bedrock_runtime_endpoint else: endpoint_url = f"https://bedrock-runtime.{region_name}.amazonaws.com"
import boto3
if aws_access_key_id != None: # uses auth params passed to completion # aws_access_key_id is not None, assume user is trying to auth using litellm.completion
client = boto3.client( service_name="bedrock-runtime", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name, endpoint_url=endpoint_url, ) else: # aws_access_key_id is None, assume user is trying to auth using env variables # boto3 automatically reads env variables
client = boto3.client( service_name="bedrock-runtime", region_name=region_name, endpoint_url=endpoint_url, )
return client
def convert_messages_to_prompt(model, messages, provider, custom_prompt_dict): # handle anthropic prompts using anthropic constants if provider == "anthropic": if model in custom_prompt_dict: # check if the model has a registered custom prompt model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details["roles"], initial_prompt_value=model_prompt_details["initial_prompt_value"], final_prompt_value=model_prompt_details["final_prompt_value"], messages=messages, ) else: prompt = prompt_factory( model=model, messages=messages, custom_llm_provider="anthropic" ) else: prompt = "" for message in messages: if "role" in message: if message["role"] == "user": prompt += f"{message['content']}" else: prompt += f"{message['content']}" else: prompt += f"{message['content']}" return prompt
"""BEDROCK AUTH Keys/Varsos.environ['AWS_ACCESS_KEY_ID'] = ""os.environ['AWS_SECRET_ACCESS_KEY'] = """""
# set os.environ['AWS_REGION_NAME'] = <your-region_name>
def completion( model: str, messages: list, custom_prompt_dict: dict, model_response: ModelResponse, print_verbose: Callable, encoding, logging_obj, optional_params=None, litellm_params=None, logger_fn=None,): exception_mapping_worked = False try: # pop aws_secret_access_key, aws_access_key_id, aws_region_name from kwargs, since completion calls fail with them aws_secret_access_key = optional_params.pop("aws_secret_access_key", None) aws_access_key_id = optional_params.pop("aws_access_key_id", None) aws_region_name = optional_params.pop("aws_region_name", None) aws_bedrock_runtime_endpoint = optional_params.pop( "aws_bedrock_runtime_endpoint", None )
# use passed in BedrockRuntime.Client if provided, otherwise create a new one client = optional_params.pop("aws_bedrock_client", None)
# only init client, if user did not pass one if client is None: client = init_bedrock_client( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_region_name=aws_region_name, aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint, )
model = model modelId = ( optional_params.pop("model_id", None) or model ) # default to model if not passed provider = model.split(".")[0] prompt = convert_messages_to_prompt( model, messages, provider, custom_prompt_dict ) inference_params = copy.deepcopy(optional_params) stream = inference_params.pop("stream", False) if provider == "anthropic": ## LOAD CONFIG config = litellm.AmazonAnthropicConfig.get_config() for k, v in config.items(): if ( k not in inference_params ): # completion(top_k=3) > anthropic_config(top_k=3) <- allows for dynamic variables to be passed in inference_params[k] = v data = json.dumps({"prompt": prompt, **inference_params}) elif provider == "ai21": ## LOAD CONFIG config = litellm.AmazonAI21Config.get_config() for k, v in config.items(): if ( k not in inference_params ): # completion(top_k=3) > anthropic_config(top_k=3) <- allows for dynamic variables to be passed in inference_params[k] = v
data = json.dumps({"prompt": prompt, **inference_params}) elif provider == "cohere": ## LOAD CONFIG config = litellm.AmazonCohereConfig.get_config() for k, v in config.items(): if ( k not in inference_params ): # completion(top_k=3) > anthropic_config(top_k=3) <- allows for dynamic variables to be passed in inference_params[k] = v if optional_params.get("stream", False) == True: inference_params[ "stream" ] = True # cohere requires stream = True in inference params data = json.dumps({"prompt": prompt, **inference_params}) elif provider == "meta": ## LOAD CONFIG config = litellm.AmazonLlamaConfig.get_config() for k, v in config.items(): if ( k not in inference_params ): # completion(top_k=3) > anthropic_config(top_k=3) <- allows for dynamic variables to be passed in inference_params[k] = v data = json.dumps({"prompt": prompt, **inference_params}) elif provider == "amazon": # amazon titan ## LOAD CONFIG config = litellm.AmazonTitanConfig.get_config() for k, v in config.items(): if ( k not in inference_params ): # completion(top_k=3) > amazon_config(top_k=3) <- allows for dynamic variables to be passed in inference_params[k] = v
data = json.dumps( { "inputText": prompt, "textGenerationConfig": inference_params, } ) else: data = json.dumps({})
## COMPLETION CALL accept = "application/json" contentType = "application/json" if stream == True: if provider == "ai21": ## LOGGING request_str = f""" response = client.invoke_model( body={data}, modelId={modelId}, accept=accept, contentType=contentType ) """ logging_obj.pre_call( input=prompt, api_key="", additional_args={ "complete_input_dict": data, "request_str": request_str, }, )
response = client.invoke_model( body=data, modelId=modelId, accept=accept, contentType=contentType )
response = response.get("body").read() return response else: ## LOGGING request_str = f""" response = client.invoke_model_with_response_stream( body={data}, modelId={modelId}, accept=accept, contentType=contentType ) """ logging_obj.pre_call( input=prompt, api_key="", additional_args={ "complete_input_dict": data, "request_str": request_str, }, )
response = client.invoke_model_with_response_stream( body=data, modelId=modelId, accept=accept, contentType=contentType ) response = response.get("body") return response try: ## LOGGING request_str = f""" response = client.invoke_model( body={data}, modelId={modelId}, accept=accept, contentType=contentType ) """ logging_obj.pre_call( input=prompt, api_key="", additional_args={ "complete_input_dict": data, "request_str": request_str, }, ) response = client.invoke_model( body=data, modelId=modelId, accept=accept, contentType=contentType ) except client.exceptions.ValidationException as e: if "The provided model identifier is invalid" in str(e): raise BedrockError(status_code=404, message=str(e)) raise BedrockError(status_code=400, message=str(e)) except Exception as e: raise BedrockError(status_code=500, message=str(e))
response_body = json.loads(response.get("body").read())
## LOGGING logging_obj.post_call( input=prompt, api_key="", original_response=json.dumps(response_body), additional_args={"complete_input_dict": data}, ) print_verbose(f"raw model_response: {response}") ## RESPONSE OBJECT outputText = "default" if provider == "ai21": outputText = response_body.get("completions")[0].get("data").get("text") elif provider == "anthropic": outputText = response_body["completion"] model_response["finish_reason"] = response_body["stop_reason"] elif provider == "cohere": outputText = response_body["generations"][0]["text"] elif provider == "meta": outputText = response_body["generation"] else: # amazon titan outputText = response_body.get("results")[0].get("outputText")
response_metadata = response.get("ResponseMetadata", {}) if response_metadata.get("HTTPStatusCode", 500) >= 400: raise BedrockError( message=outputText, status_code=response_metadata.get("HTTPStatusCode", 500), ) else: try: if len(outputText) > 0: model_response["choices"][0]["message"]["content"] = outputText except: raise BedrockError( message=json.dumps(outputText), status_code=response_metadata.get("HTTPStatusCode", 500), )
## CALCULATING USAGE - baseten charges on time, not tokens - have some mapping of cost here. prompt_tokens = len(encoding.encode(prompt)) completion_tokens = len( encoding.encode(model_response["choices"][0]["message"].get("content", "")) )
model_response["created"] = int(time.time()) model_response["model"] = model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response except BedrockError as e: exception_mapping_worked = True raise e except Exception as e: if exception_mapping_worked: raise e else: import traceback
raise BedrockError(status_code=500, message=traceback.format_exc())
def _embedding_func_single( model: str, input: str, client: Any, optional_params=None, encoding=None, logging_obj=None,): # logic for parsing in - calling - parsing out model embedding calls ## FORMAT EMBEDDING INPUT ## provider = model.split(".")[0] inference_params = copy.deepcopy(optional_params) inference_params.pop( "user", None ) # make sure user is not passed in for bedrock call modelId = ( optional_params.pop("model_id", None) or model ) # default to model if not passed if provider == "amazon": input = input.replace(os.linesep, " ") data = {"inputText": input, **inference_params} # data = json.dumps(data) elif provider == "cohere": inference_params["input_type"] = inference_params.get( "input_type", "search_document" ) # aws bedrock example default - https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/providers?model=cohere.embed-english-v3 data = {"texts": [input], **inference_params} # type: ignore body = json.dumps(data).encode("utf-8") ## LOGGING request_str = f""" response = client.invoke_model( body={body}, modelId={modelId}, accept="*/*", contentType="application/json", )""" # type: ignore logging_obj.pre_call( input=input, api_key="", # boto3 is used for init. additional_args={ "complete_input_dict": {"model": modelId, "texts": input}, "request_str": request_str, }, ) try: response = client.invoke_model( body=body, modelId=modelId, accept="*/*", contentType="application/json", ) response_body = json.loads(response.get("body").read()) ## LOGGING logging_obj.post_call( input=input, api_key="", additional_args={"complete_input_dict": data}, original_response=json.dumps(response_body), ) if provider == "cohere": response = response_body.get("embeddings") # flatten list response = [item for sublist in response for item in sublist] return response elif provider == "amazon": return response_body.get("embedding") except Exception as e: raise BedrockError( message=f"Embedding Error with model {model}: {e}", status_code=500 )
def embedding( model: str, input: Union[list, str], api_key: Optional[str] = None, logging_obj=None, model_response=None, optional_params=None, encoding=None,): ### BOTO3 INIT ### # pop aws_secret_access_key, aws_access_key_id, aws_region_name from kwargs, since completion calls fail with them aws_secret_access_key = optional_params.pop("aws_secret_access_key", None) aws_access_key_id = optional_params.pop("aws_access_key_id", None) aws_region_name = optional_params.pop("aws_region_name", None) aws_bedrock_runtime_endpoint = optional_params.pop( "aws_bedrock_runtime_endpoint", None )
# use passed in BedrockRuntime.Client if provided, otherwise create a new one client = init_bedrock_client( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_region_name=aws_region_name, aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint, ) if type(input) == str: embeddings = [ _embedding_func_single( model, input, optional_params=optional_params, client=client, logging_obj=logging_obj, ) ] else: ## Embedding Call embeddings = [ _embedding_func_single( model, i, optional_params=optional_params, client=client, logging_obj=logging_obj, ) for i in input ] # [TODO]: make these parallel calls
## Populate OpenAI compliant dictionary embedding_response = [] for idx, embedding in enumerate(embeddings): embedding_response.append( { "object": "embedding", "index": idx, "embedding": embedding, } ) model_response["object"] = "list" model_response["data"] = embedding_response model_response["model"] = model input_tokens = 0
input_str = "".join(input)
input_tokens += len(encoding.encode(input_str))
usage = Usage( prompt_tokens=input_tokens, completion_tokens=0, total_tokens=input_tokens + 0 ) model_response.usage = usage
return model_response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176import os, typesimport jsonfrom enum import Enumimport requestsimport timefrom typing import Callable, Optionalimport litellmimport httpxfrom litellm.utils import ModelResponse, Usagefrom .prompt_templates.factory import prompt_factory, custom_prompt
class CloudflareError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request(method="POST", url="https://api.cloudflare.com") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class CloudflareConfig: max_tokens: Optional[int] = None stream: Optional[bool] = None
def __init__( self, max_tokens: Optional[int] = None, stream: Optional[bool] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def validate_environment(api_key): if api_key is None: raise ValueError( "Missing CloudflareError API Key - A call is being made to cloudflare but no key is set either in the environment variables or via params" ) headers = { "accept": "application/json", "content-type": "application/json", "Authorization": "Bearer " + api_key, } return headers
def completion( model: str, messages: list, api_base: str, model_response: ModelResponse, print_verbose: Callable, encoding, api_key, logging_obj, custom_prompt_dict={}, optional_params=None, litellm_params=None, logger_fn=None,): headers = validate_environment(api_key)
## Load Config config = litellm.CloudflareConfig.get_config() for k, v in config.items(): if k not in optional_params: optional_params[k] = v
print_verbose(f"CUSTOM PROMPT DICT: {custom_prompt_dict}; model: {model}") if model in custom_prompt_dict: # check if the model has a registered custom prompt model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details.get("roles", {}), initial_prompt_value=model_prompt_details.get("initial_prompt_value", ""), final_prompt_value=model_prompt_details.get("final_prompt_value", ""), bos_token=model_prompt_details.get("bos_token", ""), eos_token=model_prompt_details.get("eos_token", ""), messages=messages, )
# cloudflare adds the model to the api base api_base = api_base + model
data = { "messages": messages, **optional_params, }
## LOGGING logging_obj.pre_call( input=messages, api_key=api_key, additional_args={ "headers": headers, "api_base": api_base, "complete_input_dict": data, }, )
## COMPLETION CALL if "stream" in optional_params and optional_params["stream"] == True: response = requests.post( api_base, headers=headers, data=json.dumps(data), stream=optional_params["stream"], ) return response.iter_lines() else: response = requests.post(api_base, headers=headers, data=json.dumps(data)) ## LOGGING logging_obj.post_call( input=messages, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data}, ) print_verbose(f"raw model_response: {response.text}") ## RESPONSE OBJECT if response.status_code != 200: raise CloudflareError( status_code=response.status_code, message=response.text ) completion_response = response.json()
model_response["choices"][0]["message"]["content"] = completion_response[ "result" ]["response"]
## CALCULATING USAGE print_verbose( f"CALCULATING CLOUDFLARE TOKEN USAGE. Model Response: {model_response}; model_response['choices'][0]['message'].get('content', ''): {model_response['choices'][0]['message'].get('content', None)}" ) prompt_tokens = litellm.utils.get_token_count(messages=messages, model=model) completion_tokens = len( encoding.encode(model_response["choices"][0]["message"].get("content", "")) )
model_response["created"] = int(time.time()) model_response["model"] = "cloudflare/" + model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response
def embedding(): # logic for parsing in - calling - parsing out model embedding calls pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293import os, typesimport jsonfrom enum import Enumimport requestsimport time, tracebackfrom typing import Callable, Optionalfrom litellm.utils import ModelResponse, Choices, Message, Usageimport litellmimport httpx
class CohereError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request( method="POST", url="https://api.cohere.ai/v1/generate" ) self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class CohereConfig: """ Reference: https://docs.cohere.com/reference/generate
The class `CohereConfig` provides configuration for the Cohere's API interface. Below are the parameters:
- `num_generations` (integer): Maximum number of generations returned. Default is 1, with a minimum value of 1 and a maximum value of 5.
- `max_tokens` (integer): Maximum number of tokens the model will generate as part of the response. Default value is 20.
- `truncate` (string): Specifies how the API handles inputs longer than maximum token length. Options include NONE, START, END. Default is END.
- `temperature` (number): A non-negative float controlling the randomness in generation. Lower temperatures result in less random generations. Default is 0.75.
- `preset` (string): Identifier of a custom preset, a combination of parameters such as prompt, temperature etc.
- `end_sequences` (array of strings): The generated text gets cut at the beginning of the earliest occurrence of an end sequence, which will be excluded from the text.
- `stop_sequences` (array of strings): The generated text gets cut at the end of the earliest occurrence of a stop sequence, which will be included in the text.
- `k` (integer): Limits generation at each step to top `k` most likely tokens. Default is 0.
- `p` (number): Limits generation at each step to most likely tokens with total probability mass of `p`. Default is 0.
- `frequency_penalty` (number): Reduces repetitiveness of generated tokens. Higher values apply stronger penalties to previously occurred tokens.
- `presence_penalty` (number): Reduces repetitiveness of generated tokens. Similar to frequency_penalty, but this penalty applies equally to all tokens that have already appeared.
- `return_likelihoods` (string): Specifies how and if token likelihoods are returned with the response. Options include GENERATION, ALL and NONE.
- `logit_bias` (object): Used to prevent the model from generating unwanted tokens or to incentivize it to include desired tokens. e.g. {"hello_world": 1233} """
num_generations: Optional[int] = None max_tokens: Optional[int] = None truncate: Optional[str] = None temperature: Optional[int] = None preset: Optional[str] = None end_sequences: Optional[list] = None stop_sequences: Optional[list] = None k: Optional[int] = None p: Optional[int] = None frequency_penalty: Optional[int] = None presence_penalty: Optional[int] = None return_likelihoods: Optional[str] = None logit_bias: Optional[dict] = None
def __init__( self, num_generations: Optional[int] = None, max_tokens: Optional[int] = None, truncate: Optional[str] = None, temperature: Optional[int] = None, preset: Optional[str] = None, end_sequences: Optional[list] = None, stop_sequences: Optional[list] = None, k: Optional[int] = None, p: Optional[int] = None, frequency_penalty: Optional[int] = None, presence_penalty: Optional[int] = None, return_likelihoods: Optional[str] = None, logit_bias: Optional[dict] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def validate_environment(api_key): headers = { "accept": "application/json", "content-type": "application/json", } if api_key: headers["Authorization"] = f"Bearer {api_key}" return headers
def completion( model: str, messages: list, api_base: str, model_response: ModelResponse, print_verbose: Callable, encoding, api_key, logging_obj, optional_params=None, litellm_params=None, logger_fn=None,): headers = validate_environment(api_key) completion_url = api_base model = model prompt = " ".join(message["content"] for message in messages)
## Load Config config = litellm.CohereConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > cohere_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
data = { "model": model, "prompt": prompt, **optional_params, }
## LOGGING logging_obj.pre_call( input=prompt, api_key=api_key, additional_args={ "complete_input_dict": data, "headers": headers, "api_base": completion_url, }, ) ## COMPLETION CALL response = requests.post( completion_url, headers=headers, data=json.dumps(data), stream=optional_params["stream"] if "stream" in optional_params else False, ) ## error handling for cohere calls if response.status_code != 200: raise CohereError(message=response.text, status_code=response.status_code)
if "stream" in optional_params and optional_params["stream"] == True: return response.iter_lines() else: ## LOGGING logging_obj.post_call( input=prompt, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data}, ) print_verbose(f"raw model_response: {response.text}") ## RESPONSE OBJECT completion_response = response.json() if "error" in completion_response: raise CohereError( message=completion_response["error"], status_code=response.status_code, ) else: try: choices_list = [] for idx, item in enumerate(completion_response["generations"]): if len(item["text"]) > 0: message_obj = Message(content=item["text"]) else: message_obj = Message(content=None) choice_obj = Choices( finish_reason=item["finish_reason"], index=idx + 1, message=message_obj, ) choices_list.append(choice_obj) model_response["choices"] = choices_list except Exception as e: raise CohereError( message=response.text, status_code=response.status_code )
## CALCULATING USAGE prompt_tokens = len(encoding.encode(prompt)) completion_tokens = len( encoding.encode(model_response["choices"][0]["message"].get("content", "")) )
model_response["created"] = int(time.time()) model_response["model"] = model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response
def embedding( model: str, input: list, api_key: Optional[str] = None, logging_obj=None, model_response=None, encoding=None, optional_params=None,): headers = validate_environment(api_key) embed_url = "https://api.cohere.ai/v1/embed" model = model data = {"model": model, "texts": input, **optional_params}
if "3" in model and "input_type" not in data: # cohere v3 embedding models require input_type, if no input_type is provided, default to "search_document" data["input_type"] = "search_document"
## LOGGING logging_obj.pre_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, ) ## COMPLETION CALL response = requests.post(embed_url, headers=headers, data=json.dumps(data)) ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=response, ) """ response { 'object': "list", 'data': [ ] 'model', 'usage' } """ if response.status_code != 200: raise CohereError(message=response.text, status_code=response.status_code) embeddings = response.json()["embeddings"] output_data = [] for idx, embedding in enumerate(embeddings): output_data.append( {"object": "embedding", "index": idx, "embedding": embedding} ) model_response["object"] = "list" model_response["data"] = output_data model_response["model"] = model input_tokens = 0 for text in input: input_tokens += len(encoding.encode(text))
model_response["usage"] = { "prompt_tokens": input_tokens, "total_tokens": input_tokens, } return model_response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import time, json, httpx, asyncio
class AsyncCustomHTTPTransport(httpx.AsyncHTTPTransport): """ Async implementation of custom http transport """
async def handle_async_request(self, request: httpx.Request) -> httpx.Response: if "images/generations" in request.url.path and request.url.params[ "api-version" ] in [ # dall-e-3 starts from `2023-12-01-preview` so we should be able to avoid conflict "2023-06-01-preview", "2023-07-01-preview", "2023-08-01-preview", "2023-09-01-preview", "2023-10-01-preview", ]: request.url = request.url.copy_with( path="/openai/images/generations:submit" ) response = await super().handle_async_request(request) operation_location_url = response.headers["operation-location"] request.url = httpx.URL(operation_location_url) request.method = "GET" response = await super().handle_async_request(request) await response.aread()
timeout_secs: int = 120 start_time = time.time() while response.json()["status"] not in ["succeeded", "failed"]: if time.time() - start_time > timeout_secs: timeout = { "error": { "code": "Timeout", "message": "Operation polling timed out.", } } return httpx.Response( status_code=400, headers=response.headers, content=json.dumps(timeout).encode("utf-8"), request=request, )
time.sleep(int(response.headers.get("retry-after")) or 10) response = await super().handle_async_request(request) await response.aread()
if response.json()["status"] == "failed": error_data = response.json() return httpx.Response( status_code=400, headers=response.headers, content=json.dumps(error_data).encode("utf-8"), request=request, )
result = response.json()["result"] return httpx.Response( status_code=200, headers=response.headers, content=json.dumps(result).encode("utf-8"), request=request, ) return await super().handle_async_request(request)
class CustomHTTPTransport(httpx.HTTPTransport): """ This class was written as a workaround to support dall-e-2 on openai > v1.x
Refer to this issue for more: https://github.com/openai/openai-python/issues/692 """
def handle_request( self, request: httpx.Request, ) -> httpx.Response: if "images/generations" in request.url.path and request.url.params[ "api-version" ] in [ # dall-e-3 starts from `2023-12-01-preview` so we should be able to avoid conflict "2023-06-01-preview", "2023-07-01-preview", "2023-08-01-preview", "2023-09-01-preview", "2023-10-01-preview", ]: request.url = request.url.copy_with( path="/openai/images/generations:submit" ) response = super().handle_request(request) operation_location_url = response.headers["operation-location"] request.url = httpx.URL(operation_location_url) request.method = "GET" response = super().handle_request(request) response.read()
timeout_secs: int = 120 start_time = time.time() while response.json()["status"] not in ["succeeded", "failed"]: if time.time() - start_time > timeout_secs: timeout = { "error": { "code": "Timeout", "message": "Operation polling timed out.", } } return httpx.Response( status_code=400, headers=response.headers, content=json.dumps(timeout).encode("utf-8"), request=request, )
time.sleep(int(response.headers.get("retry-after")) or 10) response = super().handle_request(request) response.read()
if response.json()["status"] == "failed": error_data = response.json() return httpx.Response( status_code=400, headers=response.headers, content=json.dumps(error_data).encode("utf-8"), request=request, )
result = response.json()["result"] return httpx.Response( status_code=200, headers=response.headers, content=json.dumps(result).encode("utf-8"), request=request, ) return super().handle_request(request)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222import os, types, traceback, copyimport jsonfrom enum import Enumimport timefrom typing import Callable, Optionalfrom litellm.utils import ModelResponse, get_secret, Choices, Message, Usageimport litellmimport sys, httpxfrom .prompt_templates.factory import prompt_factory, custom_prompt
class GeminiError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request( method="POST", url="https://developers.generativeai.google/api/python/google/generativeai/chat", ) self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class GeminiConfig: """ Reference: https://ai.google.dev/api/python/google/generativeai/GenerationConfig
The class `GeminiConfig` provides configuration for the Gemini's API interface. Here are the parameters:
- `candidate_count` (int): Number of generated responses to return.
- `stop_sequences` (List[str]): The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop at the first appearance of a stop sequence. The stop sequence will not be included as part of the response.
- `max_output_tokens` (int): The maximum number of tokens to include in a candidate. If unset, this will default to output_token_limit specified in the model's specification.
- `temperature` (float): Controls the randomness of the output. Note: The default value varies by model, see the Model.temperature attribute of the Model returned the genai.get_model function. Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will produce responses that are more varied and creative, while a value closer to 0.0 will typically result in more straightforward responses from the model.
- `top_p` (float): Optional. The maximum cumulative probability of tokens to consider when sampling.
- `top_k` (int): Optional. The maximum number of tokens to consider when sampling. """
candidate_count: Optional[int] = None stop_sequences: Optional[list] = None max_output_tokens: Optional[int] = None temperature: Optional[float] = None top_p: Optional[float] = None top_k: Optional[int] = None
def __init__( self, candidate_count: Optional[int] = None, stop_sequences: Optional[list] = None, max_output_tokens: Optional[int] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, top_k: Optional[int] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def completion( model: str, messages: list, model_response: ModelResponse, print_verbose: Callable, api_key, encoding, logging_obj, custom_prompt_dict: dict, acompletion: bool = False, optional_params=None, litellm_params=None, logger_fn=None,): try: import google.generativeai as genai except: raise Exception( "Importing google.generativeai failed, please run 'pip install -q google-generativeai" ) genai.configure(api_key=api_key)
if model in custom_prompt_dict: # check if the model has a registered custom prompt model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details["roles"], initial_prompt_value=model_prompt_details["initial_prompt_value"], final_prompt_value=model_prompt_details["final_prompt_value"], messages=messages, ) else: prompt = prompt_factory( model=model, messages=messages, custom_llm_provider="gemini" )
## Load Config inference_params = copy.deepcopy(optional_params) inference_params.pop( "stream", None ) # palm does not support streaming, so we handle this by fake streaming in main.py config = litellm.GeminiConfig.get_config() for k, v in config.items(): if ( k not in inference_params ): # completion(top_k=3) > gemini_config(top_k=3) <- allows for dynamic variables to be passed in inference_params[k] = v
## LOGGING logging_obj.pre_call( input=prompt, api_key="", additional_args={"complete_input_dict": {"inference_params": inference_params}}, ) ## COMPLETION CALL try: _model = genai.GenerativeModel(f"models/{model}") response = _model.generate_content( contents=prompt, generation_config=genai.types.GenerationConfig(**inference_params), ) except Exception as e: raise GeminiError( message=str(e), status_code=500, )
## LOGGING logging_obj.post_call( input=prompt, api_key="", original_response=response, additional_args={"complete_input_dict": {}}, ) print_verbose(f"raw model_response: {response}") ## RESPONSE OBJECT completion_response = response try: choices_list = [] for idx, item in enumerate(completion_response.candidates): if len(item.content.parts) > 0: message_obj = Message(content=item.content.parts[0].text) else: message_obj = Message(content=None) choice_obj = Choices(index=idx + 1, message=message_obj) choices_list.append(choice_obj) model_response["choices"] = choices_list except Exception as e: traceback.print_exc() raise GeminiError( message=traceback.format_exc(), status_code=response.status_code )
try: completion_response = model_response["choices"][0]["message"].get("content") if completion_response is None: raise Exception except: original_response = f"response: {response}" if hasattr(response, "candidates"): original_response = f"response: {response.candidates}" if "SAFETY" in original_response: original_response += "\nThe candidate content was flagged for safety reasons." elif "RECITATION" in original_response: original_response += "\nThe candidate content was flagged for recitation reasons." raise GeminiError( status_code=400, message=f"No response received. Original response - {original_response}", )
## CALCULATING USAGE prompt_str = "" for m in messages: if isinstance(m["content"], str): prompt_str += m["content"] elif isinstance(m["content"], list): for content in m["content"]: if content["type"] == "text": prompt_str += content["text"] prompt_tokens = len(encoding.encode(prompt_str)) completion_tokens = len( encoding.encode(model_response["choices"][0]["message"].get("content", "")) )
model_response["created"] = int(time.time()) model_response["model"] = "gemini/" + model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response
def embedding(): # logic for parsing in - calling - parsing out model embedding calls pass1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225230xDEADBEA7/DialoGPT-small-rick1Basco/DialoGPT-small-jake2early4coffee/DialoGPT-medium-deadpool2early4coffee/DialoGPT-small-deadpool2gud/DialogGPT-small-KoopsbotABBHISHEK/DialoGPT-small-harrypotterAIDynamics/DialoGPT-medium-MentorDealerGuyAJ/DialoGPT-small-ricksanchezAJ/rick-discord-botAJ/rick-sanchez-botAJ-Dude/DialoGPT-small-harrypotterAK270802/DialoGPT-small-harrypotterATGdev/DialoGPT-small-harrypotterAVeryRealHuman/DialoGPT-small-TonyStarkAbhinavSaiTheGreat/DialoGPT-small-harrypotterAccurateIsaiah/DialoGPT-small-jefftasticAccurateIsaiah/DialoGPT-small-mozarkAccurateIsaiah/DialoGPT-small-mozarkv2AccurateIsaiah/DialoGPT-small-sinclairAdharshJolly/HarryPotterBot-ModelAdrianGzz/DialoGPT-small-harrypotterAero/Tsubomi-HarunoAetherIT/DialoGPT-small-HalAiPorter/DialoGPT-small-Back_to_the_futureAibox/DialoGPT-small-rickAkjder/DialoGPT-small-harrypotterAllwynJ/HarryBoyAnthonyNelson/DialoGPT-small-ricksanchezApisate/DialoGPT-small-jordanArJakusz/DialoGPT-small-starkAran/DialoGPT-medium-harrypotterAran/DialoGPT-small-harrypotterArcktosh/DialoGPT-small-rickAriakimTaiyo/DialoGPT-cultured-KumikoAriakimTaiyo/DialoGPT-medium-KumikoAriakimTaiyo/DialoGPT-revised-KumikoAriakimTaiyo/DialoGPT-small-KumikoAriakimTaiyo/DialoGPT-small-RikkaArtemisZealot/DialoGTP-small-QkarinAruden/DialoGPT-medium-harrypotterallAspect11/DialoGPT-Medium-LiSBotAsuramaru/DialoGPT-small-rintohsakaAtchuth/DialoGPT-small-MichaelBotAugustvember/WOKKAWOKKAAugustvember/WokkaBot3Augustvember/testAugustvember/wokka2Augustvember/wokka4Augustvember/wokka5Augustvember/wokkabottest2AvatarXD/DialoGPT-medium-BlitzoAwsaf/DialoGPT-medium-erenAwsaf/large-erenAxcel/DialoGPT-small-rickAyjayo/DialoGPT-medium-AyjayoAIAyran/DialoGPT-medium-harry-potter-1-through-3Ayran/DialoGPT-medium-harry-potter-1-through-4-plus-6-e18Ayran/DialoGPT-medium-harry-potter-1-through-4-plus-6Ayran/DialoGPT-small-gandalfAyran/DialoGPT-small-harry-potter-1-through-3Azuris/DialoGPT-medium-envyAzuris/DialoGPT-medium-senoritaAzuris/DialoGPT-small-envyBW/TESTBackedman/DialoGPT-small-AnikaBalajiSathesh/DialoGPT-small-harrypotterBatsy24/DialoGPT-medium-Twilight_BellaBotBatsy24/DialoGPT-small-Twilight_EdBotBee-Garbs/DialoGPT-real-cartman-smallBiasface/DDDCBiasface/DDDC2BigTooth/DialoGPT-MeguminBigTooth/DialoGPT-small-tohruBigTooth/Megumin-v0.2BigeS/DialoGPT-small-RickBimal/my_bot_modelBinksSachary/DialoGPT-small-shaxxBinksSachary/ShaxxBotBinksSachary/ShaxxBot2BlightZz/DialoGPT-medium-KurisuBlightZz/MakiseKurisuBlueGamerBeast/DialoGPT-small-MorganaBotterHax/DialoGPT-small-harrypotterBroadus20/DialoGPT-small-joshuaBrunoNogueira/DialoGPT-kungfupandaBrykee/DialoGPT-medium-MortyBubb-les/DisloGPT-medium-HarryPotterCamzure/MaamiBot-testCanadiancaleb/DialoGPT-small-jesseCanadiancaleb/DialoGPT-small-walterCasualHomie/DialoGPT-small-harrypotterChae/botmanChakita/FriendsChalponkey/DialoGPT-small-BarryChaseBread/DialoGPT-small-harrypotterChiuchiyin/DialoGPT-small-DonaldChrisVCB/DialoGPT-medium-cmjsChrisVCB/DialoGPT-medium-ejChuah/DialoGPT-small-harrypotterChukSamuels/DialoGPT-small-Dr.FauciBotCiruzzo/DialoGPT-small-harrypotterClaudeCOULOMBE/RickBotCloudy/DialoGPT-CJ-largeClydeWasTaken/DialoGPT-small-joshuaCodeDanCode/CartmenBotCodeDanCode/SP-KyleBotCoderBoy432/DialoGPT-small-harrypotterCoderEFE/DialoGPT-marxbotConnor/DialoGPT-small-rickConnorvr/BrightBot-smallCopymySkill/DialoGPT-medium-atakanCorvus/DialoGPT-medium-CaptainPrice-ExtendedCorvus/DialoGPT-medium-CaptainPriceCoyotl/DialoGPT-test-last-arthurmorganCoyotl/DialoGPT-test2-arthurmorganCoyotl/DialoGPT-test3-arthurmorganCracklesCreeper/Piglin-Talks-Harry-PotterCryptikdw/DialoGPT-small-rickCthyllax/DialoGPT-medium-PaladinDanseCurtisBowser/DialoGPT-medium-sora-twoCurtisBowser/DialoGPT-medium-soraCurtisBowser/DialoGPT-small-soraCyberMuffin/DialoGPT-small-ChandlerBotDARKVIP3R/DialoGPT-medium-AnakinDaivakai/DialoGPT-small-saitamaDawit/DialogGPT-small-ironmanDaymarebait/Discord_BOT_RICKDecafNosebleed/DialoGPT-small-ScaraBotDenny29/DialoGPT-medium-asunayuukiDevid/DialoGPT-small-MikuDilmk2/DialoGPT-small-harrypotterDimedrolza/DialoGPT-small-cyberpunkDingleyMaillotUrgell/homer-botDoiman/DialoGPT-medium-harrypotterDongHai/DialoGPT-small-rickDoquey/DialoGPT-small-Luisbot1Doquey/DialoGPT-small-MichaelbotDoxophobia/DialoGPT-medium-celesteDragoniod1596/DialoGPT-small-LegaciesDreyzin/DialoGPT-medium-avatarDueLinx0402/DialoGPT-small-harrypotterDuugu/jakebot3000Dyzi/DialoGPT-small-landcheeseEEE/DialoGPT-medium-brookeEEE/DialoGPT-small-aangEEE/DialoGPT-small-yodaESPersonnel/DialoGPT-small-gotEagle3ye/DialoGPT-small-PeppaPigElzen7/DialoGPT-medium-harrypotterEmi2160/DialoGPT-small-NekuEmileAjar/DialoGPT-small-harrypotterEmileAjar/DialoGPT-small-peppapigErikaka/DialoGPT-small-lokiEstoyDePaso/DialoGPT-small-harrypotterEuropeanTurtle/DialoGPT-small-mrcobbExEngineer/DialoGPT-medium-jdtExilon/DialoGPT-large-quirkEzioDD/houseFFF000/dialogpt-FFFFangLee/DialoGPT-small-KiritoFilosofas/DialoGPT-medium-PALPATINEFlampt/DialoGPT-medium-SheldonFor/sheldonbotFosterPatch/GoT-testFu10k/DialoGPT-medium-RickGabbyDaBUNBUN/DialoGPT-medium-PinkiePieGalaxy/DialoGPT-small-hermoineGamerMan02/DialoGPT-medium-gamerbotGappy/DialoGPT-small-ZhongliGeezy/DialoGPT-small-guyGenDelport/DialoGPT-small-harrypotterGowtham25/DialoGPT-small-jackieGregor-Davies/DialoGPT-small-rickGreysan/DialoGPT-medium-TOHGuard-SK/DialoGPT-medium-ricksanchezGuard-SK/DialoGPT-small-ricksanchezGunjanPantha/DialoGPT-small-gameofthronesGuy0/DialoGPT-small-BatmanbottyHAttORi/DialoGPT-Medium-zerotwoHackyHackyMan/DialoGPT-small-harrypotterHadron/DialoGPT-medium-ninoHallzy/PeterbotHamas/DialoGPT-large-jakeHamas/DialoGPT-large-jake2Hamas/DialoGPT-large-jake3Hamas/DialoGPT-large-jake4Hamhams/DialoGPT-small-rickHansAnonymous/DialoGPT-medium-rickHansAnonymous/DialoGPT-small-shrekHarryPuttar/HarryPotterDCHarshal6927/Jack_Sparrow_GPTHarshal6927/Tony_Stark_GPTHavokx/DialoGPT-small-RickHeldhy/DialoGPT-small-tonyHeldhy/testingAgainMagnusChase7/DialoGPT-medium-harrypotterHtenn/DialoGPT-small-spongebobHtenn/DialoGPT-small-spongebobv2HueJanus/DialoGPT-small-ricksanchezHypNyx/DialoGPT-small-DwightBotHypNyx/DialoGPT-small-ThanosHypedKid/PeterBotILoveThatLady/DialoGPT-small-rickandmortyITNODove/DialoGPT-medium-cyberbonesIcemiser/chat-testIlyabarigou/Genesis-harrybotterImAPizza/DialoGPT-medium-albertImAPizza/DialoGPT-medium-alberttwoInvincible/Chat_bot-Harrypotter-mediumInvincible/Chat_bot-Harrypotter-smallInvincible/DialoGPT-medium-harryPotterIstiaque190515/SherlockIstiaque190515/harry_bot_discordIstiaque190515/harry_potterItoYagura/DialoGPT-medium-tohruItzJorinoPlays/DialoGPT-small-PickleRickJ-Chiang/DialoGPT-small-thorJDS22/DialoGPT-medium-HarryPotterBotJedi33/tonystarkAIJeffrey/DialoGPT-small-JeffreyJimmyHodl/DialoGPT-mediumJllama/dialoGPT-small-Joshua-testJonesy/DialoGPT-medium_BarneyJonesy/FG_OLDJonesy/DialoGPT-small_JTJulianqll/DialoGPT-small-finalmortyJulianqll/DialoGPT-small-ricksanchezKAIHATSU/DialoGPT-small-rickKENNETHFOO/DialoGPT-medium-harrypotterKOSTAS/DialoGPT-small-CleverbotKP2500/KPBotKai0857/DialoGPT-small-harrypotterKail91/DialoGPT-small-PeraltaBotKairu/DialoGPT-small-RickKairu/RICKBOTKakoSi/Smolmm3KakoSi/opaazziKaledmgo/DialoGPT-small-donajuliaKargan/DialoGPT-small-randombotKaydenSou/JoshuaKeen/DialoGPT-small-potterKekLord/DialoGPT-small-rick3Keqing/Keqing-SiestaKeqipig/DialoGPT-small-spamtonKhanAdeeb/model-tony-starkKingCodeSquid/OctavianKingCodeSquid/Octavian2Kirili4ik/ruDialoGpt3-medium-finetuned-telegramKnutZuidema/DialoGPT-small-mortyKonggate/DialoGPT-small-harrypotterKoriyy/DialoGPT-medium-gfKoro/DialoGPT-medium-rickandmortyKoro/DialoGPT-small-rickandmortyKringleClaus/Dialog-santaKrispyIChris/DialoGPT-small-harrypotterKryptone/BurobotKryptone/RinAIKryptone/monikAI-UnstableKryptone/monikAIKshaunish/DialoGPT-small-rickKush/DialoGPT-small-harrypotterLARACHNIDE/DialogGPT-small-swLactoseLegend/DialoGPT-small-RickLaezor/DialoGPT-small-witcher1Laezor/DialoGPT-small-yakuza_0LaiJY/DialoGPTChatbotLaptop/DialoGPT-small-gandalfLenza/DialoGPT-medium-KobayashiLeonel/DialoGPT-small-chandlerLeostronkest/DialoGPT-small-michaelLeostronkest/DialoGPTLeviii03/Dialogpt-small-Jake99Lizardon/PeterbotLovery/AquaLucdi90/DialoGPT-medium-XiaoBotLuckyWill/DialoGPT-small-JakeBotLurka/DialoGPT-medium-isseibotLurka/DialoGPT-medium-konLuxiere/DialoGPT-medium-tyrionMAUtastic/DialoGPT-medium-RickandMortyBotMCUxDaredevil/DialoGPT-small-rickMS366/DialoGPT-small-visionMadhanKumar/DialoGPT-small-HarryPotterMadhanKumar/HarryPotter-BotMagmaCubes1133/DialoGPT-large-rickMandy/DialoGPT-small-MikasaManthan/DialoGPT-small-harrypotterMara/DialoGPT-medium-harrypotterMathiasVS/DialoGPT-small-RickAndMortyMaxW0748/DialoGPT-small-RickMayankGupta/DialoGPT-small-harrypotterMichaelTheLearner/DialoGPT-medium-harryMidhunkrishna/DialoGPT-small-bjkMierln/SmartHarryMightyCoderX/DialoGPT-medium-EdwardElricModzabazeR/small-okaberintaroMohsin272/DialoGPT-medium-harrypotterMona/DialoGPT-small-harrypotterMoonlitEtherna/DialoGPT-small-NyivaeMrDuckerino/DialoGPT-medium-RickMrE/DialoGPT-medium-SARGEMrE/DialoGPT-medium-SARGER1MrE/DialoGPT-medium-SARGER3MrGentle/DeltaModel-genius1MrZ/DialoGPT-small-RickMythiie/DialoGPT-small-ModeusN8Daawg/chat_botNASABOI/MachineLearningAInabarun/DialoGPT-small-joshuaNamPE/DialoGPT-medium-Aqua-konosubaNamPE/DialoGPT-medium-Takanashi-RikkaNamPE/DialoGPT-small-satouhinaNanniKirby/DialoGPT-medium-bapiNanniKirby/bapismallNaturealbe/DialoGPT-small-harrypotter-2Naturealbe/DialoGPT-small-harrypotterNavigator/DialoGPT-medium-martymcflyNavya2608/DialoGPT-medium-chandlerNavya2608/DialoGPT-medium-rachelNavya2608/DialoGPT-small-tonystarkscriptNecrozma/harrypotterbotNekoism/Zhongli-BetaNibrasShami/DialopGPT-small-HarryPotterNickCavarretta/DialoGPT-small-laffyNihwy/DialoSquiNikhilKrishna/DialoGPT-medium-harrypotterNinja5000/DialoGPT-medium-HarryPotterNinja5000/DialoGPT-medium-TWEWYJoshuaNiphredil/DialoGPT-small-lotrNisarg2701/DialoGPT-medium-RickNoLawz/DialoGPT-medium-hagridNoLawz/DialoGPT-medium-harrypotterNoLawz/DialoGPT-medium-spongebobNova/DialoGPT-medium-LelouchNovaChrono/twervyObesitycart/ChatBotObscurity/DialoGPT-Medium-707Oji/DialoGPT-small-RickOptimal/HarryP4RZ1V4L/DialoGPT-Medium-TonyPVAbhiram2003/DialoGPT-medium-RickandMortyParadocx/Dialogpt-mid-hpaiPensador777critico/DialoGPT-small-RickandMortyPhilipTheGreat/DiabloGPT-small-TravellerPinoCorgi/DialoGPT-small-Shrek1Piumi/DialogGPT-small-harrypotterPlencers/DialoGPT-small-homerPoly-Pixel/shrek-medium-fullPoly-Pixel/shrek-mediumPoly-Pixel/shrek-test-smallPupihed/DialoGPT-small-shrekPurpleJacketGuy/My_JarvisPurpleJacketGuy/My_Jarvis_2RAhul03/DialoGPT-small-harrypotterREAP3R/Chat-botREZERO/DialoGPT-medium-saitamaRTM/ChatBotRTM/LuckyRTurk/DialoGPT-small-TIMBOTRadicalkiddo/DialoGPT-small-RadicalRashid11/DialoGPT-small-rickRathod/DialoGPT-small-harrypotterRedolid/DialoGPT-small-RickRei/DialoGPT-medium-kurisuRifsxD/DialoGPT-medium-raifuRishabhRawatt/DialoGPT-small-RickmortyRishabhRawatt/DialoGPT-small-kelaRitchie/DialoGPT-small-RickandmortyRizqFarIDN/DialoGPT-medium-harrypotterRizqFarIDN/DialoGPT-small-harrypotterRobinMari/DialoGPT-small-mikotoRoyce23/DialoGPT-small-almasRush11/DialoGPT-small-HarryPotterRyanar/DialoGPT-medium-ZeldaRyukie/DialoGPT-small-RickS34NtheGuy/DialoGPT-medium-Glass_Of_WaterS34NtheGuy/DialoGPT-medium-MonaS34NtheGuy/DialoGPT-small-Harry282S34NtheGuy/DialoGPT-small-MJOLNIR_SoulS34NtheGuy/DialoGPT-small-cursedrynoS34NtheGuy/DialoGPT-small-pikamew362S34NtheGuy/DialoGPT-small-wetterlettuceSJSui/RickBotSPGT/LiveSafe-DialoGPTSaffronIce/DialoGPT-medium-JettSalma-2/DialoGPT-small-harrypotterSammigooof/PeterbotSarahhhUwU/DialoGPT-small-allySarumomo/DialoGPT-small-testSaviour/ChandlerBotSaz/DialoGPT-small-paimonSaz/DialoGPT-small-sazScience-geek32/DialoGPT-small-doctorScience-geek32/DialoGPT-small-doctor2.0Scoops/SandalBotScottaStrong/DialogGPT-medium-ScottScottaStrong/DialogGPT-medium-joshuaScottaStrong/DialogGPT-small-ScottScottaStrong/DialogGPT-small-joshuaSebastianthecrab/DialoGPT-small-melchiorSedge/DialoGPT-small-SedgeShakaw/DialoGPT-small-spongebotShayoGun/DialoGPT-small-shayoSheel/DialoGPT-small-harrypotterSheerwin02/DialoGPT-medium-mikasaSheerwin02/DialoGPT-small-islaSherman/DialoGPT-medium-joeyShike/DialoGPT_medium_harrypotterShinx/DialoGPT-medium-myheroacademiaNaturesDisaster/DialoGPT-large-NekuNaturesDisaster/DialoGPT-small-NekuShiroNeko/DialoGPT-small-rickShubham-Kumar-DTU/DialoGPT-small-gokuSilentMyuth/sarcastic-modelSilentMyuth/stablebenSirBastianXVII/DialoGPT-small-TVDSired/DialoGPT-small-trumpbotSiyris/DialoGPT-medium-SIYSiyris/SIYSkywhy/DialoGPT-medium-ChurchyySnaky/StupidEdwinSoapsy/DialoGPT-mid-cartmanSonMooSans/DialoGPT-small-joshuaSonMooSans/testSora4762/DialoGPT-small-narutoSora4762/DialoGPT-small-naruto1.1Soumyajit1008/DialoGPT-small-harryPotterssenSpacyGalaxy/DialoGPT-medium-GandalfSpectrox/emmybotSpirax/DialoGPT-medium-sheldonSpoon/DialoGPT-small-engineerStabley/DialoGPT-small-evelynnStevo/DiagloGPT-medium-spamtonStoned-Code/DioloGPT-large-Rick-SC-420Sunnydx/BillCipherBotTTYU/DialoGPT-small-trumpTVLG/DialoGPT-small-Iroh-BotTaramiko/DialoGPT-small-hoshiyo_kojimaTaramiko/Hoshiyo_KojimaTejasvb/DialoGPT-small-rickTejasvb/DialogGPT-small-rickThatSkyFox/DialoGPT-medium-joshuaThatSkyFox/DialoGPT-small-joshuaThe-Programmer-With-Cool-Pens/TifaBotAIPackageTheCatsMoo/DialoGGPT-small-joshuaTheDiamondKing/DialoGPT-small-harrypotterThePeachOx/DialoGPT-small-harryTheReverendWes/DialoGPT-small-rickTheTUFGuy/HermioneChatBotThejas/DialoGPT-small-SteweiThejas/DialoGPT-small-elonThoracicCosine/DialoGPT-small-harrypotterTidum/DialoGPT-large-MichaelToadally/DialoGPT-small-david_mastTofu05/DialoGPT-large-boon2Tofu05/DialoGPT-med-boon3TofuBoy/DialoGPT-medium-Yubin2TofuBoy/DialoGPT-medium-boonTr1ex/DialoGPT-small-rickTrebleJeff/DialoGPT-small-MichaelTrimPeachu/DeadpoolTrixzy/rickai-v1Tropics/DialoGPT-small-peppaUKJ5/DialoGPT-small-harrypotterUsername1/Mourinhio-mediumUsername1/MourinhoUsername1/WengerVLRevolution/DialogGPT-small-GGODMODELVMET/DialoGPT-small-dumbassbotVaguelyCynical/DialoGPT-small-RickSanchezVampiro/DialoGPT-small-dante_bVampiro/DialoGPT-small-dante_cVariableZee/DialoGPT-small-ivylia03Verge/PeterbotVincentButterfield/DialoGPT-small-harrypotterVishalArun/DialoGPT-medium-harrypotterVitafeu/DialoGPT-medium-ricksanchezVulcanBin/DialoGPT-small-cortanaWarrenK-Design/DialoGPT-small-RickWessel/DiabloGPT-medium-harrypotterWhite/white-botWhitez/DialoGPT-small-twetyWise/DialogGPT-small-JCWoutN2001/james3WurmWillem/DialoGPT-medium-RickandMorty3Xeouz/Ultron-SmallXuguangAi/DialoGPT-small-HarryXuguangAi/DialoGPT-small-LeslieXuguangAi/DialoGPT-small-RickYankee/test1234Zane/RickyZane/Ricky3Zeer0/DialoGPT-small-ZerOZen1/DerekbotZen1/test1Zeph/DialoGPT-small-rickZephaus/ChromrepoZixtrauce/BDBotZixtrauce/BDBot4EpochZixtrauce/BaekBotZixtrauce/BrandonBotZixtrauce/BrandonBot2Zixtrauce/JohnBotZixtrauce/SelfAwarenessZuha/DialoGPT-small-gandalfa01709042/DialoGPT-mediumaadilhassan/Chandlerbotaashutosh2102/DialoGPT-smalll-harrypotterabhiramtirumala/DialoGPT-sarcasticabhisht/DialoGPT-medium-Emilybotabjbpi/DS_smallabjbpi/Dwight_Schruteaced/DialoGPT-medium-3POadviksinghania/DialoGPT-medium-rickaf1tang/personaGPTaggb/DialogGPT-small-AGGB-Baimiekhe/yummv1aimiekhe/yummv2aishanisingh/DiagloGPT-small-michaelscottaishanisingh/DialoGPT-small-harrypotterakaushik1/DialoGPT-small-kaiserakhooli/personachat-arabicalankar/DialoGPT-small-rickalipsezzar/DialoGPT-medium-harrypotteralistair7/bbt-diagpt2-modelaluserhuggingface/DialoGPT-small-harrypotteralvinkobe/DialoGPT-medium-steve_bikoalvinkobe/DialoGPT-small-KSTandikarachman/DialoGPT-small-sheldonanduush/DialoGPT-small-Rickange/DialoGPT-medium-Monkeankimt01/DialoGPT-small-anchann101020/le2sbot-hpanshengli2/DialogGPT-small-Botanweasha/DialoGPT-small-Chandleranweasha/DialoGPT-small-Jakeaplnestrella/Aladdin-Botarampacha/DialoGPT-medium-simpsonsarchmagos/HourAIardatasc/miniMe-version1arifbhrn/DialogGPT-small-Rickkarnav7633/DialoGPT-medium-tony_starkaryanbhosale/DialoGPT-medium-harrypotterasad/DialoGPT-small-harryporter_botashwinchandran13/DialoGPT-small-harrypotterastrobreazy/DialoGPT-small-harrypotteratkh6673/DialoGPT-small-harrypotteratkh6673/DialoGPT-small-trumpatomsspawn/DialoGPT-small-dumbledoreaugustojaba/DialoGPT-small-harrypotteravinashshrangee/DialoGPT-small-Rickyawvik360/DialoGPT-medium-plemonsawvik360/DialoGPT-medium-plemons2awvik360/DialoGPT-small-plemonsaydin/DialoGPT-medium-michaelayush19/rick-sanchezb0shakk/DialoGPT-small-Ragnarbalta/DialoGPT-small-TestBotbanden/DialoGPT-medium-RickBotbanden/DialoGPT-small-LokiBotbeatajackowska/DialoGPT-RickBotbenajtil/DialoGPT-small-Daddybenbenajtil/DialoGPT-small-RickAndMortyScriptsbenjaminbeilharz/dialoGPT-small-empatheticdialogues-generationbenmrtnz27/DialoGPT-small-misatobensuydam/CartmanBotbestminerevah/DialoGPT-small-thetenthdoctorbhaden94/LokiDiscordBot-mediumbhavya689/DialoGPT-large-chandlerbleachybrain/DialoGPT-med-ssbmdonnell/DialoGPT-medium-harrypotterbonebambi/DialoGPT-small-ThakirClonebookemdan/DialoGPT-small-harrypotterboran/berkbotboydster/DialoGPT-small-gollumbrimeggi/testbot2brokentx/newbrokiev2bspans/DialoGPT-small-yodabyeongal/Ko-DialoGPTbypequeno/DialoGPT-small-michaelscottcaps1994/DialoGPT-small-chrisbot-caps1994caps1994/DialoGPT-small-chrisbotcaps1994/DialoGPT-small-harrypotter-caps1994cartyparty/DialoGPT-small-harrypottercartyparty/DialoGPT-small-iteration1cartyparty/DialoGPT-small-nerdherdcedpsam/chatbot_frcenton21/DialoGPT-small-harrypotterchaitrabhat/DialoGPT-small-rickchamindu/DialoGPT-medium-hermionechamodkarunasena/DialoGPT-medium-sokkachan030609/DialoGPT-medium-JABchan030609/DialoGPT-small-JABchellver24/DialoGPT-medium-chizuru_ichinosechip/DialoGPT-small-chizuruthu-coai/blenderbot-400M-esconvclairesb/kindness_botclairesb/kindness_bot_repoclancystudios/DialoGPT-medium-Mortyclayfox/DialoGPT-medium-Hiccupclayfox/DialoGPT-small-Hiccupcocoaclef/DialoGPT-small-kohakucodealtgeek/DiabloGPT-medium-rickmortycolochoplay/DialoGTP-small-harrypotterconniezyj/DialoGPT-small-snapecookirei/DialoGPT-medium-Joreyarcosmic/DialoGPT-Rickcosmicray001/prod-harrycosmicray001/small-harrycrystalgate/DialoGPT-small-rickcumtowndiscord/DialoGPT-small-joshuacutiebunny639/DialoGPT-small-harryd4rk/harrydanildany/DialoGPT-small-MichaelScottdanny481/DialoGPT-small-datnguyenchatbotdanny481/DialoGPT-small-harrypotterdanny481/Final_ChatBotdarkzek/chickenbot-jon-snowdarthboii/DialoGPT-small-PickleRickdarthboii/DialoGPT-small-Rickdats/DialoGPT-small-harrypotterdattam/DialoGPT-medium-TonyStarkBotdead69/GPT-small-yodadeepparag/Aeonadeepparag/DumBot-Betadeepparag/DumBotdelvan/DialoGPT-medium-DwightV1df4rfrrf/DialoGPT-medium-Aerithdhanushlnaik/amySandisdamoe/DialoGPT-small-moedisdamoe/TheGreatManipulatordisdamoe/TheManipulatordivi/Peterbotdk16gaming/DialoGPT-small-HarryPotterdkminer81/Trommdreamline2/DialoGPT-small-joshua-demodukeme/DialoGPT-small-RDBotv1eclare/DialoGPT-small-SCHAEFEReduchav/Austin-DialoGPT-smalleduchav/Elijah-DialoGPT-smalleduchav/J-DialoGPT-smalleduchav/Sam-DialoGPT-smalleklrivera/DialoGPT-small-harrypottereldritch-axolotl/Rickericklasco/DialoGPT-small-erickHarryPotterericzhou/DialoGPT-Medium-Rickericzhou/DialoGPT-Medium-Rick_v2ericzhou/DialoGPT-medium-elonericzhou/tsundere_v1estehpanas/pascalbotethzhou/joobyethzhou/joobyChatethzhou/newJoobyf00d4tehg0dz/Peppaf00d4tehg0dz/Yodafacebook/blenderbot-1B-distillfacebook/blenderbot-3Bfacebook/blenderbot-400M-distillfacebook/blenderbot-90Mfacebook/blenderbot_small-90Mfaketermz/DialoGPTfatemaMeem98/DialoGPT-medium-HermioneGrangerBotfelinecity/DioloGPT-small-KaeyaBotfelinecity/DioloGPT-small-KaeyaBot2felinecity/DioloGPT-small-LisaBotfelinecity/ScaraBotfibruh/DialoGPT-small-harrypotterflakje/DialoGPT-small-Martyflooptherocket/DialogGPT-small-rickftnvir/DialoGPT-medium-bullyMaguiregabtan99/dialogpt-tagalog-medium-10gabtan99/dialogpt-tagalog-medium-20gabtan99/dialogpt-tagalog-medium-30gabtan99/dialogpt-tagalog-mediumgfdream/dialogpt-small-familyguygfdream/dialogpt-small-harrypotterghhostboy/DialoGPT-medium-connorDBH3-1ghhostboy/DialoGPT-medium-connorDBH3-21gizmo-dev/DialoGPT-small-jakegorkemgoknar/gpt2chatbotenglishgrayson124/chatbotwaifugrounddominator/DialoGPT-lar-Rickgusintheshell/DialoGPT-small-rickbotgwima/ryan-sackmotthama/Doctor_Bothama/Harry_Bothama/barney_bothama/me0.01hama/rick_botheabeoun/DiabloGPT-small-nuon-convhenryoce/DialoGPT-small-rick-and-mortyhervetusse/DialogGPT-small-harrypotterhireddivas/DialoGPT-small-rayhireddivas/DialoGPT-small-scullyhireddivas/dialoGPT-small-mulderhireddivas/dialoGPT-small-philhireddivas/dialoGPT-small-sonichonguyenminh/old-zhonglihoussaineamzil/DialoGPT-small-joeyhrv/DialoGPT-small-rick-mortyhyunwoongko/blenderbot-9Bhyunwoongko/reddit-3Bhyunwoongko/reddit-9Biamalpharius/GPT-Small-BenderBotianc89/hagridignkai/DialoGPT-medium-spider-man-updatedilikeapple12/DialoGPT-small-Phosimran2part/DialogGPT-small-Doctorimrit1999/DialoGPT-small-MCUmyynirew/DialoGPT-medium-ettengivmyynirew/DialoGPT-medium-leirbagmyynirew/DialoGPT-small-awazimurukionite/DialoGPT-large-Sh0rtiAI-v2ionite/DialoGPT-medium-IoniteAIionite/DialoGPT-medium-McKayAI-v2ionite/DialoGPT-medium-McKayAIionite/DialoGPT-medium-Sh0rtiAIionite/DialoGPT-medium-mohnjilesAIionite/DialoGPT-medium-orangeAIironman123/DialoGPT-small-harrypotterishraaqparvez/DialoGPT-small-harrypotterjackky46/DialoGPT-medium-gotjahz/DialoGPT-medium-FF8jalensmh/DialoGPT-medium-jalenbotjalensmh/DialoGPT-small-exophoriajamestop00/DialoGPT-spike-mediumjasper/DialoGPT-large-homersimpsonjchen/DialoGPT-evanjeanlks/DialogGPT-small-gayvidjeanlks/DialogGPT-small-patojfhr1999/CharacterTestjogp10/DialoGPT-medium-aryajollmimmim/DialoGPT-small-monkeydluffyjordanhagan/DialoGPT-medium-NegaNetizenjosephmagnayon/DialoGPT-medium-Alfredjosepjulia/RepoHumanChatBotjosh8/DialoGPT-medium-joshjosh8/DialoGPT-small-joshjpsxlr8/DialoGPT-small-harrypotterjth1903/DialoGPT-small-rickjulianolf/DialoGPT-small-harrypotterkaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaot1k/DialoGPT-small-Wandakagennotsuki/DialoGPT-medium-radionkche0138/DialoGPT-medium-DIOkingabzpro/DialoGPT-small-Rick-Botkipiiler/Rickbotknightbat/harry-potterkripanshudixit/DialoGPT-small-phoenixkris/DialoGPT-small-spockkris/DialoGPT-small-spock3kris/DialoGPT-small-spock4kris/DialoGPT-small-spock5kshitiz/testing-bot-repokunalbhargava/DialoGPT-small-housebotkvothe28/DiabloGPT-small-Rickl41n/c3rbslain2/Peterbotlanejm/DialoGPT-small-hagridlapacc33/DialoGPT-medium-ricklife4free96/DialogGPT-med-TeiaMorantalife4free96/DialogGPT-med-TeiaMoranta3light/small-rickklimivan/DialoGPT-small-c3pocosmicroxks/DialoGPT-small-scottlogube/DialogGPT_small_harrypotterlonewanderer27/DialoGPT-small-Joshualonewanderer27/KeitaroBotlonewanderer27/YoshinoriBotlonewanderer27/YuriBotlovellyweather/DialoGPT-medium-johnnyluca-martial/DialoGPT-Elonlucas-bo/DialogGPT-small-yodaludowoods/KujouSaralulueve3/DialoGPT-medium-Kokkorolulueve3/DialoGPT-medium-Kokkoro2madbuda/DialoGPT-got-skippymadbuda/DialoGPT-medium-skippymajonez57/JoeBotmanav/dialogpt-large-kanye-redditmanav/dialogpt-medium-berkeley-redditmaniacGhost24/MichaelScott-bot-push-smallmanraf/DialoGPT-smmall-harrypottermatprado/DialoGPT-small-rick-sanchezmaxxx2021/DialGPT-small-harrypottermdc1616/DialoGPT-large-sherlockmelon422/DialoGPT-medium-MelonBotmelon422/DialoGPT-medium-MelonBot2mewmew/DialoGPT-small-rickmichelleshx/DialoGPT-small-michelle-discord-botmicrosoft/DialoGPT-largemicrosoft/DialoGPT-mediummicrosoft/DialoGPT-smallmikabeebee/Peterbotmilayue/neosh-bot1minsiam/DialoGPT-medium-harrypotterbotminsiam/DialoGPT-small-harrypotterbotmiogfd1234/llmittalnishit/DialoGPT-medium-rickman2mittalnishit/DialoGPT-small-rickmanmjstamper/DialoGPT-small-samwisemk3smo/dialogpt-med-ahirumk3smo/dialogpt-med-duck2mk3smo/dialogpt-med-duck3mk3smo/dialogpt-med-duck5mk3smo/dialogpt-med-duckfinalmk3smo/dialogpt-med-stt3mklucifer/DialoGPT-medium-DEADPOOLmklucifer/DialoGPT-small-DEADPOOLmluengas/DialogGPT-small-michaelscottmodel-mili/DailoGPT-Yukub-v3model-mili/DialoGPT-small-Sapph-v1model-mili/DialoGPT-small-Yukub-v2model-mili/DialoGPT-small-Yukubmohammedks713/DialoGPT-small-harrypottermohammedks713/DialoGPT-small-jonsnowmra1ster/DialoGPT_scully_smallmuhardianab/DialoGPT-small-theofficemunezah/DialoGPT-small-aotmunezah/DialoGPT-small-sherlockmutamuta/DialoGPT-small-rickmutamuta/DialoGPT-spongebob-smallnamanrana16/DialoGPT-small-TrumpBotnanometeres/DialoGPT-medium-halbotnanometeres/DialoGPT-small-halbotncoop57/DiGPTame-mediumniharikadeokar/DialoGPT-small-Jakebotnikhilpatil2532000/DialoGPT-small-harrypotternimrazaheer/DialoGPT-small-harrypotternitishk/IronStarkBotnlokam/DialoGPT-digibot3.0-newnlokam/Digibotnlokam/ada_V.3nlokam/ada_V.6nlokam/ada_V.7nlokam/books_to_bots_v.00noobed/DialoGPT-small-astleynorie4/DialoGPT-small-kyutebotnorie4/DialoGPT-small-memojinot7even/DialoGPT-small-7evenpoolnpc-engine/exported-bart-light-gail-chatbotntjrrvarma/DialoGPT-small-RickBotnwl/DialoGPT-small-enhypennytestalkerq/DialoGPT-medium-joshuaoakkas/Dialge-small-harrypotter-oguzodinmay/joebotodinmay/zackbotmodelogpat123/DialoGPT-small-Michaelogpat23/Jules-Chatbotomkar1309/RickBotomnimokha/DialoGPT-medium-jakeamalomnimokha/DialoGPT-small-jakeamalomnimokha/jakebot2oododo/DialoGPT-small-elonotto-camp/DialoGPT-small-RickBotovergrowth/jokeboyowencubes/DialoGPT-small-Josukepaladinx00/rh-benderparigaswetha/DialoGPT-small-jakeperaltaparthsinha/DialoGPT-small-rickandmortypashin/DialoGPT-small-ironman-2pashin/DialoGPT-small-ironman-3pashin/DialoGPT-small-ironman1pastlecry/DialoGPT-small-harrypotterpeamjo/DialoGPT-small-mortyperson123/DialoGPT-small-petergriffinpewriebontal/DialoGPT-medium-Pewpewbonphantom-deluxe/dialoGPT-RickBotphantom-deluxe/dialoGPT-harryphozon/harry-potter-mediumpiyushdubey/DialoGPT-Mipompeiifreckles/DialoGPT-medium-Rickppn/DialoGPT-small-harrypotterpranavtharoor/testprofessional/DialoGPT-small-joshuaps2102/DialoGPT-small-harrypotterpsblade/DialoGPT-medium-PotterBotpuugz/DialoGPT-small-spidermanqwerty/DialoGPT-small-rickr3cdhummingbird/DialoGPT-medium-joshuar3dhummingbird/DialoGPT-medium-joshuar3dhummingbird/DialoGPT-medium-nekur3dhummingbird/DialoGPT-small-harrypotterr3dhummingbird/DialoGPT-small-nekurachelcorey/DialoGPT-medium-kramerrachelcorey/DialoGPT-medium-nilesrafakat/Botsuana-rickrahul26/DialoGPT-small-rickandmortyrahulMishra05/discord-chat-botraj2002jain/DialoGPT-small-Lightravephelps/DialoGPT-small-MichaelSbottredbloodyknife/DialoGPT-medium-shayorhollings/DialoGPT_small_steverogersrichiellei/Childerichiellei/Childe3richiellei/DialoGPT-small-rickrichielleisart/Childeridwanpratama/DialoGPT-small-misakirinz/DialoGPT-small-Harry-Potterrrrlagusrlagus123/XTC20000rlagusrlagus123/XTC4096rmicheal48/DialoGPT-small-steven_universerodrigodz/DialoGPT-medium-dxdromuNoob/MineromuNoob/testrovai/AIrovai/CARRIErovai/Chat_pytorch1rovai/chatbotmedium1rovai/chatbotmedium2rovai/chatbotmedium3rovai/chatbotmedium4rovai/chatbotonerpeng35/DialoGPT-small-erenyeagerrrtong/DialoGPT-medium-shang-chirsd511/DialoGPT-small-housersedlr/RickBotrsedlr/RickBotExampleruriko/bacquaruriko/konoaquaruriko/konodiosachdevkartik/DialoGPT-small-ricksaintseer121323/DialoGPT-small-kotonohasakai026/Chizurusakai026/Mizuharasam213/DialoGPT-small-harrypottersambotx4/scamanthasamuelssonm/DialoGPT-small-ricksanjanareddy226/JakeBotsankalpjha1/mr.bot_haarysatkinson/DialoGPT-medium-marvinsatkinson/DialoGPT-small-marvinsatvikag/chatbotsatvikag/chatbot2sergunow/movie-chatsetiadia/DialogGPT-small-HPBotshelb-doc/DialoGPT-medium-ashshihab/HarryPottershonuff/DialoGPT-medium-konosubashreeshaaithal/DialoGPT-small-Michael-Scottshreeshaaithal/Discord-AI-botshreeshaaithal/whatsapp-medium-bot-2sidkhuntia/harrypottersifclairhelix/DialoGPT-small-harrypotsimrana5/RickBotExampleskynex/DialoGPT-small-batmanskynex/DialoGPT-small-finalbatmansleekmike/DialoGPT-small-joshuasmilesandtea/DialoGPT-medium-Ricksmmzhu/DialoGPT-small-SZsolfer/DialoGPT-small-ryujispockinese/DialoGPT-small-sherlocksreyanghosh/DialoGPT-medium-jokersrirachasenpai/DialoGPT-medium-harrypottersrv/DialoGPT-medium-Breaking_Badssam/DialoGPT-small-RickmfSanchezssspider/DialoGPT-medium-harrypotterstfuowned/nekstfuowned/ricksthom/DialoGPT-small-tinsudip/bot1sudoabrar/DialoGPT-small-dwightsuhasjain/DailoGPT-small-harrypotterswapnil165/DialoGPT-small-Rickterter/rick-bot-test-v2thatoneguy267/DialoGPT-small-Oscarthatoneguy267/bruhpleasehelpmetheChanChanMan/DialoGPT-small-chandlerthefryingpan/gpt-neo-125M-splishytheiconik/hermione-grangerthesamuelpena/Dialog-medium-Sonicthesamuelpena/Dialog-medium-masterchiefthetlwin/DialoGPT-small-ironmanthinhda/chatbotthu-coai/CDial-GPT2_LCCC-basethu-coai/CDial-GPT_LCCC-basethu-coai/CDial-GPT_LCCC-largeticet11/DialoGPT-small-BOBBYtimslams666/DialoGPT-small-ricktinega/DialoGPT-small-harrypottertngo/DialoGPT-small-HankHilltoiletwater/DialoGPT-medium-ironmantom1804/HPtom1804/HP_lasttom1804/hp_newtomascerejo12/DialoGPT-small-Ricktosin/dialogpt_mwoztosin/dialogpt_svtoyfreak/DialoGPT-small-addytoyfreak/DialoGPT-small-shytpri/DialoGPT-small-patprincessazula/Dialog-GPT-small-AANGtprincessazula/Dialog-GPT-small-KATARA-AVATARtprincessazula/Dialog-GPT-small-SOKKA-AVATARtprincessazula/Dialog-GPT-small-harrypottertransfaeries/DialoGPT-Discordtransfaeries/DialoGPT-medium-Discord-1.0transfaeries/DialoGPT-small-Discord-1.0transfaeries/Twilight-Sparkle-GPTtrig/DialoGPT-small-harrypottertrig/multiverse-secondtrig/multiversetrig/sokka-chatbot-testtrig/tlok-testtroythewar/DialogGPT-small-harrypottertruthisneverlinear/EleventhDoctorttntran/DialoGPT-small-humantuantt/GroundNetughvom/Gingerughvom/britnayBOTMAINumr55766/DialogGPT-small-peppa-pigusamazaheer/DialoGPT-small-harrypotteruutkras/Pandabotuyharold86/DialoGPT-small-RickAndMortyvalarikv/DialoGPT-small-batemanvibranium19/DialoGPT-medium-jakevictordata/DialoGPT-small-Rickvictorswedspot/DialoGPT-small-gandalfvijayv500/DialoGPT-small-Big-Bang-Theory-Series-Transcriptsvijote/DialoGPT-small-Mortyvivek-g-2009/DialoGPT-medium-harrypottervlco-o/NLboto_o-aki-dialogptvlco-o/NLboto_o-small-dialogptwadeed/DialogGPT-small-chandlerbinggwanderer/DialoGPT-small-Phoebewjching/DialoGPT-small-ricksanchezwon/DialoGPT-small-harrypotterworms3401/DialoGPT-small-Eleonoraworsterman/DialoGPT-small-mulderwtrClover/DialoGPT-small-FlutterbotwtrClover/DialoGPT-small-TwilightBotxdmason/pretrainedCasxiaoheiqaq/DialoGPT-mediumJojoxiaoheiqaq/DialoGPT-smallharrypotteryahya1994/DialoGPT-small-AOT-Erenyahya1994/DialoGPT-small-DN-Lyahya1994/DialoGPT-small-DN-Lightyahya1994/DialoGPT-small-DN-Ryukyahya1994/DialoGPT-small-Gintama-Gintokiyahya1994/DialoGPT-small-Parasyte-Migiyahya1994/DialoGPT-small-ReZero-Remyahya1994/DialoGPT-small-ReZero-Subaruyahya1994/DialoGPT-small-Ryukyusufmorsi/georgebotzaydzuhri/lelouch-mediumzemi/jakebotzen-satvik/BotGPT-medium-HPzentos/DialoGPT-small-spongebobzinary/DialoGPT-small-rick-newzuto37/DialoGPT-small-sadaoMaxwere/DiabloGPT-medium-maxbotGrungle/DialoGPT-medium-butterssadkat/technoaiGrungle/DialoGPT-medium-butters2kookyklavicle/sean-diaz-botkookyklavicle/sean-diazAquasp34/DialoGPT-small-aqua1zenham/khemxaryanbhosale/smartharrypotterbotBritain/DialoGPT-small-ZifBotTwoFixedBritain/DialoGPT-small-DanyBotThreeinfinitylyj/DialogGPT-small-rickinfinitylyj/DialogGPT-small-generalinfinitylyj/DialogGPT-medium-generaljackyv/DialoGPT-small-pinocchioFreak55/DialoGPT-small-Phoenix-WrightBritain/DialoGPT-small-DanyBotThreeFixedBritain/DialoGPT-small-DanyBotTwoP4RZ1V4L/DialoGPT-medium-tonystarkBritain/DialoGPT-small-DanyBotTwoNewzenham/mskeen_m_e4_16hzenham/khemx_m_e4_16hzenham/wail_m_e4_16h_2kRTM/vilangBeanBoi50404/DialoGPT-small-PeppaPigButBetternabin19677/small-cartmanPrime2911/DialoGPT-small-handsomejackStarry/KARENTRIESdietconk/DialogGPT-small-Orangemafeu/DialoGPT-medium-willemPrime2911/DialoGPT-medium-handsomejackMeowren/DialoGPT-small-Rick-BotDB13067/PeterbotSavitar/DialoGPT-medium-RickandMortyMolePatrol/Olboterinchocolate/DialoGPT-small-harrypotterValouzze/FairuvenIAMehSatho/Tai-medium-HermioneValouzze/MegaIAMakinitas/DialoGPT-small-RickAndMortyScriptsdarthrussel/DialoGPT-small-rickandmortyvanilladucky/Friends_chatting_botvanilladucky/Friends_chatting_bot_redefinedchocoduck/Joey_botduanxingjuan/DialoGPT-medium-DEMON_SLAYERpinkducky/Monica_BotStarry/HELLORUKASpinkducky/Rachel_Bottrig/multiverse-thirdpinkducky/Ross_Botduanxingjuan/DialoGPT-large-DEMON_SLAYER_v1duanxingjuan/DialoGPT-large-DEMONduanxingjuan/DialoGPT-large-DEMON1issue89/DialoGPT-small-houseLeonLi279/DialoGPT-small-harrypotterMolePatrol/DialoGPT-Medium-ConnerBotMolePatrol/DialoGPT-Medium-MoleBotTheDaydreamer/rickyBeamBee/DialoGPT-small-LavenzaGarsic/DialoGPT-medium-pecorineCallForEcho/DialoGPT-small-harrypotterBeamBee/DialoGPT-small-LavenzaNumTwoMeowren/MichaelScottBottshalpin87/dialoGPT-homer-simpsondarthrussel/DialoGPT-small-homerbot-halfdataTheGoldenToaster/DialoGPT-medium-Woodybemich/DialoGPT-small-GeorgeCostanzaAAAA-4/DialoGPT-small-player_03Teyronebigdick/DialoGPT-small-harrypotterSammith/DialoGPT-small-miachaelNxtxn01/DialoGPT-small-harrypotterTeyronebigdick/DialoGPT-small-terrydavismczolly/DialoGPT-small-the-doctorcrazypegasus/GPT-JonSnowMrYiRen/DialoGPT-small-harrypotterTropicalJuice/Dialog-PeterGriffinTheGoldenToaster/DialoGPT-medium-BotMrYiRen/DialoGPT-small-harrypotter2gulgulglut/DialoGPT-small-Ricktrev/DialoGPT-small-MLPRAJESHNEMANI/Chatbot_AIlilapapazian/DialoGPT-small-harrypotterAlethea/GPT2-chitchatflorentiino/DialoGPT-small-harrypotterNUTELEX/Evajessicammow/DialoGPT-small-ronswansonMrYiRen/DialoGPT-small-ZCjessicammow/DialoGPT-medium-leslieknopeAmbricJohnson5888/deathAmbricJohnson5888/clauraDarrellTimothy/DialoGPT-small-harrypotterRarePizzaDog/Apes_Botiyedr8/DialoGPT-small-rickMEDT/ChatBotNonzeroCornet34/DialoGPT-small-hansoloNonzeroCornet34/DialoGPT-small-philbotatomsspawn/DialoGPT-medium-dumbledoreflorentiino/DialoGPT-small-rickShibaDeveloper/DialoGPT-small-harrypottersahilnare78/DialogGPT-medium-harrypotterGarsic/DialoGPT-medium-jillmdm/DialoGPT-small-KanyeScyKindness/Hatsune_Mikuaaaacash/DialoGPT-large-michaelscottAntoDono/DialoGPT-HarryBFMeriem/modelBFMeriem/chatbot-modelStringCheese/Dialog-small-bigbangjakewillms17/capcake-modelShivierra/DialoGPT-small-technobladeScaprod/DialoGPT-small-arbiterTlacaelel/DialoGPT-small-jarvisspuun/kekbot-beta-1Coma/BeterWavepaw/DialoGPT-medium-WardenIngoAkarsh3053/potter-chat-botMachineBabs/RickBotMachineBabs/DocBrownspuun/kekbot-beta-1-mediumMEDT/Chatbot_Mediumtosin/dialogpt_mwoz_idiomstosin/dialogpt_afriwoz_wolofaakhilv/tonystarkspuun/kekbot-beta-2-mediumxiaoGato/DialoGPT-small-villanelleJonesy/DialoGPT-small_FGdeathknight67/DialoGPT-medium-joshuakyriinx/DialoGPT-small-glyphJonesy/DialoGPT-medium_FGspuun/kekbot-beta-3-mediumLisia/DialoGPT-small-connorawvik360/DialoGPT-medium-plemons-04262022Jonesy/LisaOnIcekvnaraya/DialoGPT-small-michaelHyperspace/DialoGPT-small-HyperdriveAzuris/DialoGPT-medium-ekidonaaditeyabaral/sonoboisJonesy/HomersNightOutAndrei0086/Chat-small-botawvik360/UncleRuckuscaptainswiftfox/rickandmortyradicalrascal/DialoGPT-medium-jimmydmoz47/DialoGPT-small-peterparkerniprestige/GPT-small-DusabeBotShakerlicious/DialoGPT-small-descentbotatomsspawn/DialoGPT-small-shelbotatomsspawn/DialoGPT-small-sheldonWillow/DialoGPT-medium-willowIsekaiMeta/dapprffarjvr/DialoGPT-small-MortyfarInSaiyan/DialoGPT-small-harrypotterIsekaiMeta/dapprf3emolyscheisse/DialoGPT-small-mandybotIsekaiMeta/dapprf4qgdmonilla/DialoGPT-small-harrypotterNHStudios/DialoGPT-small-jakeShakerlicious/DialoGPT-small-raquelbotannasham/DialoGPT-small-myneighborTotoroCaptAdorable/RickBotWillow/DialoGPT-large-willowKabutopusu/DialoGPT-medium-NITWMaeHarmlessTarget/DialoGPT-medium-Bendersoni69/DialoGPT-medium-holmescaptainswiftfox/DialoGPT-small-rickkathywu/DialoGPT-small-kathymybot/DialoGPT-medium-harrypotterDedemg1988/DialoGPT-small-michaelscottpedrobaiainin/DialoGPT-small-harrypotterkathywu/DialoGPT-medium-kathySNCannon/DialoGPT-medium-mercTHE-DDLM/DialoGPT-sebastianfatirali/DialoGPT-medium-harrypotterTejasARathod/DialoGPT-medium-BatmanBotVarick/dialo-jarvisRobinsd/HarryBotdipstheman/DialoGPT-small-humanconversationdipstheman/DialoGPT-small-humanconversationpartLinkTheSinger/DialoGPT-small-KannaLinkTheSinger/DialoGPT-small-Kannav4Robinsd/HarryBot4SomeRandomGuy/tonyMeowren/HumanBotmarcoperez/DialoGPT-small-rickandmortyLarsBell/DialoGPT-small-billyloomisokwach/mawaidhaChatbotLooksLikeIveLost/DialoGPT-medium-meokwach/mawaidhaChatbot2thebyy/DialoGPT-small-mortyisarickrongina/DialoGPT-small-cartmanfransoa/arrombado-dmsionite/DialoGPT-medium-MarkAIddrmaster1000/DialoGPT-medium-rickPeritusDux/DialoGPT-small-rickHomerChatbot/HomerSimpsont8oo/DialoGPT-small-zenit8oo/DialoGPT-small-zenigatasexomq/DialoGPT-medium-TeoBotChar135/DialoGPT-medium-sebastianHomerChatbot/DialoGPT-small-HomerSimpsontrev/Twilight-Sparklegigikenneth/family-guy-botulises801/DialoGPT-medium-rickfujuta/DialoGPT-medium-HarryPotterfujuta/DialoGPT-medium-RonWeasleyfujuta/DialoGPT-medium-HermioneGranderdeepparag/Aeona-BetaHomerChatbot/DialoGPT-small-homersimpsonbotredcy/FrasierBotv1ElMuchoDingDong/DialoGPT-medium-AudreyHepburnnatdon/DialoGPT_Michael_ScottElMuchoDingDong/DialoGPT-medium-AudreyHepburn_v3deathmite/DiabloGPT-small-potaruElMuchoDingDong/DialoGPT-medium-AudreyHepburn_v4DaBaap/Chat-Bot-BatmanIwa/botbadlawyer/DialoGPT-medium-sherlock-botthanhchauns2/DialoGPT-medium-Lunajayklaws0606/DialoGPT-small-jayBotRUCAIBox/mvpFlem/DialoGPT-medium-alastorkeans/DialoGPT-small-highjackerjayklaws0606/dgpt-small-jaybotCodeMaestro/DialoGPT-small-TChallaElMuchoDingDong/AudreyBotBlenderBotstfuowned/rickfinalDuskSigma/DialogGPTHomerSimpsonhireddivas/dialoGPT-small-sonic2N0NAne/DialoGPT-small-harrypottertinkoff-ai/response-quality-classifier-tinytinkoff-ai/response-quality-classifier-basetinkoff-ai/response-quality-classifier-largetinkoff-ai/response-toxicity-classifier-baseRUCAIBox/mvp-open-dialogRUCAIBox/mtl-open-dialogRUCAIBox/mvp-multi-taskCirilaron/DialoGPT-medium-raidenBlackSamorez/rudialogpt3_medium_based_on_gpt2_2chlucataco/DialogGPT-med-Ricklucataco/DialoGPT-medium-rafagloomyworm/DialoGPT-small-orthokozlovtsev/DialoGPT-medium-harrypotterCirilaron/DialoGPT-medium-jetstreamsamlucataco/DialoGPT-medium-omarlucataco/DialoGPT-medium-milodaedalus2003/HouseBotSallyXue/DialoGPT-small-harrypotterAverium/DialoGPT-medium-TailsBotnlokam99/ada_samplenlokam99/ada_sample_2nlokam99/ada_sample_3nlokam/adanimals_V1spuun/kekbot-beta-4-mediumquirkys/DialoGPT-small-harrypottermarkofhope/DialoGPT-medium-HarringtonBotAntoDono/DialoGPT-Bopy-Alpha-1.01Hermite/DialoGPT-large-hermiterobinhad/gpt2-uk-conversationalBrowbon/DialoGPT-small-LucaChangrettagloomyworm/DialoGPT-medium-orthoBrowbon/DialoGPT-medium-LucaChangrettaFluffypillow/DialoGPT-small-RemHermite/DialoGPT-large-hermite2Bman/DialoGPT-medium-peppapigZipperXYZ/DialoGPT-medium-TheWorldMachineAlyxTheKitten/DialoGPT-medium-AgedBlaine-2Averium/DialoGPT-medium-TailsBot1.1Elijah629/DialoGPT-mrsanaiZipperXYZ/DialoGPT-medium-TheWorldMachine2damianruel/DialoGPT-medium-MySonZipperXYZ/DialoGPT-medium-TheWorldMachineExpressiveElijah629/DialoGPT-shrekAlyxTheKitten/DialoGPT-medium-Jimmis-2dennis-fast/DialoGPT-ElonMuskSealgair/DialoGPT-medium-Eydencrystallyzing/DialoGPT-small-nishikiyamacrystallyzing/DialoGPT-small-kiryuNikkiTiredAf/DialoGPT-small-billy2Evokus/DialoGPT-small-harrypottermcimmy/DialoGPT-small-bobLaggrif/DialoGPT-medium-LukeLaggrif/DialoGPT-medium-3POZipperXYZ/DialoGPT-medium-TheWorldMachineExpressive2prprakash/DialoGPT-small-TonyStarksexomq/TeoBot-Romanian-mediumBman/DialoGPT-medium-doraHermite/DialoGPT-large-hermite3Averium/FabioBotarem/DialoGPT-medium-rickandmortysoProf1998/DialoGPT-small-chattyricksoProf1998/DialoGPT-medium-chattyrickDorin/DialoGPT-small-RickOptimalHoiboy/DialoGPT-small-kasumaiHartmann/DialoGPT-small-koishikomeijiKonbai/DialoGPT-small-akagiKonbai/DialoGPT-small-akagi2JazzyLucas/DialoGPT-small-TonyStarkmystery/DialoGPT-small-pinkiepiesexomq/TeoBot-Romanian-medium2erikycd/chatbot_haditainfinix/Sheldon-botJamesonSpiff/chatBot_test_modelAkito1961/DialoGPT-small-C3PONaturealbe/DialoGPT-small-TechnobladezR0clu/DialoGPT-medium-Mr.Robotoreso/DialoGPT-medium-v3gatrimox/tryingnewstuffNakul24/YC_Botcasperthegazer/DiabloGPT-medium-lukedotJamesStratford/PLord-bot-DialoGPT-mediumCaptPyrite/DialoGPT-small-catSafeTorpedo/DialoGPT-small-MichaelBotbrianveebee/DialoGPT-medium-bendermyynirew/DialoGPT-medium-shouko01myynirew/2-0OKUOHSsmmzhu/DialoGPT-medium-sammyynirew/shouko0-3myynirew/dumbbotLamia/DialoGPT-small-Sundropashtrindade/chatbot-staceytinkoff-ai/ruDialoGPT-smalltinkoff-ai/ruDialoGPT-medium24adamaliv/DialoGPT-medium-Willcybertelx/DialoGPT-small-drunkic0nRick-C137/DialoGPT-small-rickdebyve/dumbbotAmir-UL/JimBotBoxCrab/DialoGPT-small-StriderAbdalK25/DialoGPT-small-TheWiseBotcasperthegazer/DialoGT-gandalf-urdotpineappleSoup/DialoGPT-medium-707Nakul24/AD_ChatBotTeaTM/DialoGPT-small-bushcationite/DialoGPT-medium-NakaAICreepton/DDLCYuri-DialoGPT-smallTeaTM/DialoGPT-large-bushcatyazinga/DialoGPT-medium-scoutthrowaway112358112358/DialoGPT-medium-scriptJingna/test_hpv_discordanonchickenlegs/sartoshi-botxander-cross/DialoGPT-small-EvilMortyTheBotBman/DialoGPT-medium-shrekYank2901/DialoGPT-small-Rickakshatpandeyme/DialoGPT-small-manpreetJenwvwmabskvwh/DialoGPT-small-josh444akshatpandeyme/DialoGPT-small-parthivakshatpandeyme/DialoGPT-small-ParthivBotseeksery/DialoGPT-caligakshatpandeyme/DialoGPT-small-AnyaBotJordine/shittermodel-attribution-challenge/DialoGPT-largeseeksery/DialoGPT-calig2obl1t/DialoGPT-medium-Jotarotrickstters/DialoGPT-small-evanbottrickstters/evanbot-gptAriakimTaiyo/gpt2-chatYank2901/DialoGPT-small-Harrylizz27/DialoGPT-small-baymaxobl1t/DialoGPT-medium-Jolyneseeksery/DialoGPT-calig3Jenwvwmabskvwh/DialoGPT-small-josh445trickstters/evbot2Jenwvwmabskvwh/DialoGPT-small-josh450lizz27/DialoGPT-medium-BaymaxBotsoop/DialoGPT-medium-BaymaxBotabelblue3/DialoGPT-medium-baymaxpriyankac/DialoGPT-medium-BaymaxBotIronpanther1/Testingtosin/dialogpt_afriwoz_pidginAnon25/DialoGPT-Medium-BaymaxBotGoldenRedstone/DialoGPT-medium-Phoenix-WrightPrimobot/DialoGPT-small-harrypotterLyem/LyemBotv1JamesSantosxx/DialoGPT-small-harrypotterLyem/LyemBotv2Ironpanther1/ArtoriaBotSwervin7s/DialoGPT-medium-anakinDogH2O/DialoGPT-small-narutoNoPeanuts/DialoGPT-small-poGravitygaming/homeraiLyem/LyemBotv3celine45688/LuTingantwortemir/shouko04SebastianS/MetalSebastiannotaproblem00/DialoGPT-small-bakugoumyodoctor/DIALOGPT-medium-HarryPotterBotaniketface/DialoGPT-medium-elonnoiseBase/DialoGPT-small-HarryPotterkaran21/DialoGPT-medium-rickandmortykaran21/DialoGPT-medium-guinSophiejs/DialoGPT-small-BlaineBotskouras/DialoGPT-small-swdaskouras/DialoGPT-small-maptaskTheodoreAinsley/LindaGoldAlbedoAI/DialoGPT-large-AlbedoAlbedoAI/DialoGPT-large-Albedo2willmay/DialoGPT-medium-willAlbedoAI/DialoGPT-medium-Albedochulainn/DialoGPT-medium-Zukoctoner2653/DialoGPT-medium-RickBotyNumber4/DialoGPT-medium-harrypotteryummyhat/DialoGPT-small-spikeEllyPony/flutterbotSuryansh-23/DialoGPT-small-MichaelScottOfficeCirilaron/DialoGPT-medium-vergilIzuuk/izuukshungyan/Diablo-small-harrypotterbhavyasharma/DialoGPT-small-harrypotternintwentydo/rickbottylersfoot/DialoGPT-medium-rickEJoftheVern/DialoGPT-medium-shaggyxtraXpert/DialoGPT-small-RickAndMorty2ANIKEThash/DialoGPT-medium-characterNoonw/DialoGPT-small-hijackersexurmomfat32man/elon_answersMinhP/DialoGPT-small-themisNoonw/DialoGPT-small-osamaflyplaneNoonw/DialoGPT-small-ladenflyplaneNoonw/DialoGPT-small-ladenonjetMinhP/DialoGPT-small-francoKaran59/DialoGPT-small-evaModelmarblyso/DialoGPT-medium-marblesbagelJojo17/DialoGPT-small-RickAndMortydeseipel/medium-LucyClarke_DiscordBackup/model0000SirSpiffy/IvanModelwoodmtaylor/DialoGPT-small-Heejwoodmtaylor/DialoGPT-medium-HeejOctaviusI/marisaV0ChloeMJM/DialoGPT-small-rickJDesignEra/DialoGPT-small-AnyaMrE/DialoGPT-medium-SARGER4aarya-c111/DialoGPT-small-Rogersbozlucas/DialoGPT-medium-HermioneBotLasseVKP/DialoGPT-Mogensmetaloopa/DialoGPT-medium-Rintaroingen51/DialoGPT-medium-GPT4Divyesh/DialoGPT-medium-harrypotterNatsuki-Chan/DialoGPT-medium-luzakira2001/DialoGPT-medium-harrypotterosueng02/DialoGPT-small-STAN_BOTosueng02/DialoGPT-medium-STAN_BOTwormed/DialoGPT-small-denaiRehanP123/DialoGPT-medium-kermit.oldNakul24/SM_Botchulainn/DialoGPT-medium-Ragnaraniketface/DialoGPT-productshohanursobuj/DialoGPTmarblyso/DialoGPT-medium-heromarblyso/DialoGPT-medium-kelmarblyso/DialoGPT-medium-aubreyakil191/small-test-harryakakakakasanpellegrino/CoryBotArqhero/DialoGPT-small-adventuretimechulainn/DialoGPT-medium-TyrionVTG/MentalHealthChatbotv1luminolblue/HomunculusGPT-testbotPaulina354/DialoGPT-small-rickandmortykhuranagarvit019/MentalHealthChatbotVirtualizedTrash/Chatbotpedrocaribe/DialoGPT-medium-LLqueenaccila/DialoGPT-small-kashiwagiGarfExit/DialogGPT-medium-707marblyso/DialoGPT-medium-shepherdSpectre29/DialoGPT-small-KaisaSpectre29/Kaisa-converse-modelZedTheUndead/Rick_fragmentmarblyso/DialoGPT-medium-mariDelicious/DialoGPT-small-harrypotterBBHKR/DialoGPT-small-jacksparrowGuwon/DialoGPT-small-Quincyepeicher/DialoGPT-small-homer-2timmychanga/DialoGPT-small-ashleymywateriswet/ShuanBotepeicher/DialoGPT-small-flandersSuper-McTea/DialoGPT-small-McTeaEronzin/meuBotzindoEronTechdra/DialoGPT-large-theboyEronzin/DialoGPT-small-Frodogtgillott/gibAwesomeDWNJ/EmiBotCJ3/DialoGPT-medium-amber3GamerMan02/DialoGPT-medium-gamerbot2GamerMan02/DialoGPT-medium-gamerbot1Insomnic/DialoGPT-small-harrypotterSuper-McTea/DialoGPT-small-McTeaV2FelipeJoazeiro/chatbot-mortymicrosoft/GODEL-v1_1-base-seq2seqmicrosoft/GODEL-v1_1-large-seq2seqRencist/DialoGPT-small-rickscorpiofrens/DialoGPT-medium-ergonsomemusicnerdwoops/DialoGPT-small-shadowpowchang/DialoGPT2-medium-CAiFEratneshrt/DialoGPT-small-Articosomemusicnerdwoops/DialoGPT-distilgpt2-sonicfandubTsec-Research/DialoGPT-chandler-pennyneonon/DialoGPT-medium-cloyddae208s/DialoGPT-small-dimitrimossfarmer/VRANAKMatax/Aristrathor3000brownanchovy/HarryOverlrd/DialoGPT-small-cartmanepeicher/DialoGPT-large-homercomradesocrates/DialoGPT-medium-strangerRakublu/DialoGPT-small-yasuoneonon/DialoGPT-medium-htcccAlt41r/gpt-simpsonNimit-Jjw/DialoGPT-chandler-pennyQuoc123/DialoGPT-small-AQUAmarblyso/DialoGPT-medium-pearlestus2/rick-superu-rick2marblyso/DialoGPT-medium-marinarovenmusic/DialoGPT-small-melodybotdeseipel/small-LucyClarke_rovenmusic/DialoGPT-small-melodybotv2rovenmusic/DialoGPT-small-melodybotv3epeicher/DialoGPT-medium-homerandrewkroening/GalaxyFarAway-DialoGPT-HanSolonams/nams-botNicktherat/DialoGPT-medium-endellaalfirsaafauzulh/DialoGPT-small-KamuiBastionrovenmusic/DialoGPT-small-melodyv10somesh212/Harry_Potter-BOTsomesh212/Harry_Potter_botDialoGPT_Som2jmagine/DialoGPT-small-metaheadsomesh212/Harry_Potter_botDialoGPT_Som3rovenmusic/DialoGPT-small-melodyvfinaljmagine/DialoGPT-small-jmaginejmagine/DialoGPT-small-fundedjmagine/DialoGPT-small-jimjandrewkroening/GalaxyFarAway-DialoGPT-LukeSkywalkerandrewkroening/GalaxyFarAway-DialoGPT-Threepioandrewkroening/GalaxyFarAway-DialoGPT-Vaderandrewkroening/GalaxyFarAway-DialoGPT-LeiaOrganaandrewkroening/GalaxyFarAway-DialoGPT-YodaWizardd/DialoGPT-small-sheldonBenKJH/DialoGPT-small-lucybotasgAnanjas/AwooAIAnanjas/AwooV2kookyklavicle/gpt-sean-diazkookyklavicle/SeanDiazBot2Ananjas/AwooV3Overlrd/DialoGPT-medium-cartmanAnanjas/AwooV6mathecas/HarryPotterBotAIKarina256/DialoGPT-small-doryTony8657/DialoGPT-small-TonyStarkBotSebastianS/my_mimTFS668/DialoGPT-small-Rickredhoff/DialoGPT-Medium-RedBotFeriVOQ/DialoGPT-small-joshuaTriobloid/DialoGPT-small-lianaharrypotterquinnzie/DialoGPT-small-sinisterFarziBuilder/DialoGPT-medium-harrypottersohampatil/DialoGPT-small-mentalchatbotgtkarber/DialoGPT-medium-columboPaddlePaddle/plato-miniJunkan/DialoGPT-medium-BilboThatSkyFox/DialoGPT-medium-whatsappAr4ikov/DialogAgentGPT2reallygoodtechdeals/Bingocat-ai-Dialo-GPT-mediumthmauler/crashedOptionaI/DialoGPT-small-beepboopydavebathhews/DialoGPT-OTISGGOM/SipBotGGOMdavebathhews/DialoGPT-OTISBOTGGOM/WillBotGGOMGGOM/ElyasBotGGOMreallygoodtechdeals/steve-ai-Dialo-GPT-mediumCrushtoe/DialoGPT-small-vanglussapotempest/DialoGPT-medium-geraltDiogoSabec/DialoGPT-small-joshuaWaleedArif/DialoGPT-small-MichealCrushtoe/DialoGPT-medium-vanglussCrushtoe/GODEL-v1_1-base-seq2seq-vanglussDiogoSabec/BOTLe033/DialoGPT-small-rickmortyFilosofas/DialoGPT-medium-PALPATINE2JadansTower/jobotNTMNathan/DialoGPT-small-harrypotterAshypaws/DialoGPT-medium-Ashybotwmdosborne/DialoGPT-medium-kyritebotworms3402/DialoGPT-small-automata2Pi3141/DialoGPT-small-elonGrendar/Dialo-GPT-medium-shiroPi3141/DialoGPT-medium-elonPi3141/DialoGPT-medium-elon-2JoshuaPawlik/DialoGPT-medium-joshuaPi3141/DialoGPT-medium-elon-3josephthen3320/DialoGPT-small-walterrobbiegwald/RickGurtej/DrbotHereward/DialoGPT_medium_ObiWan_KenobiGiu888/DialoGPT-small-saoGrendar/blenderbot-400M-distill-Shirokeeg8/Book-0-1500keeg8/Book-1500-1700keeg8/Book-1850-1900keeg8/Book-1700-1850karlreimond/DialoGPT-small-harrypotterlenartlola/SpongeBoblenartlola/rick-botDeedlit/DialoGPT-small-southparkbabylasagne/DialoGPT-small-narryutobabylasagne/DialoGPT-small-harrybabylasagne/DialoGPT-small-spiderbabylasagne/DialoGPT-small-batmanBradHeffernan/rickNmortyModelUmUDev/DialoGPT-medium-AlexVNukikunz/gas-kenji-mediumukikunz/gas-kenjiIsokeel/DialoGPT-medium-KMbotKakoSi/AcciGPT-smolSpoofed/DiabloGPT-small-petersophiadt/DialoGPT-medium-707UmUDev/DialoGPT-medium-AlexPygmalionAI/pygmalion-350msophiadt/DialoGPT-medium-reigenrexfi/DialoGPT-small-peterrexfi/NafezBot-DialoGPTcaps1994/chris-botrexfi/RickyBotallenai/cosmo-xlwoodmtaylor/DialoGPT-large-Dumplingrexfi/MikeScottBotapfallinus/RickBotapfallinus/HarryBotapfallinus/MedBotapfallinus/AeonaBotapfallinus/BatmanBotapfallinus/AiBotLostXOR/TotallyNotARobotgachaddict/DialoGPT-medium-ikeOctaviusI/stagingPygmalionAI/pygmalion-1.3bTerrymir/DialoGPT-medium-SorakaSantiPingui58/DialoGPT-small-hikass1612/montana-chatMrEmpty/DialoGPT-small-rickandmortyshikiskhakis/DialoGPT-small-blackdoomalexandreteles/GPTChizuruChae/scottbot_medAhmedMostafa/DialoGPT-small-Rickmetkoon/30dollarceoDinocroth/DialoGPT-medium-Trevor-PhilipsV2metkoon/MatBotSmallQ/DialoGPT-small-Anyabigbossa/aiko6GK123/DialoGPT-medium-hanbotTheHappyDrone/DialoGPT-medium-salesmanPcik/DialoGPT-medium-JaidenTheHappyDrone/DialoGPT-medium-Nexus-NovaPcik/DialoGPT-medium-DanteAlmightyDeathCheater/DialoGPT-medium-harrypotterPcik/DialoGPT-medium-KirbyStarry/COUNTNARCTheHappyDrone/DialoGPT-medium-Nexus-Nova-turing-v2wetwoteraq/DialoGPT-medium-aquawetwoteraq/DialoGPT-small-peterwetwoteraq/DialoGPT-medium-peterlilexo2/DialoGPT-medium-Monicamomo10/DialoGPT-small-harryPotterAntale123/ConorBotshikiskhakis/DialoGPT-small-xemnasEcook/DialoGPT-medium-EcookPygmalionAI/pygmalion-2.7bFowlerF/DiscordChatBotJoeRoganfan-69420/DialoGPT-medium-HarryPotterbotdusty310/DialoGPT-medium-MisakiGurtej/Drbot2Gurtej/Drbot3Gurtej/Drbot4Gurtej/Drbot5Gurtej/Drbot6Gurtej/Drbot7Gurtej/Drbot8Gurtej/Drbot9PygmalionAI/pygmalion-6bGurtej/Drbot11navygup/Mood-TrackerMaraslumunnus/DialoGPT-small-ivernDAS9051/BatemanChatBotSmallQLALA/DialoGPT-small-AnyaRinkaDev/GPT-Peppa-Pigthu-coai/blenderbot-1B-augescsiyaT/DialoGPT-harrypotter-smallkeircare/DialoGPT-small-RickSanchezshiiiroe/DialoGPT-medium-kiritojdakillah/Rickkielljoy/DialoGPT-small-stupidspecialkayAshypaws/DialoGPT-medium-Kitaibotjdakillah/RICK-V2jdakillah/Benderjdakillah/Generalbotkielljoy/DialoGPT-medium-ryanbotemre/spanish-dialoGPTvuminhtue/DialoGPT-large-HarryPotter3ralphsorz/DialoGPT-small-samwiseSumYin/DialoGPT-small-HomerJamesRoy/DGPT-DCBlizzchor/DialoGPT-medium-HarryBottergjhghjk/rickgjhghjk/rick2SumYin/ZeroTwo-Medium-DialoGPTBlizzchor/DialoGPT-medium-gamoraMydia2/DialoGPT-small-FlonnealiveAL-CT/DialoGPT-small-slayerDhruvShek/Webraft-Aiarno2077/DiabloGPT-small-harrypotterkeyonecs/fourept-debique-gptBlizzchor/DialoGPT-medium-QuillLordcallmeclover/Stinger-CONVRS_MODLaminFelah/DialogueGPT-very-small-harryPotterKeijuro/aeris-dialogptAbdelrahman853/DialoGPT-small-echoBearfoot/DialoGPT-medium-shrekarthme2/jayarthme2/DialoGPT-medium-Jay42meow/DialoGPT-medium-42meowPeeepy/EvieHorniFolks/Unicornwaifu-workshop/pygmalion-6bagenttylostudios/DialoGPT-small-BocchiGregariousJamie/DialoGPT-small-jamieFuwaguwa/DialoGPT-Medium-AzurLaneMusashi-v8s3nh/DialoGPT-large-Ricks3nh/DialoGPT-large-Mortys3nh/DialoGPT-small-mortyGivinghawk/GPT-MortyDhruvShek/swearbotgrart/DialoGPT-small-gillioninterpixle/Sir_Caladans3nh/DialoGPT-tony-montanas3nh/DialoGPT-small-harry-potter-goblet-of-fires3nh/DialoGPT-small-hermione-granger-goblet-of-fires3nh/DialoGPT-small-woody-toy-storys3nh/DialoGPT-small-buzz-toy-storypuj0/DialoGPT-small-joshuajulianvd49/DialoGPT-medium-EllieBotSreyas/DialoGPT-small-elitDiscordRequestsAPI/DialoGPT-medium-NurDeepsMarinHinawa/DialoGPT-medium-Enepolandball/polanballwhoami24142/DialoGPT-small-padilhaDiscordRequestsAPI/NurDeeps-BotVaibhav-rm/GPT2-Shri-v1chrisrowles/DialoGPT-small-chrisrowlesespeon98/DialoGPT-kenny-botespeon98/DialoGPT-kenny-bot-2polandball/GPT-Polenchrisrowles/DialoGPT-medium-chrisrowlesDiscordRequestsAPI/NurDeeps-Bot-2steerevo88/DialoGPT-small-baikenakiFQC/japanese-dialogpt-small-aozoraNgao/DialoGPT-small-ngaoMineroero/DialoGPT-medium-M4SOPMODsimple2312/DialoGPT-nayeonnemowet88/DialoGPT-small-ricktestAbraxas3d/housevampiregirl/DialoGPT-medium-lennoxramaisingapore/coherence-momentumsimple2312/DialoGPT-Elliesimple2312/DialoGPT-Twicetestaws/DialoGPT-small-joshuanemowet88/output-pythia-testGurtej/Drbot12Gurtej/Drbot13Gurtej/Drbot14Gurtej/Drbot16EZSNoVa/DialogGPT-medium-NoVamattallio/Archivist-medium-dialoGPTrlatt/DialoGPT-small-RickSanchezLyforth/DialoGPT-Medium-Maribellekittenwhiperer/DeadpoolKumquatJoe/DialoGPT-medium-MaleToucherBotlmkhoa/GODEL_base_modelJamesStratford/Pidrow-bot-DialoGPT-Large-Feb2023LrxLcs/DialogGPT2-SMALDelcos/internal_chat_model_e2euvu/DialoGPT-small-harrypotterLrxLcs/GPT2-V2LrxLcs/GPT2-Testeuvu/euvu-rickbotWeeeeeeeeeeeee00/DialoGPT-small-harrypotterslyslasher24/DialoGPT-Medium-Pondweedslyslasher24/DialoGPT-Small-Pondweedbradydawg/AI-Bot2aisingapore/rumour-detection-twitterRatInChat/Pilup7575rlatt/DialoGPT-large-RickSanchezKira225784/Klarabot-testbigbossa/DialoGPT-small-aikogirlsckova/DialoGPT-small-joshuasckova/DialoGPT-medium-joshuasckova/DialoGPT-mediumBeltenebros/DialoGPT-small-PerionOfGaulByteno/DialoGPT-medium-glamrockfreddyaudreycl/audreycl-testagainaisingapore/Lif3WayApaudreycl/DialoGPT-RoyalPurpleFishaudreycl/DialoGPT-RPFAxelajs26/DialoGPT-small-alicetendouNoohance/DialoGPT-medium-noohbotDraptor/DialoGPT-small-coolcoDavid042/DialoGPT-LucasBotHobospider132/DialoGPT-Mahiru-ProtoDraptor/DialoGPT-medium-motoaisingapore/SPANBertJYBX/DialoGPT-small-PennyJYBX/DialoGPT-small-Pennybotaisingapore/RoBERTa-baseJYBX/DialoGPT-small-AmybotLuckyBor11/FigureFlyingGrayson0304/Gandalf-stupid-versionBlinksFly/Harry_Potter-AiPhilipN/DialoGPT-small-KeqingBotYTTD/DialoGPT-medium-souPhilipN/DialoGPT-large-KeqingBotYTTD/DialoGPT-medium-souv2keonju/chat_botMysteriousAmazon/DialoGPT-medium-alastormICHPl/MINI_AIrlatt/DialoGPT-large-King-James-Bible-testv3nom1704/DialoGPT-small-potterbotTechcs002/DialoGPT-medium-AboTalkTestMysteriousAmazon/DialoGPT-medium-freddyICAMPB204/DialoGPT-small-HarryPotterkelvinhang/DialoGPT-medium-badguytatsumis6/MonikaAIkennethhendricks/DialoGPT-medium-PowPowGaming-Gen1rlatt/DialoGPT-large-King-James-Bible-test-accuratekennethhendricks/DialoGPT-medium-PowPowGamingkelvinhang/DialoGPT-medium-badguy2zami0011/qqpbksdjvladiyudi/Morty-dataRazaK18/DialoGPT-small-harrypottercomradesocrates/DialoGPT-large-iokelvinhang/DialoGPT-medium-okakoroMonchic/chatwithkanizami0011/rickdickCallMeJeremy/DialoGPT-medium-THREEPIOLeomas/DialoGPT-medium-LeomasRehanP123/DialoGPT-large-kermitshahules786/Safetybot-T5-basehuolongguo10/CDial-GPT2-LCCC-Base-copyyashR4J/TyrionBOTTakoIsATaco/DialoGPT-small-ShinAIMrLamBam/DialoGPT-medium-LUKEBotZeda/DialoGPT-Medium-ZedaBotprincedream/DialoGPT-small-harrypottershahules786/Safetybot-mt5-basexiaomengdotcom/Chatgpt-harryPProtonPLUS/ColabYTTD/DialoGPT-medium-safjasondubon/HubermanGPT-small-v1YTTD/DialoGPT-medium-safv2YTTD/DialoGPT-medium-safv3kennethhendricks/DialoGPT-medium-jared-hendricks-gen1Cohee/pygmalion-6b-pyggyback-v6_40_v8p4_60DiogenesGois/DialoGPT-medium-RickLordDanielDE/DialoGPT-medium-HinaITG/DialoGPT-medium-spanish-chitchatkemsa51/DialoGPT-medium-cartmanMogwhy/DialoGPT-medium-ArrobotnRuaif/Pyg6B-V8P2Seer-luma/DialoGPT-small-SeerBotDinoloverwii/DialoGPT-Sachibotflayeddie/Mikewooldover/krautbotkielljoy/DialoGPT-small-kWAHCLAN/DialoGPT-Medium-DANss1612/loki-chatIceBruhOne/mytestcharacterwooldover/pygbotIceBruhOne/DialoGPT-medium-subjectaiYukioKoito/DialoGPT-small-ozuagaytrimoh/DialoGPT-small-harrypotterYukioKoito/DialoGPT-small-doogIceBruhOne/DialoGPT-medium-subjectai2custads23/DialoGPT-medium-aubreyHaHaMagpie/DialoGPT-small-phineasCarslo45/DialoGPT-medium-ddlc-monikazl111/ChatDoctorMarinHinawa/DialoGPT-medium-harukacustads23/DialoGPT-medium-basilIceBruhOne/DialoGPT-medium-complexaiMarinHinawa/DialoGPT-medium-Shintarojlsalty9999/DialoGPT-medium-Riddlecustads23/DialoGPT-medium-mincyWtfsquad/DialoGPT-small-pulpfictionVincentss1612/erika-chatv4WAHCLAN/DialoGPT-Large-DANSpeedemon/jake-peralta-aiSpeedemon/cobaltDeliveryBoy/DiabloGPT-medium-KurisuAbbyRhea/DialoGPT-small-adrienbotmonish162/kirthin-waifuujanna42/DialoGPT-small-phoenixAbbyRhea/DialoGPT-medium-AAFrozenSmoothie/DialoGPT-medium-starFizi12341/astro_bot1234stiGGy/DialoGPT-medium-raymondpatthebaker45/DialoGPT-small-Carlbotr4k4n1/DialoGPT-small-joshuaSukul/DialoGPT-small-HarsabotSukul/DialoGPT-small-Harsabot1hihihotdog/DialoGPT-botLarsJonasson/pythia-1.4b-deduped-sft-swedishmayaeary/pygmalion-6b-4bit-128gmayaeary/pygmalion-6b_dev-4bit-128gInhaexpress/DialoGPT-medium-paimonsanyasna517/DialoGPT-medium-ZhongliStephenBrink/DialoGPT-small-willStanleyRoberts/Nixboudchicha/soluzionemayaeary/PPO_Pygway-V8p4_Dev-6b-4bit-128gToborWinner/DialoGPT-medium-jollymayaeary/PPO_Pygway-6b-Mix-4bit-128gayushutkarsh/t3Inhaexpress/DialoGPT-medium-paimon2eepyblanky/DialoGPT-medium-malinaeachadea/legacy-ggml-vicuna-13b-4biteachadea/ggml-gpt4-x-alpaca-13b-native-4bittotallynotbrent/brotGPTInhaexpress/DialoGPT-medium-harry_potter_psrobintan66/DialoGPT-small-harrypotterMajorCrayon7047/MadboneAssistantGPT-2VennuT/DialoGPT-medium-Alphinaudtriple777/annicebottotallynotbrent/aaronGPTalphaPlaaasma/gerald-modelyashugupta786/bart_large_xsum_samsum_conv_summarizereachadea/legacy-ggml-vicuna-7b-4bitColtonAi/LlmtrainColtonAi/Chem4IchtacaKemeRaz/favabeanStromello/DialoGPT-medium-ZeroTwototallynotbrent/brotGPTplusstorminstakk/Stormin-StakkToddGoldfarb/Cadet-Tinyaghelan3/eggIncubationRepohackathon-somos-nlp-2023/SalpiBloomZ_15949_input_1024-1b7JosephusCheung/Guanacoraymondho/DialoGPT-small-harryCapitalist/DialoGPT-small-rickgfgddfg/DialoGPT-small-qiu_chateachadea/ggml-toolpaca-13b-4bitCNR223/DialoGPT-small-MasterOAbigaming75/Bot_wapranitrai07/DialoGPT-medium-harrypotterIlyaGusev/saiga_7b_loraAncestral/Dolly_Shygmalion-6b-4bit-128gAncestral/PPO_Shygmalion-6b-4bit-128gwyskiski/winonabothcpwr/DialoGPT-medium-samanthaRoguwan/DialoGPT-medium-rogutotallynotbrent/aaronGPTplusAncestral/Dolly_Malion-6b-4bit-128gvantozdad/DialoGPT-medium-DumbledoreAbyss-fyf/DialoGPT-small-discordCrystalzAura/DialoGPT-small-elysiaeachadea/ggml-gpt4all-7b-4bitinu-ai/alpaca-guanaco-japanese-gpt-1bHusnul/pepper-bot-mortyTheBloke/vicuna-13B-1.1-GPTQCRD716/ggml-vicuna-1.1-quantized4bit/pygmalion-6b-4bit-128gReaver1092/DialoGPT-small-bonesIbnelaiq/Makise-Amadeus-Kurisu-smallinu-ai/dolly-japanese-gpt-1bclawrex/DialoGPT-medium-waltIlyaGusev/saiga_13b_loraZeda/DialoGPT-Large-ZedaBotIbnelaiq/Makise-Amadeus-KurisuJaxon/DialoGPT-medium-kiritoglitchie/bbAqua002/DialoGPT-small-deadpoolAqua002/discord-chatbotlemoniada/PrzembotAvitas8485/Dialogpt-small-v1Jprafol/DialoGPT-large-ARCHIBotJprafol/DialoGPT-large-ARCHIBotV2spitfire4794/ben-ultraIlyaGusev/saiga_30b_loraNbAiLab/nb-gpt-j-6B-norpacawinglian/vicuna-self-reflect-13b0x044/test-10x044/dgptss1612/erika-chatv6TestingCoder463632/DialoGPT-small-palpatineBlizzchor/DialoGPT-medium-BarryBsasha0552/pygmalion-6b-f16-ggmlkavindu999/BetterEnglishGPT-v1kavindu999/BetterEnglishGPT-v2EnterNameBros/DialoGPT-small-FoxySanOrientalDude/DialoGPT-medium-GOKUAvitas8485/Dialogpt-medium-v1finex/pfe-mohamed-HarryAvitas8485/Dialogpt-medium-finetunedpsyamk/DialoGPT-small-harrypotterJamesonn/DialoGPT-small-juminCNXT/CNXTIlangraterol/Dataset_modelIlyaGusev/saiga_30b_ggmlLocutusque/gpt2-conversational-or-qaTrippingFollowing39/AMOGUSmoomoomer/DialoGPT-medium-garfieldPygmalionAI/pygmalion-7bViperxyz/DialoGPT-small-CartmanNeko-Institute-of-Science/pygmalion-7bTehVenom/Pygmalion-7b-Merged-SafetensorsBiaDd/DialoGPT-medium-PunkoNewBreaker/chatglm-6b-int4TehVenom/Pygmalion-7b-4bit-GPTQ-SafetensorsTehVenom/Pygmalion-7b-4bit-Q4_1-GGMLuserzyzz/piggyShardedsteinhaug/models-bckblueberrycheesecake/DialoGPT-small-misssophieImablank/P1GM4L10N-7B-MERGED_WEIGHTSMrToast/idkSouroJ/DialoGPT-medium-Mordecaisasha0552/pygmalion-7b-bf16swajan/DialoGPT-small-Trail-1RobiKenobi/DialoGPT-medium-petesasha0552/pygmalion-7b-f16-ggmlsasha0552/pygmalion-7b-f16winglian/llama-adapter-13bMatLumber/Bishoiconical/MortyChatbotAIswajan/Trail-1swajan/Trail-2Misfit2/DialoGPT-large-SonicToddGoldfarb/Cadet-Mediumajpieroni/DiabloGPT-medium-medeaAliiaR/DialoGPT-medium-empathetic-dialoguesChun121/ChocolaChatlemoniada/kicerobotKazeyami-o7/DialoGPT-medium-beterbiffinElucia/Diluc_BotElucia/Diluc_Bot_1.1Elucia/Diluc_Bot_1.2neurofumo/DialoGPT-small-joshuaElucia/Diluc_Bot_1.3GraphicStylz/Stylznaybiblu/ChizuruBotcalvindoingstuff/DialoGPT-medium-luffyxZephy/DialoGPT-small-HelperBotcrazywombat/DialoGPT-small-abandonwareanshengli2/DialoGPT-small-counter-hatesephwalker3/piggy-7bapricxty/DialoGPT-small-chatbotleadmaister/langchain-prompt-masterCovriar/DialoGPT-med-kiryuyesuns/DialoGPT-small-yesundavidviriato/DialoGPT-small-joshuaVMware/open-llama-0.3T-7B-open-instruct-v1.1prabhguron/DialoGPT-small-harrypotterxHexyy/small-testmalteos/bloom-6b4-clp-german-oasst-v0.1Pcik/DialoGPT-medium-Rubysasha0552/pygmalion-7b-q4_0-ggmlsasha0552/pygmalion-7b-q4_1-ggmlsasha0552/pygmalion-7b-q5_0-ggmlsasha0552/pygmalion-7b-q5_1-ggmlsasha0552/pygmalion-7b-q8_0-ggmlrjorg543/DialoGPT-small-beneachadea/ggml-gpt4-x-vicuna-13bTlethal/DialoGPT-small-harrypotterxHexyy/test2xHexyy/test3ldilov/stablelm-tuned-alpha-7b-4bit-128g-descact-sym-true-sequentialAnimusOG/pygmalion-7b-4bit-128g-cuda-2048Tokenjun-ai/BeethovenBotchannashi/DialoGPT-small-rocketbiscuitbutb/biscuitbot-dialogpt-modelytrbqrkflbvbhy/DialoGPT-small-me-rusPruz0/VescGPTIlyaGusev/saiga_7b_ggmlIlyaGusev/saiga_13b_ggmlTechTay/DialoGPT-small-LucianoBlackBull/yeetWAHCLAN/DialoGPT-Medium-SAMMistyIce/dialog-gpt-HeshanPruz0/LennGPTWanfq/MAKER-mwoz-full-kb-t5-baseWanfq/MAKER-mwoz-full-kb-t5-largeWanfq/MAKER-smd-condensed-kb-t5-baseWanfq/MAKER-smd-condensed-kb-t5-largeWanfq/MAKER-camrest-condensed-kb-t5-baseWanfq/MAKER-camrest-condensed-kb-t5-largeWanfq/MAKER-camrest-full-kb-t5-baseWanfq/MAKER-camrest-full-kb-t5-largeWanfq/MAKER-mwoz-condensed-kb-t5-baseWanfq/MAKER-mwoz-condensed-kb-t5-largeraphaman/testPruz0/HaLLGPTBinaryy/blender-bot-distill-finetunedalex297/DialoGPT-small-sparkyPruz0/GeoGPTPruz0/PruzGPTdorkai/pygmalion-2.7bikocx-to24/DialoGPT-medium-planktonth3d4nk/llamaModel1PygmalionAI/pygmalion-13bTehVenom/Pygmalion-13b-Mergedivaan01/TFG-Maurialex297/DialoGPT-medium-foxCrataco/Pygmalion-1.3B-GGMLSaintMcMuffins/DialoGPT-small-brain2.0dujade18/DialoGPT-medium-dwightofficeTehVenom/Pygmalion-13b-8bit-GPTQhelloerikaaa/chandlerGPTSaintMcMuffins/Brain2.1kb2c37g/DialoGPT-small-Rickalex297/DialoGPT-small-foxTeraSpace/dialofrednocontextEnterNameBros/DialoGPT-small-SenkoEnterNameBros/DialoGPT-small-Senko-san4bit/pyg-7bEnterNameBros/DialoGPT-small-Senko-san-verLumiras/rachbotkevintest1234/DialoGPT-small-harrypotterEnterNameBros/DialoGPT-small-Senko-san-ver-2EnterNameBros/DialoGPT-large-Senko-san-ver-2Delmarfish/Delmardiankymar/kittyTatonkaHF/ruDialoGpt3-medium-finetuned-russian-jokeEggsInAJar/DialoGPT-small-MerrickBotDBoi/Mayreel2hosst/FridgeLLMloitran/DialoGPT-medium-peppapigSyamil/DialoGPT-small-pixalAvitas8485/Dialogpt-medium-v2Inhaexpress/DialoGPT-medium-harrypotterloitran/DialoGPT-medium-HarryPotterSyamil/DialoGPT-medium-pixalroykim/ko_chatSyamil/DialoGPT-medium-pixalsminhcrafters/DialoGPT-small-FukuyaWarren00/DialoGPT-Med-peppa05aSyamil/DialoGPT-medium-pixalbotLelouchH/DiabloGPT-small-RaidenBotInhaexpress/DialoGPT-medium-shrek124Inhaexpress/DialoGPT-medium-terra1nascar123/Discordtester000EnterNameBros/Offical-Senko-medium-updateEnterNameBros/Offical-Senko-medium-update-2EnterNameBros/Offical-Senko-medium-update-3EnterNameBros/Senko-mediumjiezhou1996/testElMater06/SpaceCoreEnterNameBros/Offical-Senko-mediumEnterNameBros/Senko-sanDBoi/MayreelVMware/open-llama-0.7T-7B-open-instruct-v1.1Warren00/DialoGPT-Small-Peppa06_053123mpalacio/DialoGPT_ootwlprotag07/DialoGPT-small-harrypotterh2oai/h2ogpt-gm-oasst1-en-2048-falcon-7b-v2cosimoiaia/Loquace-70mcosimoiaia/Loquace-410mMareNoceda/DialoGPT-medium-LuzGarrisonBot/DialoGPT-medium-herbertgarrisoncosimoiaia/Loquace-12Bcosimoiaia/Loquace-7BDeojoandco/ahGPT-small-v1PeachHeles/bmoRays236/DialoGPT-small-harrypotterDeojoandco/ahGPT-small-v2Syamil/DialoGPT-medium-newpixalCoderhuynin/DialoGPT-large-TonyStarkSotirisLegkas/final_socratic_dialoGPTademfatnassi/bonjourGPT-smallikocx-to24/DialoGPT-small-planktongpt2EricYou/RickBotAyaakaa/DialoGPT-small-Yoisaki-KanadeDoesNoPro/DialoGPT-small-RaidenGrajeshbot/DialoGPT-medium-Harry-to-HariDoesNoPro/DialoGPT-small-RaidenG2SamsonP/pygmalion-6b-sftDeojoandco/ahDialoGPT-small-v4Syamil/GPTNeo-PIXAL-ModelSyamil/GPTNeo-PIXAL-newLattori/DiabloGPT-small-ConanBotBadzee/DialoGPT-medium-jackbotmeowsynth/DialoGPT-small-sophieEnterNameBros/Senko-san-medium-babyDeojoandco/ah-GPT2-v4cosimoiaia/Loquace-20BEnterNameBros/Senko-san-medium-foxMarkyMarx/DialoGPT-medium-jimmybot2DhruvShek/DialoGPTDoge22/DialoGPT-medium-maxlyogavin/Anima33Bsteerevo88/testThotBotsteerevo88/workingthotBotYTTD/DialoGPT-medium-keijiMisguidedKerbal/DialoGPT-medium-kerbalBlueify/DialoGPT-small-model-lotrsteerevo88/newthotBotparipi/Malishkafinex/pfe-mohamed2023-RONDhruvShek/CMDGPTfinex/pfe-mohamed2023-HermioneSkylerBlu9/DialoGPT-medium-CitrAISkylerBlu9/DialoGPT-medium-autismobotMisguidedKerbal/DialoGPT-kerbalV2EnterNameBros/Senko-san-medium-adderr/testmodelpriyanshdahiya/DialoGPT-small-rickGoodnoway/DialoGPT-nerbalV2WompWomp1/DialoGPT-medium-Kirinlyogavin/Anima33B-mergedpeytonai/DialoGPT-small-wali-joshuaMisguidedKerbal/DialoGPT-kerbalV3WompWomp1/DialoGPT-medium-KaoriOmarDiab/DialoGPT-small-Amogusservetier/DialoGPT-large-miguelOmarDiab/DialoGPT-small-Amogus-2steveglover/falcon-7b-instruct-telco-chatLazycuber/Janemalion-6BGoodnoway/DialoGPT-nerbalV4gvij/gpt-j-6B-alpaca-gpt4papahawk/keya-560mJavRedstone/DialoGPT-small-tesseractistimuncomfortable/DiabloGPT-small-CocoAtarashiAmod/falcon7b-fine-tuned-therapy-mergedOshirigami1980/DialoGPT-medium-StevenDrevanil/DialoGPT-small-tryYaewe/1DataHammer/mozi_emotional_7budxyz/HarryPotterBotKasyapa/DialoGPT-medium-hagridbotlyogavin/Anima33B-DPO-Belle-1kJeanL-0/TestingModel-01TejasC2/DialoGPT-TejasBotlyogavin/Anima33B-DPO-Belle-1k-mergedInterruptAI/Interrupt-350MLucideds/LucidedsEnterNameBros/Senko-san-medium-scEnterNameBros/Senko-san-medium-sclDaddySen/tighnariettevyemerald/DialoGPT-medium-beomgyuminhcrafters/DialoGPT-small-mindwanderingJNDankwah/DialoGPT-small-ThorCBminhcrafters/DialoGPT-medium-Zephirelpapahawk/falcon-40bsonntt/DialoGPT-small-mindwanderingpundapog/DialoGPT-medium-ethanbotTheBloke/Pygmalion-7B-SuperHOT-8K-GGMLTheBloke/Pygmalion-7B-SuperHOT-8K-fp16pobierz69/model-6b-read-descsidca/CamEnterNameBros/Senko-san-medium-abcabhi-8/DialoGPT-medium-Michaelabhi-8/DialoGPT-medium-Rickabhi-8/DialoGPT-medium-Joshua-twevyspitfire4794/dialogpt-small-rickabhi-8/Joshua-botJustus-Jonas/Imaginary-Embeddings-ClassicJustus-Jonas/Imaginary-Embeddings-SpeakerTokensJustus-Jonas/Imaginary-Embeddings-SpeakerTokens-STPspitfire4794/dialogpt-small-mortyKauru/DialoGPT-medium-Rannicrazydamns/DialoGPT-Johnny2jpandeinge/DialoGPT-medium-Oshiwambo-Botcustads23/pygmalion-1.3bHatCha01/DialoGPT-small-Batmancrazydamns/DialoGPT-Johnny3assembleteams/curiouspiKauru/DialoGPT-medium-Ranniv2SatwikShrivastava/narutoAI-chatbotdigitalmax1/maxadr2432/small-Joshua-BotObsessedCitrus/DialoGPT-small-PeterBot_ChatBotsuarkadipa/HubermanGPT-small-v1suarkadipa/HarryPotterGPT-small-v1wevie1978/DialoGPT-medium-Kebbkopeqwerty/DialoGPT-medium-idotbotzelalt/Chatbot_T5-Prmtrsjarvissss/DialoGPT-medium-idotbotMagmadue/DiabloGPT-small-einicbull/DialoGPT-small-cryptonicnicbull/DialoGPT-small-cryptonic2chloe0x0/DialoGPT-small-Mutychloe0x0/mutyGPTalexwang05/DialoGPT-small-sophBHAndersonJr/DialoGPT-small-frytimothykim04/DialoGPT-medium-timothykimtimothykim04/DialoGPT-medium-harrypotterLuca999/Limitlessai99Madgimmy/DiabloGPT-small-Madgimmychloe0x0/mutyGPT-v2nuggster/DialoGPT-small-ianbotwe1kkk/llama2-hf-qlora-oasst1IlyaGusev/saiga2_7b_loraIlyaGusev/gigasaiga_lorajliu03/JustinBotheliosbrahma/falcon-7b-finetuned-mental-health-conversationaldrunknmonk/GPT-Chandlerjun-ai/llama2-qlora-finetunined-frenchWompWomp1/DialoGPT-large-KirinWompWomp1/DialoGPT-large-Kirin-2WompWomp1/DialoGPT-large-Rinor4cl3ai/Aiden_t5jstawski/Llama-2-13b-hf-finetuned-SNGGelmo/HaloufIlyaGusev/saiga2_13b_lorasophji/DialoGPT-small-GodlyLJATrapenard/Discord-Impersonation-Bothiamitabha/llama2forbittlerobotIlyaGusev/saiga2_7b_ggufIlyaGusev/saiga2_13b_ggufTejasC2/DialoGPT-TejasBot2CNR223/DialoGPT-medium-MalcolmReynoldminh-hahaha/DialoGPT-small-harrypotterphucnq1591999/SolanaChatBotmarclove/llama-2-7b-chat-functionsSheerapi/testYukioKoito/DialoGPT-small-chibiYukioKoito/DialoGPT-small-twilightamzrana/loraierhon/basic-chatbotPula23/HggjgFocs/DialoGPT-medium-tony-starkKenobiwan/DialoGPT-small-AizakkuBot2drado/DialoGPT-small-joshuarah-1/Rahuliotanishqvashisht/DialoGPT-small-JoshuaKenobiwan/DialoGPT-small-AizakkuBot3Ridloo/DialogGPT-small-harrypotterdyuhong80/DialoGPT-large-ModerateEffortBombGPTai-forever/paper_persi_chatparalleldynamix/paralleldynamix-model101kelSidenna/SoftwareRequirements-T5-Baserenahime/DialoGPT-medium-uminekoShaun1204/RedGPT-Gormleediwas7777/HarryBotheliosbrahma/falcon-7b-sharded-bf16-finetuned-mental-health-conversationalkelSidenna/SoftwareReq-DialoGPT-mediumshanover/medbot-convJ-Wiggler/DialoGPT-medium-Stanleygearski/DialoGPT-small-itsklebwozniakclub/llama-2-7b-medtext-llama2gearski/DialoGPT-medium-itsklebrebornrulz/Rulz-AIQuantsr/DialogGPT-small-Aerisostorc/rick-sanchez-chatbotnicbull/DialoGPT-medium-nicnicbull/DialoGPT-medium-nic2gorkemgoknar/llama2-7f-moviechatbot-ggml-q4aka-nikko/ainz-ooal-gownllSourcell/medllama2_7bxtuner/Llama-2-7b-qlora-moss-003-sftxtuner/Llama-2-7b-qlora-arxiv-gentitlextuner/internlm-7b-qlora-arxiv-gentitlextuner/internlm-7b-qlora-alpaca-enzhxtuner/Baichuan-7B-qlora-arxiv-gentitlextuner/Baichuan-7B-qlora-alpaca-enzhnicbull/DialoGPT-medium-lericIan-14/llm13theastro/starkbotyupimrandy/DialoGPT-medium-butcherhclaim/clamgptattempt4yupimrandy/DialoGPT-medium-hughienekohacker591/google1zhmx31/Mychatbotsk8ingcat/DialoGPT-small-TonyStarkSanchoJR/meXxtuner/Qwen-7B-qlora-moss-003-sftxtuner/Qwen-7B-qlora-arxiv-gentitlextuner/Qwen-7B-qlora-alpaca-enzhxtuner/Qwen-7B-qlora-oasst1xtuner/Baichuan-7B-qlora-oasst1xtuner/internlm-7b-qlora-oasst14bit/medllama2_7bJGKD/JangoGPTv1.0kwankwan1000/DialoGPT-small-peppaJGKD/JangoGPTv1.5SoniR/configmjyh/falcon-7b-qlora-sclue-20230601-04-mergedsadzip/SiberianPersona-ruGPT-3.5-qloraWolffire88/DialoGPT-medium-Android16nolly3317/DialoGPT-small-alicefeelinrealcute/pym-6bnixsy/AvasLovefeelinrealcute/pym-13b7AleksiDu/HarryPotterBotBelcebuzzz/DialoGPT-small-TomoGFxtuner/internlm-7b-qlora-lawyerxtuner/internlm-7b-qlora-coloristxtuner/internlm-7b-qlora-coderxtuner/internlm-7b-qlora-open-platypusxtuner/internlm-7b-qlora-sqlinception-mbzuai/jais-13b-chatFredithefish/Guanaco-3B-Uncensoredgarrachonr/LlamaDosliterallywood/DialoGPT-small-ekanshIALABS/Arturosfastfoodjavieitor/DialoGPT-medium-RickKuduxaaa/ava-smallAl-Hathboor-Bikal-ai-2023/SRTIP-GPT-F7B-baseL-R/LLmRa-355MFredithefish/Guanaco-3B-Uncensored-v2xtuner/Llama-2-7b-qlora-coloristKE-AI/basicchatbot-keljosepholiver/TEST_MODEL_1PlaceReporter99/Utility_Bot_ChatJ-Wiggler2/CaesarJ-Wiggler2/Caesar2matvalan/vittae-cotDawnstarhunter/DialoGPT-medium-Evelinesahilxyd/DialoGPT-small-joshuaEnterNameBros/Senko-san-medium-abcd6adityaverma/DialoGPT-large-Walter6adityaverma/DialoGPT-large-RickIlyaGusev/saiga2_70b_loraAyushK0808/StarWarsBotEnterNameBros/Senko-ai-mediumFredithefish/Guanaco-7B-UncensoredIlyaGusev/saiga2_70b_ggufglassofwine/DialoGPT-medium-johanwinezattio770/120-Days-of-LORA-v2-13Bcannice/blenderbot-400M-distill-empatheticLikelihood94/JackoftradesHapski/DialoGPT-small-neneFredithefish/Guanaco-13B-Uncensoredkitbear444/DialoGPT-medium-kitSonnyAu/DialoGPT-dumbledoreTheBloke/Guanaco-7B-Uncensored-GGUFTheBloke/Guanaco-13B-Uncensored-GGUFTheBloke/Guanaco-7B-Uncensored-GPTQTheBloke/Guanaco-13B-Uncensored-GPTQTheBloke/Guanaco-3B-Uncensored-v2-GPTQTheBloke/Guanaco-3B-Uncensored-v2-GGMLCodexister/DialoGPT-medium-KafkaBotV1mfodwo/STUGPT-small-v1asas-ai/jais-13b-chat-8bitSoupChickn/Valeen-DialoGPTCodexister/DialoGPT-medium-KafkaBotV2KoalaAI/OPT-1.3b-ChatNafaille/nafaille6bDiTy/dialogptSeverus27/BeingWell_llama2_7brayho/DialoGPT-small-polysoftTuningAI/Llama2_13B_startup_Assistantdipxsy/testmodeldipxsy/Jarvis-smallLazycuber/L2-7b-Chat-Guanaco-Uncensoreddipxsy/jarvis-blendTheBloke/Guanaco-13B-Uncensored-AWQTheBloke/Guanaco-7B-Uncensored-AWQwstock04/shiddeatorBotV1Boqianshen/llama-2-7b-miniguanacosebastiantrbl/distilgpt2-finetuned-wikitext2herzlixh/DialoGPTs_HarryFromHogwartspoiccard/jais-13b-chat-adnsebastiantrbl/test-DialoGPT-finetuneuffergist/DialoGPT-small-cummywstock04/shiddeatorBotV3.0wstock04/shiddeatorBotDUMBApplekinz/JohnOr4cl3/1nsfwsebastiantrbl/DialoGPT-finetuned-daily-dialogLTC-AI-Labs/L2-7b-Base-WVG-Uncensoredhussain2030/jais13bchat2subabi/DialoGPT-medium-subabicordmarblyso/DialoGPT-medium-collinCrataco/Pygmalion-6B-GGMLdipxsy/jltesterhubhai/krnedoIAteSpaghettiForLunch/DialoGPT-medium-GLADoSIAteSpaghettiForLunch/GLADoSBOTNikolai5592/DialoGPT-Medium-RickBotKuroganeNiello/medium-NebBot123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750## Uses the huggingface text generation inference APIimport os, copy, typesimport jsonfrom enum import Enumimport httpx, requestsfrom .base import BaseLLMimport timeimport litellmfrom typing import Callable, Dict, List, Anyfrom litellm.utils import ModelResponse, Choices, Message, CustomStreamWrapper, Usagefrom typing import Optionalfrom .prompt_templates.factory import prompt_factory, custom_prompt
class HuggingfaceError(Exception): def __init__( self, status_code, message, request: Optional[httpx.Request] = None, response: Optional[httpx.Response] = None, ): self.status_code = status_code self.message = message if request is not None: self.request = request else: self.request = httpx.Request( method="POST", url="https://api-inference.huggingface.co/models" ) if response is not None: self.response = response else: self.response = httpx.Response( status_code=status_code, request=self.request ) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class HuggingfaceConfig: """ Reference: https://huggingface.github.io/text-generation-inference/#/Text%20Generation%20Inference/compat_generate """
best_of: Optional[int] = None decoder_input_details: Optional[bool] = None details: Optional[bool] = True # enables returning logprobs + best of max_new_tokens: Optional[int] = None repetition_penalty: Optional[float] = None return_full_text: Optional[ bool ] = False # by default don't return the input as part of the output seed: Optional[int] = None temperature: Optional[float] = None top_k: Optional[int] = None top_n_tokens: Optional[int] = None top_p: Optional[int] = None truncate: Optional[int] = None typical_p: Optional[float] = None watermark: Optional[bool] = None
def __init__( self, best_of: Optional[int] = None, decoder_input_details: Optional[bool] = None, details: Optional[bool] = None, max_new_tokens: Optional[int] = None, repetition_penalty: Optional[float] = None, return_full_text: Optional[bool] = None, seed: Optional[int] = None, temperature: Optional[float] = None, top_k: Optional[int] = None, top_n_tokens: Optional[int] = None, top_p: Optional[int] = None, truncate: Optional[int] = None, typical_p: Optional[float] = None, watermark: Optional[bool] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def output_parser(generated_text: str): """ Parse the output text to remove any special characters. In our current approach we just check for ChatML tokens.
Initial issue that prompted this - https://github.com/BerriAI/litellm/issues/763 """ chat_template_tokens = ["<|assistant|>", "<|system|>", "<|user|>", "<s>", "</s>"] for token in chat_template_tokens: if generated_text.strip().startswith(token): generated_text = generated_text.replace(token, "", 1) if generated_text.endswith(token): generated_text = generated_text[::-1].replace(token[::-1], "", 1)[::-1] return generated_text
tgi_models_cache = Noneconv_models_cache = None
def read_tgi_conv_models(): try: global tgi_models_cache, conv_models_cache # Check if the cache is already populated # so we don't keep on reading txt file if there are 1k requests if (tgi_models_cache is not None) and (conv_models_cache is not None): return tgi_models_cache, conv_models_cache # If not, read the file and populate the cache tgi_models = set() script_directory = os.path.dirname(os.path.abspath(__file__)) # Construct the file path relative to the script's directory file_path = os.path.join( script_directory, "huggingface_llms_metadata", "hf_text_generation_models.txt", )
with open(file_path, "r") as file: for line in file: tgi_models.add(line.strip())
# Cache the set for future use tgi_models_cache = tgi_models
# If not, read the file and populate the cache file_path = os.path.join( script_directory, "huggingface_llms_metadata", "hf_conversational_models.txt", ) conv_models = set() with open(file_path, "r") as file: for line in file: conv_models.add(line.strip()) # Cache the set for future use conv_models_cache = conv_models return tgi_models, conv_models except: return set(), set()
def get_hf_task_for_model(model): # read text file, cast it to set # read the file called "huggingface_llms_metadata/hf_text_generation_models.txt" tgi_models, conversational_models = read_tgi_conv_models() if model in tgi_models: return "text-generation-inference" elif model in conversational_models: return "conversational" elif "roneneldan/TinyStories" in model: return None else: return "text-generation-inference" # default to tgi
class Huggingface(BaseLLM): _client_session: Optional[httpx.Client] = None _aclient_session: Optional[httpx.AsyncClient] = None
def __init__(self) -> None: super().__init__()
def validate_environment(self, api_key, headers): default_headers = { "content-type": "application/json", } if api_key and headers is None: default_headers[ "Authorization" ] = f"Bearer {api_key}" # Huggingface Inference Endpoint default is to accept bearer tokens headers = default_headers elif headers: headers = headers else: headers = default_headers return headers
def convert_to_model_response_object( self, completion_response, model_response, task, optional_params, encoding, input_text, model, ): if task == "conversational": if len(completion_response["generated_text"]) > 0: # type: ignore model_response["choices"][0]["message"][ "content" ] = completion_response[ "generated_text" ] # type: ignore elif task == "text-generation-inference": if ( not isinstance(completion_response, list) or not isinstance(completion_response[0], dict) or "generated_text" not in completion_response[0] ): raise HuggingfaceError( status_code=422, message=f"response is not in expected format - {completion_response}", )
if len(completion_response[0]["generated_text"]) > 0: model_response["choices"][0]["message"]["content"] = output_parser( completion_response[0]["generated_text"] ) ## GETTING LOGPROBS + FINISH REASON if ( "details" in completion_response[0] and "tokens" in completion_response[0]["details"] ): model_response.choices[0].finish_reason = completion_response[0][ "details" ]["finish_reason"] sum_logprob = 0 for token in completion_response[0]["details"]["tokens"]: if token["logprob"] != None: sum_logprob += token["logprob"] model_response["choices"][0]["message"]._logprob = sum_logprob if "best_of" in optional_params and optional_params["best_of"] > 1: if ( "details" in completion_response[0] and "best_of_sequences" in completion_response[0]["details"] ): choices_list = [] for idx, item in enumerate( completion_response[0]["details"]["best_of_sequences"] ): sum_logprob = 0 for token in item["tokens"]: if token["logprob"] != None: sum_logprob += token["logprob"] if len(item["generated_text"]) > 0: message_obj = Message( content=output_parser(item["generated_text"]), logprobs=sum_logprob, ) else: message_obj = Message(content=None) choice_obj = Choices( finish_reason=item["finish_reason"], index=idx + 1, message=message_obj, ) choices_list.append(choice_obj) model_response["choices"].extend(choices_list) else: if len(completion_response[0]["generated_text"]) > 0: model_response["choices"][0]["message"]["content"] = output_parser( completion_response[0]["generated_text"] ) ## CALCULATING USAGE prompt_tokens = 0 try: prompt_tokens = len( encoding.encode(input_text) ) ##[TODO] use the llama2 tokenizer here except: # this should remain non blocking we should not block a response returning if calculating usage fails pass output_text = model_response["choices"][0]["message"].get("content", "") if output_text is not None and len(output_text) > 0: completion_tokens = 0 try: completion_tokens = len( encoding.encode( model_response["choices"][0]["message"].get("content", "") ) ) ##[TODO] use the llama2 tokenizer here except: # this should remain non blocking we should not block a response returning if calculating usage fails pass else: completion_tokens = 0
model_response["created"] = int(time.time()) model_response["model"] = model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage model_response._hidden_params["original_response"] = completion_response return model_response
def completion( self, model: str, messages: list, api_base: Optional[str], headers: Optional[dict], model_response: ModelResponse, print_verbose: Callable, timeout: float, encoding, api_key, logging_obj, custom_prompt_dict={}, acompletion: bool = False, optional_params=None, litellm_params=None, logger_fn=None, ): super().completion() exception_mapping_worked = False try: headers = self.validate_environment(api_key, headers) task = get_hf_task_for_model(model) print_verbose(f"{model}, {task}") completion_url = "" input_text = "" if "https" in model: completion_url = model elif api_base: completion_url = api_base elif "HF_API_BASE" in os.environ: completion_url = os.getenv("HF_API_BASE", "") elif "HUGGINGFACE_API_BASE" in os.environ: completion_url = os.getenv("HUGGINGFACE_API_BASE", "") else: completion_url = f"https://api-inference.huggingface.co/models/{model}"
## Load Config config = litellm.HuggingfaceConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > huggingfaceConfig(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
### MAP INPUT PARAMS if task == "conversational": inference_params = copy.deepcopy(optional_params) inference_params.pop("details") inference_params.pop("return_full_text") past_user_inputs = [] generated_responses = [] text = "" for message in messages: if message["role"] == "user": if text != "": past_user_inputs.append(text) text = message["content"] elif message["role"] == "assistant" or message["role"] == "system": generated_responses.append(message["content"]) data = { "inputs": { "text": text, "past_user_inputs": past_user_inputs, "generated_responses": generated_responses, }, "parameters": inference_params, } input_text = "".join(message["content"] for message in messages) elif task == "text-generation-inference": # always send "details" and "return_full_text" as params if model in custom_prompt_dict: # check if the model has a registered custom prompt model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details.get("roles", None), initial_prompt_value=model_prompt_details.get( "initial_prompt_value", "" ), final_prompt_value=model_prompt_details.get( "final_prompt_value", "" ), messages=messages, ) else: prompt = prompt_factory(model=model, messages=messages) data = { "inputs": prompt, "parameters": optional_params, "stream": True if "stream" in optional_params and optional_params["stream"] == True else False, } input_text = prompt else: # Non TGI and Conversational llms # We need this branch, it removes 'details' and 'return_full_text' from params if model in custom_prompt_dict: # check if the model has a registered custom prompt model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details.get("roles", {}), initial_prompt_value=model_prompt_details.get( "initial_prompt_value", "" ), final_prompt_value=model_prompt_details.get( "final_prompt_value", "" ), bos_token=model_prompt_details.get("bos_token", ""), eos_token=model_prompt_details.get("eos_token", ""), messages=messages, ) else: prompt = prompt_factory(model=model, messages=messages) inference_params = copy.deepcopy(optional_params) inference_params.pop("details") inference_params.pop("return_full_text") data = { "inputs": prompt, "parameters": inference_params, "stream": True if "stream" in optional_params and optional_params["stream"] == True else False, } input_text = prompt ## LOGGING logging_obj.pre_call( input=input_text, api_key=api_key, additional_args={ "complete_input_dict": data, "task": task, "headers": headers, "api_base": completion_url, "acompletion": acompletion, }, ) ## COMPLETION CALL if acompletion is True: ### ASYNC STREAMING if optional_params.get("stream", False): return self.async_streaming(logging_obj=logging_obj, api_base=completion_url, data=data, headers=headers, model_response=model_response, model=model, timeout=timeout) # type: ignore else: ### ASYNC COMPLETION return self.acompletion(api_base=completion_url, data=data, headers=headers, model_response=model_response, task=task, encoding=encoding, input_text=input_text, model=model, optional_params=optional_params, timeout=timeout) # type: ignore ### SYNC STREAMING if "stream" in optional_params and optional_params["stream"] == True: response = requests.post( completion_url, headers=headers, data=json.dumps(data), stream=optional_params["stream"], ) return response.iter_lines() ### SYNC COMPLETION else: response = requests.post( completion_url, headers=headers, data=json.dumps(data) )
## Some servers might return streaming responses even though stream was not set to true. (e.g. Baseten) is_streamed = False if ( response.__dict__["headers"].get("Content-Type", "") == "text/event-stream" ): is_streamed = True
# iterate over the complete streamed response, and return the final answer if is_streamed: streamed_response = CustomStreamWrapper( completion_stream=response.iter_lines(), model=model, custom_llm_provider="huggingface", logging_obj=logging_obj, ) content = "" for chunk in streamed_response: content += chunk["choices"][0]["delta"]["content"] completion_response: List[Dict[str, Any]] = [ {"generated_text": content} ] ## LOGGING logging_obj.post_call( input=input_text, api_key=api_key, original_response=completion_response, additional_args={"complete_input_dict": data, "task": task}, ) else: ## LOGGING logging_obj.post_call( input=input_text, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data, "task": task}, ) ## RESPONSE OBJECT try: completion_response = response.json() if isinstance(completion_response, dict): completion_response = [completion_response] except: import traceback
raise HuggingfaceError( message=f"Original Response received: {response.text}; Stacktrace: {traceback.format_exc()}", status_code=response.status_code, ) print_verbose(f"response: {completion_response}") if ( isinstance(completion_response, dict) and "error" in completion_response ): print_verbose(f"completion error: {completion_response['error']}") print_verbose(f"response.status_code: {response.status_code}") raise HuggingfaceError( message=completion_response["error"], status_code=response.status_code, ) return self.convert_to_model_response_object( completion_response=completion_response, model_response=model_response, task=task, optional_params=optional_params, encoding=encoding, input_text=input_text, model=model, ) except HuggingfaceError as e: exception_mapping_worked = True raise e except Exception as e: if exception_mapping_worked: raise e else: import traceback
raise HuggingfaceError(status_code=500, message=traceback.format_exc())
async def acompletion( self, api_base: str, data: dict, headers: dict, model_response: ModelResponse, task: str, encoding: Any, input_text: str, model: str, optional_params: dict, timeout: float ): response = None try: async with httpx.AsyncClient(timeout=timeout) as client: response = await client.post( url=api_base, json=data, headers=headers ) response_json = response.json() if response.status_code != 200: raise HuggingfaceError( status_code=response.status_code, message=response.text, request=response.request, response=response, )
## RESPONSE OBJECT return self.convert_to_model_response_object( completion_response=response_json, model_response=model_response, task=task, encoding=encoding, input_text=input_text, model=model, optional_params=optional_params, ) except Exception as e: if isinstance(e, httpx.TimeoutException): raise HuggingfaceError(status_code=500, message="Request Timeout Error") elif response is not None and hasattr(response, "text"): raise HuggingfaceError( status_code=500, message=f"{str(e)}\n\nOriginal Response: {response.text}", ) else: raise HuggingfaceError(status_code=500, message=f"{str(e)}")
async def async_streaming( self, logging_obj, api_base: str, data: dict, headers: dict, model_response: ModelResponse, model: str, timeout: float ): async with httpx.AsyncClient(timeout=timeout) as client: response = client.stream( "POST", url=f"{api_base}", json=data, headers=headers ) async with response as r: if r.status_code != 200: raise HuggingfaceError( status_code=r.status_code, message="An error occurred while streaming", ) streamwrapper = CustomStreamWrapper( completion_stream=r.aiter_lines(), model=model, custom_llm_provider="huggingface", logging_obj=logging_obj, ) async for transformed_chunk in streamwrapper: yield transformed_chunk
def embedding( self, model: str, input: list, api_key: Optional[str] = None, api_base: Optional[str] = None, logging_obj=None, model_response=None, encoding=None, ): super().embedding() headers = self.validate_environment(api_key, headers=None) # print_verbose(f"{model}, {task}") embed_url = "" if "https" in model: embed_url = model elif api_base: embed_url = api_base elif "HF_API_BASE" in os.environ: embed_url = os.getenv("HF_API_BASE", "") elif "HUGGINGFACE_API_BASE" in os.environ: embed_url = os.getenv("HUGGINGFACE_API_BASE", "") else: embed_url = f"https://api-inference.huggingface.co/models/{model}"
if "sentence-transformers" in model: if len(input) == 0: raise HuggingfaceError( status_code=400, message="sentence transformers requires 2+ sentences", ) data = { "inputs": { "source_sentence": input[0], "sentences": [ "That is a happy dog", "That is a very happy person", "Today is a sunny day", ], } } else: data = {"inputs": input} # type: ignore
## LOGGING logging_obj.pre_call( input=input, api_key=api_key, additional_args={ "complete_input_dict": data, "headers": headers, "api_base": embed_url, }, ) ## COMPLETION CALL response = requests.post(embed_url, headers=headers, data=json.dumps(data))
## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=response, )
embeddings = response.json()
if "error" in embeddings: raise HuggingfaceError(status_code=500, message=embeddings["error"])
output_data = [] if "similarities" in embeddings: for idx, embedding in embeddings["similarities"]: output_data.append( { "object": "embedding", "index": idx, "embedding": embedding, # flatten list returned from hf } ) else: for idx, embedding in enumerate(embeddings): if isinstance(embedding, float): output_data.append( { "object": "embedding", "index": idx, "embedding": embedding, # flatten list returned from hf } ) elif isinstance(embedding, list) and isinstance(embedding[0], float): output_data.append( { "object": "embedding", "index": idx, "embedding": embedding, # flatten list returned from hf } ) else: output_data.append( { "object": "embedding", "index": idx, "embedding": embedding[0][ 0 ], # flatten list returned from hf } ) model_response["object"] = "list" model_response["data"] = output_data model_response["model"] = model input_tokens = 0 for text in input: input_tokens += len(encoding.encode(text))
model_response["usage"] = { "prompt_tokens": input_tokens, "total_tokens": input_tokens, } return model_response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189import os, typesimport jsonfrom enum import Enumimport requestsimport time, tracebackfrom typing import Callable, Optional, Listfrom litellm.utils import ModelResponse, Choices, Message, Usageimport litellm
class MaritalkError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class MaritTalkConfig: """ The class `MaritTalkConfig` provides configuration for the MaritTalk's API interface. Here are the parameters:
- `max_tokens` (integer): Maximum number of tokens the model will generate as part of the response. Default is 1.
- `model` (string): The model used for conversation. Default is 'maritalk'.
- `do_sample` (boolean): If set to True, the API will generate a response using sampling. Default is True.
- `temperature` (number): A non-negative float controlling the randomness in generation. Lower temperatures result in less random generations. Default is 0.7.
- `top_p` (number): Selection threshold for token inclusion based on cumulative probability. Default is 0.95.
- `repetition_penalty` (number): Penalty for repetition in the generated conversation. Default is 1.
- `stopping_tokens` (list of string): List of tokens where the conversation can be stopped/stopped. """
max_tokens: Optional[int] = None model: Optional[str] = None do_sample: Optional[bool] = None temperature: Optional[float] = None top_p: Optional[float] = None repetition_penalty: Optional[float] = None stopping_tokens: Optional[List[str]] = None
def __init__( self, max_tokens: Optional[int] = None, model: Optional[str] = None, do_sample: Optional[bool] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, repetition_penalty: Optional[float] = None, stopping_tokens: Optional[List[str]] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def validate_environment(api_key): headers = { "accept": "application/json", "content-type": "application/json", } if api_key: headers["Authorization"] = f"Key {api_key}" return headers
def completion( model: str, messages: list, api_base: str, model_response: ModelResponse, print_verbose: Callable, encoding, api_key, logging_obj, optional_params=None, litellm_params=None, logger_fn=None,): headers = validate_environment(api_key) completion_url = api_base model = model
## Load Config config = litellm.MaritTalkConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > maritalk_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
data = { "messages": messages, **optional_params, }
## LOGGING logging_obj.pre_call( input=messages, api_key=api_key, additional_args={"complete_input_dict": data}, ) ## COMPLETION CALL response = requests.post( completion_url, headers=headers, data=json.dumps(data), stream=optional_params["stream"] if "stream" in optional_params else False, ) if "stream" in optional_params and optional_params["stream"] == True: return response.iter_lines() else: ## LOGGING logging_obj.post_call( input=messages, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data}, ) print_verbose(f"raw model_response: {response.text}") ## RESPONSE OBJECT completion_response = response.json() if "error" in completion_response: raise MaritalkError( message=completion_response["error"], status_code=response.status_code, ) else: try: if len(completion_response["answer"]) > 0: model_response["choices"][0]["message"][ "content" ] = completion_response["answer"] except Exception as e: raise MaritalkError( message=response.text, status_code=response.status_code )
## CALCULATING USAGE prompt = "".join(m["content"] for m in messages) prompt_tokens = len(encoding.encode(prompt)) completion_tokens = len( encoding.encode(model_response["choices"][0]["message"].get("content", "")) )
model_response["created"] = int(time.time()) model_response["model"] = model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response
def embedding( model: str, input: list, api_key: Optional[str] = None, logging_obj=None, model_response=None, encoding=None,): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243import os, typesimport jsonfrom enum import Enumimport requestsimport timefrom typing import Callable, Optionalimport litellmfrom litellm.utils import ModelResponse, Usage
class NLPCloudError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class NLPCloudConfig: """ Reference: https://docs.nlpcloud.com/#generation
- `max_length` (int): Optional. The maximum number of tokens that the generated text should contain.
- `length_no_input` (boolean): Optional. Whether `min_length` and `max_length` should not include the length of the input text.
- `end_sequence` (string): Optional. A specific token that should be the end of the generated sequence.
- `remove_end_sequence` (boolean): Optional. Whether to remove the `end_sequence` string from the result.
- `remove_input` (boolean): Optional. Whether to remove the input text from the result.
- `bad_words` (list of strings): Optional. List of tokens that are not allowed to be generated.
- `temperature` (float): Optional. Temperature sampling. It modulates the next token probabilities.
- `top_p` (float): Optional. Top P sampling. Below 1, only the most probable tokens with probabilities that add up to top_p or higher are kept for generation.
- `top_k` (int): Optional. Top K sampling. The number of highest probability vocabulary tokens to keep for top k filtering.
- `repetition_penalty` (float): Optional. Prevents the same word from being repeated too many times.
- `num_beams` (int): Optional. Number of beams for beam search.
- `num_return_sequences` (int): Optional. The number of independently computed returned sequences. """
max_length: Optional[int] = None length_no_input: Optional[bool] = None end_sequence: Optional[str] = None remove_end_sequence: Optional[bool] = None remove_input: Optional[bool] = None bad_words: Optional[list] = None temperature: Optional[float] = None top_p: Optional[float] = None top_k: Optional[int] = None repetition_penalty: Optional[float] = None num_beams: Optional[int] = None num_return_sequences: Optional[int] = None
def __init__( self, max_length: Optional[int] = None, length_no_input: Optional[bool] = None, end_sequence: Optional[str] = None, remove_end_sequence: Optional[bool] = None, remove_input: Optional[bool] = None, bad_words: Optional[list] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, top_k: Optional[int] = None, repetition_penalty: Optional[float] = None, num_beams: Optional[int] = None, num_return_sequences: Optional[int] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
def validate_environment(api_key): headers = { "accept": "application/json", "content-type": "application/json", } if api_key: headers["Authorization"] = f"Token {api_key}" return headers
def completion( model: str, messages: list, api_base: str, model_response: ModelResponse, print_verbose: Callable, encoding, api_key, logging_obj, optional_params=None, litellm_params=None, logger_fn=None, default_max_tokens_to_sample=None,): headers = validate_environment(api_key)
## Load Config config = litellm.NLPCloudConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > togetherai_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
completion_url_fragment_1 = api_base completion_url_fragment_2 = "/generation" model = model text = " ".join(message["content"] for message in messages)
data = { "text": text, **optional_params, }
completion_url = completion_url_fragment_1 + model + completion_url_fragment_2
## LOGGING logging_obj.pre_call( input=text, api_key=api_key, additional_args={ "complete_input_dict": data, "headers": headers, "api_base": completion_url, }, ) ## COMPLETION CALL response = requests.post( completion_url, headers=headers, data=json.dumps(data), stream=optional_params["stream"] if "stream" in optional_params else False, ) if "stream" in optional_params and optional_params["stream"] == True: return clean_and_iterate_chunks(response) else: ## LOGGING logging_obj.post_call( input=text, api_key=api_key, original_response=response.text, additional_args={"complete_input_dict": data}, ) print_verbose(f"raw model_response: {response.text}") ## RESPONSE OBJECT try: completion_response = response.json() except: raise NLPCloudError(message=response.text, status_code=response.status_code) if "error" in completion_response: raise NLPCloudError( message=completion_response["error"], status_code=response.status_code, ) else: try: if len(completion_response["generated_text"]) > 0: model_response["choices"][0]["message"][ "content" ] = completion_response["generated_text"] except: raise NLPCloudError( message=json.dumps(completion_response), status_code=response.status_code, )
## CALCULATING USAGE - baseten charges on time, not tokens - have some mapping of cost here. prompt_tokens = completion_response["nb_input_tokens"] completion_tokens = completion_response["nb_generated_tokens"]
model_response["created"] = int(time.time()) model_response["model"] = model usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) model_response.usage = usage return model_response
# def clean_and_iterate_chunks(response):# def process_chunk(chunk):# print(f"received chunk: {chunk}")# cleaned_chunk = chunk.decode("utf-8")# # Perform further processing based on your needs# return cleaned_chunk
# for line in response.iter_lines():# if line:# yield process_chunk(line)def clean_and_iterate_chunks(response): buffer = b""
for chunk in response.iter_content(chunk_size=1024): if not chunk: break
buffer += chunk while b"\x00" in buffer: buffer = buffer.replace(b"\x00", b"") yield buffer.decode("utf-8") buffer = b""
# No more data expected, yield any remaining data in the buffer if buffer: yield buffer.decode("utf-8")
def embedding(): # logic for parsing in - calling - parsing out model embedding calls pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400import requests, types, timeimport json, uuidimport tracebackfrom typing import Optionalimport litellmimport httpx, aiohttp, asynciofrom .prompt_templates.factory import prompt_factory, custom_prompt
class OllamaError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request(method="POST", url="http://localhost:11434") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class OllamaConfig: """ Reference: https://github.com/jmorganca/ollama/blob/main/docs/api.md#parameters
The class `OllamaConfig` provides the configuration for the Ollama's API interface. Below are the parameters:
- `mirostat` (int): Enable Mirostat sampling for controlling perplexity. Default is 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0. Example usage: mirostat 0
- `mirostat_eta` (float): Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. Default: 0.1. Example usage: mirostat_eta 0.1
- `mirostat_tau` (float): Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. Default: 5.0. Example usage: mirostat_tau 5.0
- `num_ctx` (int): Sets the size of the context window used to generate the next token. Default: 2048. Example usage: num_ctx 4096
- `num_gqa` (int): The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b. Example usage: num_gqa 1
- `num_gpu` (int): The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. Example usage: num_gpu 0
- `num_thread` (int): Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Example usage: num_thread 8
- `repeat_last_n` (int): Sets how far back for the model to look back to prevent repetition. Default: 64, 0 = disabled, -1 = num_ctx. Example usage: repeat_last_n 64
- `repeat_penalty` (float): Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. Default: 1.1. Example usage: repeat_penalty 1.1
- `temperature` (float): The temperature of the model. Increasing the temperature will make the model answer more creatively. Default: 0.8. Example usage: temperature 0.7
- `stop` (string[]): Sets the stop sequences to use. Example usage: stop "AI assistant:"
- `tfs_z` (float): Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. Default: 1. Example usage: tfs_z 1
- `num_predict` (int): Maximum number of tokens to predict when generating text. Default: 128, -1 = infinite generation, -2 = fill context. Example usage: num_predict 42
- `top_k` (int): Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. Default: 40. Example usage: top_k 40
- `top_p` (float): Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. Default: 0.9. Example usage: top_p 0.9
- `system` (string): system prompt for model (overrides what is defined in the Modelfile)
- `template` (string): the full prompt or prompt template (overrides what is defined in the Modelfile) """
mirostat: Optional[int] = None mirostat_eta: Optional[float] = None mirostat_tau: Optional[float] = None num_ctx: Optional[int] = None num_gqa: Optional[int] = None num_thread: Optional[int] = None repeat_last_n: Optional[int] = None repeat_penalty: Optional[float] = None temperature: Optional[float] = None stop: Optional[ list ] = None # stop is a list based on this - https://github.com/jmorganca/ollama/pull/442 tfs_z: Optional[float] = None num_predict: Optional[int] = None top_k: Optional[int] = None top_p: Optional[float] = None system: Optional[str] = None template: Optional[str] = None
def __init__( self, mirostat: Optional[int] = None, mirostat_eta: Optional[float] = None, mirostat_tau: Optional[float] = None, num_ctx: Optional[int] = None, num_gqa: Optional[int] = None, num_thread: Optional[int] = None, repeat_last_n: Optional[int] = None, repeat_penalty: Optional[float] = None, temperature: Optional[float] = None, stop: Optional[list] = None, tfs_z: Optional[float] = None, num_predict: Optional[int] = None, top_k: Optional[int] = None, top_p: Optional[float] = None, system: Optional[str] = None, template: Optional[str] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
# ollama implementationdef get_ollama_response( api_base="http://localhost:11434", model="llama2", prompt="Why is the sky blue?", optional_params=None, logging_obj=None, acompletion: bool = False, model_response=None, encoding=None,): if api_base.endswith("/api/generate"): url = api_base else: url = f"{api_base}/api/generate"
## Load Config config = litellm.OllamaConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > cohere_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
optional_params["stream"] = optional_params.get("stream", False) data = {"model": model, "prompt": prompt, **optional_params} ## LOGGING logging_obj.pre_call( input=None, api_key=None, additional_args={ "api_base": url, "complete_input_dict": data, "headers": {}, "acompletion": acompletion, }, ) if acompletion is True: if optional_params.get("stream", False) == True: response = ollama_async_streaming( url=url, data=data, model_response=model_response, encoding=encoding, logging_obj=logging_obj, ) else: response = ollama_acompletion( url=url, data=data, model_response=model_response, encoding=encoding, logging_obj=logging_obj, ) return response elif optional_params.get("stream", False) == True: return ollama_completion_stream(url=url, data=data, logging_obj=logging_obj)
response = requests.post(url=f"{url}", json=data, timeout=litellm.request_timeout) if response.status_code != 200: raise OllamaError(status_code=response.status_code, message=response.text)
## LOGGING logging_obj.post_call( input=prompt, api_key="", original_response=response.text, additional_args={ "headers": None, "api_base": api_base, }, )
response_json = response.json()
## RESPONSE OBJECT model_response["choices"][0]["finish_reason"] = "stop" if optional_params.get("format", "") == "json": message = litellm.Message( content=None, tool_calls=[ { "id": f"call_{str(uuid.uuid4())}", "function": {"arguments": response_json["response"], "name": ""}, "type": "function", } ], ) model_response["choices"][0]["message"] = message else: model_response["choices"][0]["message"]["content"] = response_json["response"] model_response["created"] = int(time.time()) model_response["model"] = "ollama/" + model prompt_tokens = response_json.get("prompt_eval_count", len(encoding.encode(prompt))) # type: ignore completion_tokens = response_json["eval_count"] model_response["usage"] = litellm.Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) return model_response
def ollama_completion_stream(url, data, logging_obj): with httpx.stream( url=url, json=data, method="POST", timeout=litellm.request_timeout ) as response: try: if response.status_code != 200: raise OllamaError( status_code=response.status_code, message=response.text )
streamwrapper = litellm.CustomStreamWrapper( completion_stream=response.iter_lines(), model=data["model"], custom_llm_provider="ollama", logging_obj=logging_obj, ) for transformed_chunk in streamwrapper: yield transformed_chunk except Exception as e: raise e
async def ollama_async_streaming(url, data, model_response, encoding, logging_obj): try: client = httpx.AsyncClient() async with client.stream( url=f"{url}", json=data, method="POST", timeout=litellm.request_timeout ) as response: if response.status_code != 200: raise OllamaError( status_code=response.status_code, message=response.text )
streamwrapper = litellm.CustomStreamWrapper( completion_stream=response.aiter_lines(), model=data["model"], custom_llm_provider="ollama", logging_obj=logging_obj, ) async for transformed_chunk in streamwrapper: yield transformed_chunk except Exception as e: traceback.print_exc()
async def ollama_acompletion(url, data, model_response, encoding, logging_obj): data["stream"] = False try: timeout = aiohttp.ClientTimeout(total=litellm.request_timeout) # 10 minutes async with aiohttp.ClientSession(timeout=timeout) as session: resp = await session.post(url, json=data)
if resp.status != 200: text = await resp.text() raise OllamaError(status_code=resp.status, message=text)
## LOGGING logging_obj.post_call( input=data["prompt"], api_key="", original_response=resp.text, additional_args={ "headers": None, "api_base": url, }, )
response_json = await resp.json() ## RESPONSE OBJECT model_response["choices"][0]["finish_reason"] = "stop" if data.get("format", "") == "json": message = litellm.Message( content=None, tool_calls=[ { "id": f"call_{str(uuid.uuid4())}", "function": { "arguments": response_json["response"], "name": "", }, "type": "function", } ], ) model_response["choices"][0]["message"] = message else: model_response["choices"][0]["message"]["content"] = response_json[ "response" ] model_response["created"] = int(time.time()) model_response["model"] = "ollama/" + data["model"] prompt_tokens = response_json.get("prompt_eval_count", len(encoding.encode(data["prompt"]))) # type: ignore completion_tokens = response_json["eval_count"] model_response["usage"] = litellm.Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) return model_response except Exception as e: traceback.print_exc() raise e
async def ollama_aembeddings( api_base="http://localhost:11434", model="llama2", prompt="Why is the sky blue?", optional_params=None, logging_obj=None, model_response=None, encoding=None,): if api_base.endswith("/api/embeddings"): url = api_base else: url = f"{api_base}/api/embeddings"
## Load Config config = litellm.OllamaConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > cohere_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
data = { "model": model, "prompt": prompt, } ## LOGGING logging_obj.pre_call( input=None, api_key=None, additional_args={"api_base": url, "complete_input_dict": data, "headers": {}}, ) timeout = aiohttp.ClientTimeout(total=litellm.request_timeout) # 10 minutes async with aiohttp.ClientSession(timeout=timeout) as session: response = await session.post(url, json=data)
if response.status != 200: text = await response.text() raise OllamaError(status_code=response.status, message=text)
## LOGGING logging_obj.post_call( input=prompt, api_key="", original_response=response.text, additional_args={ "headers": None, "api_base": api_base, }, )
response_json = await response.json() embeddings = response_json["embedding"] ## RESPONSE OBJECT output_data = [] for idx, embedding in enumerate(embeddings): output_data.append( {"object": "embedding", "index": idx, "embedding": embedding} ) model_response["object"] = "list" model_response["data"] = output_data model_response["model"] = model
input_tokens = len(encoding.encode(prompt))
model_response["usage"] = { "prompt_tokens": input_tokens, "total_tokens": input_tokens, } return model_response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333import requests, types, timeimport json, uuidimport tracebackfrom typing import Optionalimport litellmimport httpx, aiohttp, asynciofrom .prompt_templates.factory import prompt_factory, custom_prompt
class OllamaError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message self.request = httpx.Request(method="POST", url="http://localhost:11434") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( self.message ) # Call the base class constructor with the parameters it needs
class OllamaConfig: """ Reference: https://github.com/jmorganca/ollama/blob/main/docs/api.md#parameters
The class `OllamaConfig` provides the configuration for the Ollama's API interface. Below are the parameters:
- `mirostat` (int): Enable Mirostat sampling for controlling perplexity. Default is 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0. Example usage: mirostat 0
- `mirostat_eta` (float): Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. Default: 0.1. Example usage: mirostat_eta 0.1
- `mirostat_tau` (float): Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. Default: 5.0. Example usage: mirostat_tau 5.0
- `num_ctx` (int): Sets the size of the context window used to generate the next token. Default: 2048. Example usage: num_ctx 4096
- `num_gqa` (int): The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b. Example usage: num_gqa 1
- `num_gpu` (int): The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. Example usage: num_gpu 0
- `num_thread` (int): Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Example usage: num_thread 8
- `repeat_last_n` (int): Sets how far back for the model to look back to prevent repetition. Default: 64, 0 = disabled, -1 = num_ctx. Example usage: repeat_last_n 64
- `repeat_penalty` (float): Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. Default: 1.1. Example usage: repeat_penalty 1.1
- `temperature` (float): The temperature of the model. Increasing the temperature will make the model answer more creatively. Default: 0.8. Example usage: temperature 0.7
- `stop` (string[]): Sets the stop sequences to use. Example usage: stop "AI assistant:"
- `tfs_z` (float): Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. Default: 1. Example usage: tfs_z 1
- `num_predict` (int): Maximum number of tokens to predict when generating text. Default: 128, -1 = infinite generation, -2 = fill context. Example usage: num_predict 42
- `top_k` (int): Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. Default: 40. Example usage: top_k 40
- `top_p` (float): Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. Default: 0.9. Example usage: top_p 0.9
- `system` (string): system prompt for model (overrides what is defined in the Modelfile)
- `template` (string): the full prompt or prompt template (overrides what is defined in the Modelfile) """
mirostat: Optional[int] = None mirostat_eta: Optional[float] = None mirostat_tau: Optional[float] = None num_ctx: Optional[int] = None num_gqa: Optional[int] = None num_thread: Optional[int] = None repeat_last_n: Optional[int] = None repeat_penalty: Optional[float] = None temperature: Optional[float] = None stop: Optional[ list ] = None # stop is a list based on this - https://github.com/jmorganca/ollama/pull/442 tfs_z: Optional[float] = None num_predict: Optional[int] = None top_k: Optional[int] = None top_p: Optional[float] = None system: Optional[str] = None template: Optional[str] = None
def __init__( self, mirostat: Optional[int] = None, mirostat_eta: Optional[float] = None, mirostat_tau: Optional[float] = None, num_ctx: Optional[int] = None, num_gqa: Optional[int] = None, num_thread: Optional[int] = None, repeat_last_n: Optional[int] = None, repeat_penalty: Optional[float] = None, temperature: Optional[float] = None, stop: Optional[list] = None, tfs_z: Optional[float] = None, num_predict: Optional[int] = None, top_k: Optional[int] = None, top_p: Optional[float] = None, system: Optional[str] = None, template: Optional[str] = None, ) -> None: locals_ = locals() for key, value in locals_.items(): if key != "self" and value is not None: setattr(self.__class__, key, value)
@classmethod def get_config(cls): return { k: v for k, v in cls.__dict__.items() if not k.startswith("__") and not isinstance( v, ( types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod, ), ) and v is not None }
# ollama implementationdef get_ollama_response( api_base="http://localhost:11434", model="llama2", messages=None, optional_params=None, logging_obj=None, acompletion: bool = False, model_response=None, encoding=None,): if api_base.endswith("/api/chat"): url = api_base else: url = f"{api_base}/api/chat"
## Load Config config = litellm.OllamaConfig.get_config() for k, v in config.items(): if ( k not in optional_params ): # completion(top_k=3) > cohere_config(top_k=3) <- allows for dynamic variables to be passed in optional_params[k] = v
optional_params["stream"] = optional_params.get("stream", False) data = {"model": model, "messages": messages, **optional_params} ## LOGGING logging_obj.pre_call( input=None, api_key=None, additional_args={ "api_base": url, "complete_input_dict": data, "headers": {}, "acompletion": acompletion, }, ) if acompletion is True: if optional_params.get("stream", False) == True: response = ollama_async_streaming( url=url, data=data, model_response=model_response, encoding=encoding, logging_obj=logging_obj, ) else: response = ollama_acompletion( url=url, data=data, model_response=model_response, encoding=encoding, logging_obj=logging_obj, ) return response elif optional_params.get("stream", False) == True: return ollama_completion_stream(url=url, data=data, logging_obj=logging_obj)
response = requests.post( url=f"{url}", json=data, ) if response.status_code != 200: raise OllamaError(status_code=response.status_code, message=response.text)
## LOGGING logging_obj.post_call( input=messages, api_key="", original_response=response.text, additional_args={ "headers": None, "api_base": api_base, }, )
response_json = response.json()
## RESPONSE OBJECT model_response["choices"][0]["finish_reason"] = "stop" if data.get("format", "") == "json": message = litellm.Message( content=None, tool_calls=[ { "id": f"call_{str(uuid.uuid4())}", "function": { "arguments": response_json["message"]["content"], "name": "", }, "type": "function", } ], ) model_response["choices"][0]["message"] = message else: model_response["choices"][0]["message"] = response_json["message"] model_response["created"] = int(time.time()) model_response["model"] = "ollama/" + model prompt_tokens = response_json["prompt_eval_count"] # type: ignore completion_tokens = response_json["eval_count"] model_response["usage"] = litellm.Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) return model_response
def ollama_completion_stream(url, data, logging_obj): with httpx.stream( url=url, json=data, method="POST", timeout=litellm.request_timeout ) as response: try: if response.status_code != 200: raise OllamaError( status_code=response.status_code, message=response.iter_lines() )
streamwrapper = litellm.CustomStreamWrapper( completion_stream=response.iter_lines(), model=data["model"], custom_llm_provider="ollama_chat", logging_obj=logging_obj, ) for transformed_chunk in streamwrapper: yield transformed_chunk except Exception as e: raise e
async def ollama_async_streaming(url, data, model_response, encoding, logging_obj): try: client = httpx.AsyncClient() async with client.stream( url=f"{url}", json=data, method="POST", timeout=litellm.request_timeout ) as response: if response.status_code != 200: raise OllamaError( status_code=response.status_code, message=response.text )
streamwrapper = litellm.CustomStreamWrapper( completion_stream=response.aiter_lines(), model=data["model"], custom_llm_provider="ollama_chat", logging_obj=logging_obj, ) async for transformed_chunk in streamwrapper: yield transformed_chunk except Exception as e: traceback.print_exc()
async def ollama_acompletion(url, data, model_response, encoding, logging_obj): data["stream"] = False try: timeout = aiohttp.ClientTimeout(total=litellm.request_timeout) # 10 minutes async with aiohttp.ClientSession(timeout=timeout) as session: resp = await session.post(url, json=data)
if resp.status != 200: text = await resp.text() raise OllamaError(status_code=resp.status, message=text)
response_json = await resp.json()
## LOGGING logging_obj.post_call( input=data, api_key="", original_response=response_json, additional_args={ "headers": None, "api_base": url, }, )
## RESPONSE OBJECT model_response["choices"][0]["finish_reason"] = "stop" if data.get("format", "") == "json": message = litellm.Message( content=None, tool_calls=[ { "id": f"call_{str(uuid.uuid4())}", "function": { "arguments": response_json["message"]["content"], "name": "", }, "type": "function", } ], ) model_response["choices"][0]["message"] = message else: model_response["choices"][0]["message"] = response_json["message"] model_response["created"] = int(time.time()) model_response["model"] = "ollama/" + data["model"] prompt_tokens = response_json["prompt_eval_count"] # type: ignore completion_tokens = response_json["eval_count"] model_response["usage"] = litellm.Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ) return model_response except Exception as e: traceback.print_exc() raise elitellm/__init__.pyAdded+557
litellm/_logging.pyAdded+30
litellm/_redis.pyAdded+93
litellm/_version.pyAdded+6
litellm/budget_manager.pyAdded+206
litellm/caching.pyAdded+678
litellm/cost.jsonAdded+5
litellm/deprecated_litellm_server/.env.templateAdded+43
litellm/deprecated_litellm_server/DockerfileAdded+10
litellm/deprecated_litellm_server/README.mdAdded+3
litellm/deprecated_litellm_server/__init__.pyAdded+2
litellm/deprecated_litellm_server/main.pyAdded+193
litellm/deprecated_litellm_server/requirements.txtAdded+7
litellm/deprecated_litellm_server/server_utils.pyAdded+85
litellm/exceptions.pyAdded+200
litellm/integrations/__init__.pyAdded+1
litellm/integrations/aispend.pyAdded+177
litellm/integrations/berrispend.pyAdded+184
litellm/integrations/custom_logger.pyAdded+130
litellm/integrations/dynamodb.pyAdded+92
litellm/integrations/helicone.pyAdded+114
litellm/integrations/langfuse.pyAdded+191
litellm/integrations/langsmith.pyAdded+75
litellm/integrations/litedebugger.pyAdded+262
litellm/integrations/llmonitor.pyAdded+127
litellm/integrations/prompt_layer.pyAdded+72
litellm/integrations/s3.pyAdded+150
litellm/integrations/supabase.pyAdded+117
litellm/integrations/traceloop.pyAdded+114
litellm/integrations/weights_biases.pyAdded+223
litellm/llms/__init__.pyAdded+1
litellm/llms/ai21.pyAdded+212
litellm/llms/aleph_alpha.pyAdded+304
litellm/llms/anthropic.pyAdded+215
litellm/llms/azure.pyAdded+799
litellm/llms/base.pyAdded+45
litellm/llms/baseten.pyAdded+164
litellm/llms/bedrock.pyAdded+799
litellm/llms/cloudflare.pyAdded+176
litellm/llms/cohere.pyAdded+293
litellm/llms/custom_httpx/azure_dall_e_2.pyAdded+136
litellm/llms/custom_httpx/bedrock_async.pyAdded
litellm/llms/gemini.pyAdded+222
litellm/llms/huggingface_llms_metadata/hf_conversational_models.txtAdded+2523
litellm/llms/huggingface_llms_metadata/hf_text_generation_models.txtAdded
litellm/llms/huggingface_restapi.pyAdded+750
litellm/llms/maritalk.pyAdded+189
litellm/llms/nlp_cloud.pyAdded+243
litellm/llms/ollama.pyAdded+400
litellm/llms/ollama_chat.pyAdded+333