index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
64,335
litellm.llms.prompt_templates.factory
map_system_message_pt
Convert 'system' message to 'user' message if provider doesn't support 'system' role. Enabled via `completion(...,supports_system_message=False)` If next message is a user message or assistant message -> merge system prompt into it if next message is system -> append a user message instead of the system message
def map_system_message_pt(messages: list) -> list: """ Convert 'system' message to 'user' message if provider doesn't support 'system' role. Enabled via `completion(...,supports_system_message=False)` If next message is a user message or assistant message -> merge system prompt into it if next message is system -> append a user message instead of the system message """ new_messages = [] for i, m in enumerate(messages): if m["role"] == "system": if i < len(messages) - 1: # Not the last message next_m = messages[i + 1] next_role = next_m["role"] if ( next_role == "user" or next_role == "assistant" ): # Next message is a user or assistant message # Merge system prompt into the next message next_m["content"] = m["content"] + " " + next_m["content"] elif next_role == "system": # Next message is a system message # Append a user message instead of the system message new_message = {"role": "user", "content": m["content"]} new_messages.append(new_message) else: # Last message new_message = {"role": "user", "content": m["content"]} new_messages.append(new_message) else: # Not a system message new_messages.append(m) return new_messages
(messages: list) -> list
64,337
litellm.main
mock_completion
Generate a mock completion response for testing or debugging purposes. This is a helper function that simulates the response structure of the OpenAI completion API. Parameters: model (str): The name of the language model for which the mock response is generated. messages (List): A list of message objects representing the conversation context. stream (bool, optional): If True, returns a mock streaming response (default is False). mock_response (str, optional): The content of the mock response (default is "This is a mock request"). **kwargs: Additional keyword arguments that can be used but are not required. Returns: litellm.ModelResponse: A ModelResponse simulating a completion response with the specified model, messages, and mock response. Raises: Exception: If an error occurs during the generation of the mock completion response. Note: - This function is intended for testing or debugging purposes to generate mock completion responses. - If 'stream' is True, it returns a response that mimics the behavior of a streaming completion.
def mock_completion( model: str, messages: List, stream: Optional[bool] = False, mock_response: Union[str, Exception] = "This is a mock request", logging=None, **kwargs, ): """ Generate a mock completion response for testing or debugging purposes. This is a helper function that simulates the response structure of the OpenAI completion API. Parameters: model (str): The name of the language model for which the mock response is generated. messages (List): A list of message objects representing the conversation context. stream (bool, optional): If True, returns a mock streaming response (default is False). mock_response (str, optional): The content of the mock response (default is "This is a mock request"). **kwargs: Additional keyword arguments that can be used but are not required. Returns: litellm.ModelResponse: A ModelResponse simulating a completion response with the specified model, messages, and mock response. Raises: Exception: If an error occurs during the generation of the mock completion response. Note: - This function is intended for testing or debugging purposes to generate mock completion responses. - If 'stream' is True, it returns a response that mimics the behavior of a streaming completion. """ try: ## LOGGING if logging is not None: logging.pre_call( input=messages, api_key="mock-key", ) if isinstance(mock_response, Exception): raise litellm.APIError( status_code=500, # type: ignore message=str(mock_response), llm_provider="openai", # type: ignore model=model, # type: ignore request=httpx.Request(method="POST", url="https://api.openai.com/v1/"), ) model_response = ModelResponse(stream=stream) if stream is True: # don't try to access stream object, if kwargs.get("acompletion", False) == True: return CustomStreamWrapper( completion_stream=async_mock_completion_streaming_obj( model_response, mock_response=mock_response, model=model ), model=model, custom_llm_provider="openai", logging_obj=logging, ) response = mock_completion_streaming_obj( model_response, mock_response=mock_response, model=model ) return response model_response["choices"][0]["message"]["content"] = mock_response model_response["created"] = int(time.time()) model_response["model"] = model setattr( model_response, "usage", Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30), ) try: _, custom_llm_provider, _, _ = litellm.utils.get_llm_provider(model=model) model_response._hidden_params["custom_llm_provider"] = custom_llm_provider except: # dont let setting a hidden param block a mock_respose pass return model_response except: traceback.print_exc() raise Exception("Mock completion response failed")
(model: str, messages: List, stream: Optional[bool] = False, mock_response: Union[str, Exception] = 'This is a mock request', logging=None, **kwargs)
64,339
litellm.main
moderation
null
def moderation( input: str, model: Optional[str] = None, api_key: Optional[str] = None, **kwargs ): # only supports open ai for now api_key = ( api_key or litellm.api_key or litellm.openai_key or get_secret("OPENAI_API_KEY") ) openai_client = kwargs.get("client", None) if openai_client is None: openai_client = openai.OpenAI( api_key=api_key, ) response = openai_client.moderations.create(input=input, model=model) return response
(input: str, model: Optional[str] = None, api_key: Optional[str] = None, **kwargs)
64,340
litellm.utils
modify_integration
null
def modify_integration(integration_name, integration_params): global supabaseClient if integration_name == "supabase": if "table_name" in integration_params: Supabase.supabase_table_name = integration_params["table_name"]
(integration_name, integration_params)
64,349
typing_extensions
override
Indicate that a method is intended to override a method in a base class. Usage: class Base: def method(self) -> None: pass class Child(Base): @override def method(self) -> None: super().method() When this decorator is applied to a method, the type checker will validate that it overrides a method with the same name on a base class. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class. There is no runtime checking of these properties. The decorator sets the ``__override__`` attribute to ``True`` on the decorated object to allow runtime introspection. See PEP 698 for details.
def override(arg: _F, /) -> _F: """Indicate that a method is intended to override a method in a base class. Usage: class Base: def method(self) -> None: pass class Child(Base): @override def method(self) -> None: super().method() When this decorator is applied to a method, the type checker will validate that it overrides a method with the same name on a base class. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class. There is no runtime checking of these properties. The decorator sets the ``__override__`` attribute to ``True`` on the decorated object to allow runtime introspection. See PEP 698 for details. """ try: arg.__override__ = True except (AttributeError, TypeError): # Skip the attribute silently if it is not writable. # AttributeError happens if the object has __slots__ or a # read-only property, TypeError if it's a builtin class. pass return arg
(arg: ~_F, /) -> ~_F
64,353
litellm.main
print_verbose
null
def print_verbose(print_statement): try: verbose_logger.debug(print_statement) if litellm.set_verbose: print(print_statement) # noqa except: pass
(print_statement)
64,356
litellm.llms.prompt_templates.factory
prompt_factory
null
def prompt_factory( model: str, messages: list, custom_llm_provider: Optional[str] = None, api_key: Optional[str] = None, ): original_model_name = model model = model.lower() if custom_llm_provider == "ollama": return ollama_pt(model=model, messages=messages) elif custom_llm_provider == "anthropic": if model == "claude-instant-1" or model == "claude-2": return anthropic_pt(messages=messages) return anthropic_messages_pt(messages=messages) elif custom_llm_provider == "anthropic_xml": return anthropic_messages_pt_xml(messages=messages) elif custom_llm_provider == "together_ai": prompt_format, chat_template = get_model_info(token=api_key, model=model) return format_prompt_togetherai( messages=messages, prompt_format=prompt_format, chat_template=chat_template ) elif custom_llm_provider == "gemini": if ( model == "gemini-pro-vision" or litellm.supports_vision(model=model) or litellm.supports_vision(model=custom_llm_provider + "/" + model) ): return _gemini_vision_convert_messages(messages=messages) else: return gemini_text_image_pt(messages=messages) elif custom_llm_provider == "mistral": return mistral_api_pt(messages=messages) elif custom_llm_provider == "bedrock": if "amazon.titan-text" in model: return amazon_titan_pt(messages=messages) elif "anthropic." in model: if any(_ in model for _ in ["claude-2.1", "claude-v2:1"]): return claude_2_1_pt(messages=messages) else: return anthropic_pt(messages=messages) elif "mistral." in model: return mistral_instruct_pt(messages=messages) elif "llama2" in model and "chat" in model: return llama_2_chat_pt(messages=messages) elif "llama3" in model and "instruct" in model: return hf_chat_template( model="meta-llama/Meta-Llama-3-8B-Instruct", messages=messages, ) elif custom_llm_provider == "clarifai": if "claude" in model: return anthropic_pt(messages=messages) elif custom_llm_provider == "perplexity": for message in messages: message.pop("name", None) return messages elif custom_llm_provider == "azure_text": return azure_text_pt(messages=messages) elif custom_llm_provider == "watsonx": if "granite" in model and "chat" in model: # granite-13b-chat-v1 and granite-13b-chat-v2 use a specific prompt template return ibm_granite_pt(messages=messages) elif "ibm-mistral" in model and "instruct" in model: # models like ibm-mistral/mixtral-8x7b-instruct-v01-q use the mistral instruct prompt template return mistral_instruct_pt(messages=messages) elif "meta-llama/llama-3" in model and "instruct" in model: # https://llama.meta.com/docs/model-cards-and-prompt-formats/meta-llama-3/ return custom_prompt( role_dict={ "system": { "pre_message": "<|start_header_id|>system<|end_header_id|>\n", "post_message": "<|eot_id|>", }, "user": { "pre_message": "<|start_header_id|>user<|end_header_id|>\n", "post_message": "<|eot_id|>", }, "assistant": { "pre_message": "<|start_header_id|>assistant<|end_header_id|>\n", "post_message": "<|eot_id|>", }, }, messages=messages, initial_prompt_value="<|begin_of_text|>", final_prompt_value="<|start_header_id|>assistant<|end_header_id|>\n", ) try: if "meta-llama/llama-2" in model and "chat" in model: return llama_2_chat_pt(messages=messages) elif ( "meta-llama/llama-3" in model or "meta-llama-3" in model ) and "instruct" in model: return hf_chat_template( model="meta-llama/Meta-Llama-3-8B-Instruct", messages=messages, ) elif ( "tiiuae/falcon" in model ): # Note: for the instruct models, it's best to use a User: .., Assistant:.. approach in your prompt template. if model == "tiiuae/falcon-180B-chat": return falcon_chat_pt(messages=messages) elif "instruct" in model: return falcon_instruct_pt(messages=messages) elif "mosaicml/mpt" in model: if "chat" in model: return mpt_chat_pt(messages=messages) elif "codellama/codellama" in model or "togethercomputer/codellama" in model: if "instruct" in model: return llama_2_chat_pt( messages=messages ) # https://huggingface.co/blog/codellama#conversational-instructions elif "wizardlm/wizardcoder" in model: return wizardcoder_pt(messages=messages) elif "phind/phind-codellama" in model: return phind_codellama_pt(messages=messages) elif "togethercomputer/llama-2" in model and ( "instruct" in model or "chat" in model ): return llama_2_chat_pt(messages=messages) elif model in [ "gryphe/mythomax-l2-13b", "gryphe/mythomix-l2-13b", "gryphe/mythologic-l2-13b", ]: return alpaca_pt(messages=messages) elif model.strip() == "meta-llama/llamaguard-7b": chat_template = "{% if messages|length % 2 == 0 %}{% set role = 'Agent' %}{% else %}{% set role = 'User' %}{% endif %}{{ \"[INST] Task: Check if there is unsafe content in '\" + role + \"' messages in conversations according our safety policy with the below categories.\n\n<BEGIN UNSAFE CONTENT CATEGORIES>\nO1: Violence and Hate. \nShould not\n- Help people plan or engage in violence.\n- Encourage people to engage in violence.\n- Express hateful, derogatory, or demeaning sentiments against people based on sensitive personal characteristics like their race, color, religion, national origin, sexual orientation, gender, gender identity, or disability.\n- Encourage discrimination against people based on those characteristics and should not use slurs or create insults based on those characteristics.\nCan\n- Provide information on violence and discrimination.\n- Discuss the topics of hate and violence, and can discuss historical events involving violence.\nO2: Sexual Content.\nShould not\n- Engage in sexually explicit (i.e., erotic) conversations and should not encourage people to engage in sexual activities.\nCan\n- Discuss topics related to sexuality and sexual education.\n- Provide general information regarding sexual activities.\n- Provide guidance on topics related to sexual health.\nO3: Criminal Planning.\nShould not\n- Help people plan or engage in criminal activities like theft, kidnapping, or financial crimes, especially when the person indicates that they may act on the information provided to them.\n- Encourage people to engage in criminal activities or condone criminal behavior.\nCan\n- Help people understand how crimes are committed, provided that the response is not so detailed that it could be used to provide a roadmap for future crimes.\n- Help people understand how systems work that are used to prevent crimes, provided those descriptions do not provide detailed information on how to defeat those systems.\nO4: Guns and Illegal Weapons.\nShould not\n- Assist in the planning or execution of firearm or illegal weapons crimes, especially when the person indicates that they may act on the information provided to them.\n- Encourage people to engage in firearm or illegal weapons crimes or condone such behavior.\nCan\n- Discuss firearms and the arguments for and against firearm ownership.\nO5: Regulated or Controlled Substances.\nShould not\n- Encourage or assist people in the trafficking, consumption, or use of regulated or controlled substances, including but not limited to illegal drugs, tobacco, alcohol, and cannabis.\n- Assist or encourage people to create such substances when it is illegal to do so.\nCan\n- Discuss the use of regulated or controlled substances, and can provide general information on those substances (ex: what their chemical composition is and what their effects are).\n- Provide information on how those substances are manufactured, provided that the information is not so detailed as to provide step-by-step instructions for their creation.\nO6: Self-Harm.\nShould not\n- Encourage people to harm themselves.\n- Romanticize or condone self-harm or suicide.\n- Provide information regarding the methods of suicide or self-harm.\n- Provide any information or advice, other than information regarding appropriate health resources, to people who express or imply that they wish to harm themselves.\nCan\n- Provide general information regarding self-harm and suicide (ex: statistics, the mental health challenges faced by those who take these actions).\nShould\n- Provide information regarding appropriate health resources to people who imply or express the desire to harm themselves.\n<END UNSAFE CONTENT CATEGORIES>\n\n<BEGIN CONVERSATION>\n\n\" }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{% set role = 'User' %}{% elif message['role'] == 'assistant' %}{% set role = 'Agent' %}{% endif %}{{ role + ': ' + content.strip() + '\n\n' }}{% endfor %}{{ \"<END CONVERSATION>\n\nProvide your safety assessment for \" + role + \" in the above conversation:\n- First line must read 'safe' or 'unsafe'.\n- If unsafe, a second line must include a comma-separated list of violated categories. [/INST]\" }}" return hf_chat_template( model=model, messages=messages, chat_template=chat_template ) else: return hf_chat_template(original_model_name, messages) except Exception as e: return default_pt( messages=messages ) # default that covers Bloom, T-5, any non-chat tuned model (e.g. base Llama2)
(model: str, messages: list, custom_llm_provider: Optional[str] = None, api_key: Optional[str] = None)
64,360
litellm.utils
read_config_args
null
def read_config_args(config_path) -> dict: try: import os current_path = os.getcwd() with open(config_path, "r") as config_file: config = json.load(config_file) # read keys/ values from config file and return them return config except Exception as e: raise e
(config_path) -> dict
64,361
litellm.utils
register_model
Register new / Override existing models (and their pricing) to specific providers. Provide EITHER a model cost dictionary or a url to a hosted json blob Example usage: model_cost_dict = { "gpt-4": { "max_tokens": 8192, "input_cost_per_token": 0.00003, "output_cost_per_token": 0.00006, "litellm_provider": "openai", "mode": "chat" }, }
def register_model(model_cost: Union[str, dict]): """ Register new / Override existing models (and their pricing) to specific providers. Provide EITHER a model cost dictionary or a url to a hosted json blob Example usage: model_cost_dict = { "gpt-4": { "max_tokens": 8192, "input_cost_per_token": 0.00003, "output_cost_per_token": 0.00006, "litellm_provider": "openai", "mode": "chat" }, } """ loaded_model_cost = {} if isinstance(model_cost, dict): loaded_model_cost = model_cost elif isinstance(model_cost, str): loaded_model_cost = litellm.get_model_cost_map(url=model_cost) for key, value in loaded_model_cost.items(): ## override / add new keys to the existing model cost dictionary litellm.model_cost.setdefault(key, {}).update(value) verbose_logger.debug(f"{key} added to model cost map") # add new model names to provider lists if value.get("litellm_provider") == "openai": if key not in litellm.open_ai_chat_completion_models: litellm.open_ai_chat_completion_models.append(key) elif value.get("litellm_provider") == "text-completion-openai": if key not in litellm.open_ai_text_completion_models: litellm.open_ai_text_completion_models.append(key) elif value.get("litellm_provider") == "cohere": if key not in litellm.cohere_models: litellm.cohere_models.append(key) elif value.get("litellm_provider") == "anthropic": if key not in litellm.anthropic_models: litellm.anthropic_models.append(key) elif value.get("litellm_provider") == "openrouter": split_string = key.split("/", 1) if key not in litellm.openrouter_models: litellm.openrouter_models.append(split_string[1]) elif value.get("litellm_provider") == "vertex_ai-text-models": if key not in litellm.vertex_text_models: litellm.vertex_text_models.append(key) elif value.get("litellm_provider") == "vertex_ai-code-text-models": if key not in litellm.vertex_code_text_models: litellm.vertex_code_text_models.append(key) elif value.get("litellm_provider") == "vertex_ai-chat-models": if key not in litellm.vertex_chat_models: litellm.vertex_chat_models.append(key) elif value.get("litellm_provider") == "vertex_ai-code-chat-models": if key not in litellm.vertex_code_chat_models: litellm.vertex_code_chat_models.append(key) elif value.get("litellm_provider") == "ai21": if key not in litellm.ai21_models: litellm.ai21_models.append(key) elif value.get("litellm_provider") == "nlp_cloud": if key not in litellm.nlp_cloud_models: litellm.nlp_cloud_models.append(key) elif value.get("litellm_provider") == "aleph_alpha": if key not in litellm.aleph_alpha_models: litellm.aleph_alpha_models.append(key) elif value.get("litellm_provider") == "bedrock": if key not in litellm.bedrock_models: litellm.bedrock_models.append(key) return model_cost
(model_cost: Union[str, dict])
64,362
litellm.utils
register_prompt_template
Register a prompt template to follow your custom format for a given model Args: model (str): The name of the model. roles (dict): A dictionary mapping roles to their respective prompt values. initial_prompt_value (str, optional): The initial prompt value. Defaults to "". final_prompt_value (str, optional): The final prompt value. Defaults to "". Returns: dict: The updated custom prompt dictionary. Example usage: ``` import litellm litellm.register_prompt_template( model="llama-2", initial_prompt_value="You are a good assistant" # [OPTIONAL] roles={ "system": { "pre_message": "[INST] <<SYS>> ", # [OPTIONAL] "post_message": " <</SYS>> [/INST] " # [OPTIONAL] }, "user": { "pre_message": "[INST] ", # [OPTIONAL] "post_message": " [/INST]" # [OPTIONAL] }, "assistant": { "pre_message": " " # [OPTIONAL] "post_message": " " # [OPTIONAL] } } final_prompt_value="Now answer as best you can:" # [OPTIONAL] ) ```
def register_prompt_template( model: str, roles: dict, initial_prompt_value: str = "", final_prompt_value: str = "", ): """ Register a prompt template to follow your custom format for a given model Args: model (str): The name of the model. roles (dict): A dictionary mapping roles to their respective prompt values. initial_prompt_value (str, optional): The initial prompt value. Defaults to "". final_prompt_value (str, optional): The final prompt value. Defaults to "". Returns: dict: The updated custom prompt dictionary. Example usage: ``` import litellm litellm.register_prompt_template( model="llama-2", initial_prompt_value="You are a good assistant" # [OPTIONAL] roles={ "system": { "pre_message": "[INST] <<SYS>>\n", # [OPTIONAL] "post_message": "\n<</SYS>>\n [/INST]\n" # [OPTIONAL] }, "user": { "pre_message": "[INST] ", # [OPTIONAL] "post_message": " [/INST]" # [OPTIONAL] }, "assistant": { "pre_message": "\n" # [OPTIONAL] "post_message": "\n" # [OPTIONAL] } } final_prompt_value="Now answer as best you can:" # [OPTIONAL] ) ``` """ model = get_llm_provider(model=model)[0] litellm.custom_prompt_dict[model] = { "roles": roles, "initial_prompt_value": initial_prompt_value, "final_prompt_value": final_prompt_value, } return litellm.custom_prompt_dict
(model: str, roles: dict, initial_prompt_value: str = '', final_prompt_value: str = '')
64,367
litellm.assistants.main
run_thread
Run a given thread + assistant.
def run_thread( custom_llm_provider: Literal["openai"], thread_id: str, assistant_id: str, additional_instructions: Optional[str] = None, instructions: Optional[str] = None, metadata: Optional[dict] = None, model: Optional[str] = None, stream: Optional[bool] = None, tools: Optional[Iterable[AssistantToolParam]] = None, client: Optional[OpenAI] = None, **kwargs, ) -> Run: """Run a given thread + assistant.""" optional_params = GenericLiteLLMParams(**kwargs) ### TIMEOUT LOGIC ### timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 # set timeout for 10 minutes by default if ( timeout is not None and isinstance(timeout, httpx.Timeout) and supports_httpx_timeout(custom_llm_provider) == False ): read_timeout = timeout.read or 600 timeout = read_timeout # default 10 min timeout elif timeout is not None and not isinstance(timeout, httpx.Timeout): timeout = float(timeout) # type: ignore elif timeout is None: timeout = 600.0 response: Optional[Run] = None if custom_llm_provider == "openai": api_base = ( optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there or litellm.api_base or os.getenv("OPENAI_API_BASE") or "https://api.openai.com/v1" ) organization = ( optional_params.organization or litellm.organization or os.getenv("OPENAI_ORGANIZATION", None) or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 ) # set API KEY api_key = ( optional_params.api_key or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there or litellm.openai_key or os.getenv("OPENAI_API_KEY") ) response = openai_assistants_api.run_thread( thread_id=thread_id, assistant_id=assistant_id, additional_instructions=additional_instructions, instructions=instructions, metadata=metadata, model=model, stream=stream, tools=tools, api_base=api_base, api_key=api_key, timeout=timeout, max_retries=optional_params.max_retries, organization=organization, client=client, ) else: raise litellm.exceptions.BadRequestError( message="LiteLLM doesn't support {} for 'run_thread'. Only 'openai' is supported.".format( custom_llm_provider ), model="n/a", llm_provider=custom_llm_provider, response=httpx.Response( status_code=400, content="Unsupported provider", request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response
(custom_llm_provider: Literal['openai'], thread_id: str, assistant_id: str, additional_instructions: Optional[str] = None, instructions: Optional[str] = None, metadata: Optional[dict] = None, model: Optional[str] = None, stream: Optional[bool] = None, tools: Optional[Iterable[Union[openai.types.beta.code_interpreter_tool_param.CodeInterpreterToolParam, openai.types.beta.file_search_tool_param.FileSearchToolParam, openai.types.beta.function_tool_param.FunctionToolParam]]] = None, client: Optional[openai.OpenAI] = None, **kwargs) -> openai.types.beta.threads.run.Run
64,370
litellm.main
stream_chunk_builder
null
def stream_chunk_builder( chunks: list, messages: Optional[list] = None, start_time=None, end_time=None ): model_response = litellm.ModelResponse() ### SORT CHUNKS BASED ON CREATED ORDER ## print_verbose("Goes into checking if chunk has hiddden created at param") if chunks[0]._hidden_params.get("created_at", None): print_verbose("Chunks have a created at hidden param") # Sort chunks based on created_at in ascending order chunks = sorted( chunks, key=lambda x: x._hidden_params.get("created_at", float("inf")) ) print_verbose("Chunks sorted") # set hidden params from chunk to model_response if model_response is not None and hasattr(model_response, "_hidden_params"): model_response._hidden_params = chunks[0].get("_hidden_params", {}) id = chunks[0]["id"] object = chunks[0]["object"] created = chunks[0]["created"] model = chunks[0]["model"] system_fingerprint = chunks[0].get("system_fingerprint", None) if isinstance( chunks[0]["choices"][0], litellm.utils.TextChoices ): # route to the text completion logic return stream_chunk_builder_text_completion(chunks=chunks, messages=messages) role = chunks[0]["choices"][0]["delta"]["role"] finish_reason = chunks[-1]["choices"][0]["finish_reason"] # Initialize the response dictionary response = { "id": id, "object": object, "created": created, "model": model, "system_fingerprint": system_fingerprint, "choices": [ { "index": 0, "message": {"role": role, "content": ""}, "finish_reason": finish_reason, } ], "usage": { "prompt_tokens": 0, # Modify as needed "completion_tokens": 0, # Modify as needed "total_tokens": 0, # Modify as needed }, } # Extract the "content" strings from the nested dictionaries within "choices" content_list = [] combined_content = "" combined_arguments = "" if ( "tool_calls" in chunks[0]["choices"][0]["delta"] and chunks[0]["choices"][0]["delta"]["tool_calls"] is not None ): argument_list = [] delta = chunks[0]["choices"][0]["delta"] message = response["choices"][0]["message"] message["tool_calls"] = [] id = None name = None type = None tool_calls_list = [] prev_index = 0 prev_id = None curr_id = None curr_index = 0 for chunk in chunks: choices = chunk["choices"] for choice in choices: delta = choice.get("delta", {}) tool_calls = delta.get("tool_calls", "") # Check if a tool call is present if tool_calls and tool_calls[0].function is not None: if tool_calls[0].id: id = tool_calls[0].id curr_id = id if prev_id is None: prev_id = curr_id if tool_calls[0].index: curr_index = tool_calls[0].index if tool_calls[0].function.arguments: # Now, tool_calls is expected to be a dictionary arguments = tool_calls[0].function.arguments argument_list.append(arguments) if tool_calls[0].function.name: name = tool_calls[0].function.name if tool_calls[0].type: type = tool_calls[0].type if curr_index != prev_index: # new tool call combined_arguments = "".join(argument_list) tool_calls_list.append( { "id": prev_id, "index": prev_index, "function": {"arguments": combined_arguments, "name": name}, "type": type, } ) argument_list = [] # reset prev_index = curr_index prev_id = curr_id combined_arguments = "".join(argument_list) tool_calls_list.append( { "id": id, "function": {"arguments": combined_arguments, "name": name}, "type": type, } ) response["choices"][0]["message"]["content"] = None response["choices"][0]["message"]["tool_calls"] = tool_calls_list elif ( "function_call" in chunks[0]["choices"][0]["delta"] and chunks[0]["choices"][0]["delta"]["function_call"] is not None ): argument_list = [] delta = chunks[0]["choices"][0]["delta"] function_call = delta.get("function_call", "") function_call_name = function_call.name message = response["choices"][0]["message"] message["function_call"] = {} message["function_call"]["name"] = function_call_name for chunk in chunks: choices = chunk["choices"] for choice in choices: delta = choice.get("delta", {}) function_call = delta.get("function_call", "") # Check if a function call is present if function_call: # Now, function_call is expected to be a dictionary arguments = function_call.arguments argument_list.append(arguments) combined_arguments = "".join(argument_list) response["choices"][0]["message"]["content"] = None response["choices"][0]["message"]["function_call"][ "arguments" ] = combined_arguments else: for chunk in chunks: choices = chunk["choices"] for choice in choices: delta = choice.get("delta", {}) content = delta.get("content", "") if content == None: continue # openai v1.0.0 sets content = None for chunks content_list.append(content) # Combine the "content" strings into a single string || combine the 'function' strings into a single string combined_content = "".join(content_list) # Update the "content" field within the response dictionary response["choices"][0]["message"]["content"] = combined_content if len(combined_content) > 0: completion_output = combined_content elif len(combined_arguments) > 0: completion_output = combined_arguments else: completion_output = "" # # Update usage information if needed try: response["usage"]["prompt_tokens"] = token_counter( model=model, messages=messages ) except: # don't allow this failing to block a complete streaming response from being returned print_verbose(f"token_counter failed, assuming prompt tokens is 0") response["usage"]["prompt_tokens"] = 0 response["usage"]["completion_tokens"] = token_counter( model=model, text=completion_output, count_response_tokens=True, # count_response_tokens is a Flag to tell token counter this is a response, No need to add extra tokens we do for input messages ) response["usage"]["total_tokens"] = ( response["usage"]["prompt_tokens"] + response["usage"]["completion_tokens"] ) return convert_to_model_response_object( response_object=response, model_response_object=model_response, start_time=start_time, end_time=end_time, )
(chunks: list, messages: Optional[list] = None, start_time=None, end_time=None)
64,371
litellm.main
stream_chunk_builder_text_completion
null
def stream_chunk_builder_text_completion(chunks: list, messages: Optional[List] = None): id = chunks[0]["id"] object = chunks[0]["object"] created = chunks[0]["created"] model = chunks[0]["model"] system_fingerprint = chunks[0].get("system_fingerprint", None) finish_reason = chunks[-1]["choices"][0]["finish_reason"] logprobs = chunks[-1]["choices"][0]["logprobs"] response = { "id": id, "object": object, "created": created, "model": model, "system_fingerprint": system_fingerprint, "choices": [ { "text": None, "index": 0, "logprobs": logprobs, "finish_reason": finish_reason, } ], "usage": { "prompt_tokens": None, "completion_tokens": None, "total_tokens": None, }, } content_list = [] for chunk in chunks: choices = chunk["choices"] for choice in choices: if ( choice is not None and hasattr(choice, "text") and choice.get("text") is not None ): _choice = choice.get("text") content_list.append(_choice) # Combine the "content" strings into a single string || combine the 'function' strings into a single string combined_content = "".join(content_list) # Update the "content" field within the response dictionary response["choices"][0]["text"] = combined_content if len(combined_content) > 0: completion_output = combined_content else: completion_output = "" # # Update usage information if needed try: response["usage"]["prompt_tokens"] = token_counter( model=model, messages=messages ) except: # don't allow this failing to block a complete streaming response from being returned print_verbose(f"token_counter failed, assuming prompt tokens is 0") response["usage"]["prompt_tokens"] = 0 response["usage"]["completion_tokens"] = token_counter( model=model, text=combined_content, count_response_tokens=True, # count_response_tokens is a Flag to tell token counter this is a response, No need to add extra tokens we do for input messages ) response["usage"]["total_tokens"] = ( response["usage"]["prompt_tokens"] + response["usage"]["completion_tokens"] ) return response
(chunks: list, messages: Optional[List] = None)
64,373
litellm.utils
supports_function_calling
Check if the given model supports function calling and return a boolean value. Parameters: model (str): The model name to be checked. Returns: bool: True if the model supports function calling, False otherwise. Raises: Exception: If the given model is not found in model_prices_and_context_window.json.
def supports_function_calling(model: str) -> bool: """ Check if the given model supports function calling and return a boolean value. Parameters: model (str): The model name to be checked. Returns: bool: True if the model supports function calling, False otherwise. Raises: Exception: If the given model is not found in model_prices_and_context_window.json. """ if model in litellm.model_cost: model_info = litellm.model_cost[model] if model_info.get("supports_function_calling", False): return True return False else: raise Exception( f"Model not in model_prices_and_context_window.json. You passed model={model}." )
(model: str) -> bool
64,374
litellm.utils
supports_httpx_timeout
Helper function to know if a provider implementation supports httpx timeout
def supports_httpx_timeout(custom_llm_provider: str) -> bool: """ Helper function to know if a provider implementation supports httpx timeout """ supported_providers = ["openai", "azure", "bedrock"] if custom_llm_provider in supported_providers: return True return False
(custom_llm_provider: str) -> bool
64,375
litellm.utils
supports_parallel_function_calling
Check if the given model supports parallel function calling and return True if it does, False otherwise. Parameters: model (str): The model to check for support of parallel function calling. Returns: bool: True if the model supports parallel function calling, False otherwise. Raises: Exception: If the model is not found in the model_cost dictionary.
def supports_parallel_function_calling(model: str): """ Check if the given model supports parallel function calling and return True if it does, False otherwise. Parameters: model (str): The model to check for support of parallel function calling. Returns: bool: True if the model supports parallel function calling, False otherwise. Raises: Exception: If the model is not found in the model_cost dictionary. """ if model in litellm.model_cost: model_info = litellm.model_cost[model] if model_info.get("supports_parallel_function_calling", False): return True return False else: raise Exception( f"Model not in model_prices_and_context_window.json. You passed model={model}." )
(model: str)
64,376
litellm.utils
supports_vision
Check if the given model supports vision and return a boolean value. Parameters: model (str): The model name to be checked. Returns: bool: True if the model supports vision, False otherwise. Raises: Exception: If the given model is not found in model_prices_and_context_window.json.
def supports_vision(model: str): """ Check if the given model supports vision and return a boolean value. Parameters: model (str): The model name to be checked. Returns: bool: True if the model supports vision, False otherwise. Raises: Exception: If the given model is not found in model_prices_and_context_window.json. """ if model in litellm.model_cost: model_info = litellm.model_cost[model] if model_info.get("supports_vision", False): return True return False else: return False
(model: str)
64,378
litellm.main
text_completion
null
def embedding( model, input=[], # Optional params dimensions: Optional[int] = None, timeout=600, # default to 10 minutes # set api_base, api_version, api_key api_base: Optional[str] = None, api_version: Optional[str] = None, api_key: Optional[str] = None, api_type: Optional[str] = None, caching: bool = False, user: Optional[str] = None, custom_llm_provider=None, litellm_call_id=None, litellm_logging_obj=None, logger_fn=None, **kwargs, ): """ Embedding function that calls an API to generate embeddings for the given input. Parameters: - model: The embedding model to use. - input: The input for which embeddings are to be generated. - dimensions: The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models. - timeout: The timeout value for the API call, default 10 mins - litellm_call_id: The call ID for litellm logging. - litellm_logging_obj: The litellm logging object. - logger_fn: The logger function. - api_base: Optional. The base URL for the API. - api_version: Optional. The version of the API. - api_key: Optional. The API key to use. - api_type: Optional. The type of the API. - caching: A boolean indicating whether to enable caching. - custom_llm_provider: The custom llm provider. Returns: - response: The response received from the API call. Raises: - exception_type: If an exception occurs during the API call. """ azure = kwargs.get("azure", None) client = kwargs.pop("client", None) rpm = kwargs.pop("rpm", None) tpm = kwargs.pop("tpm", None) max_parallel_requests = kwargs.pop("max_parallel_requests", None) model_info = kwargs.get("model_info", None) metadata = kwargs.get("metadata", None) encoding_format = kwargs.get("encoding_format", None) proxy_server_request = kwargs.get("proxy_server_request", None) aembedding = kwargs.get("aembedding", None) ### CUSTOM MODEL COST ### input_cost_per_token = kwargs.get("input_cost_per_token", None) output_cost_per_token = kwargs.get("output_cost_per_token", None) input_cost_per_second = kwargs.get("input_cost_per_second", None) output_cost_per_second = kwargs.get("output_cost_per_second", None) openai_params = [ "user", "dimensions", "request_timeout", "api_base", "api_version", "api_key", "deployment_id", "organization", "base_url", "default_headers", "timeout", "max_retries", "encoding_format", ] litellm_params = [ "metadata", "aembedding", "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", "retry_policy", "roles", "final_prompt_value", "bos_token", "eos_token", "request_timeout", "complete_response", "self", "client", "rpm", "tpm", "max_parallel_requests", "input_cost_per_token", "output_cost_per_token", "input_cost_per_second", "output_cost_per_second", "hf_model_name", "proxy_server_request", "model_info", "preset_cache_key", "caching_groups", "ttl", "cache", "no-log", "region_name", "allowed_model_region", ] default_params = openai_params + litellm_params non_default_params = { k: v for k, v in kwargs.items() if k not in default_params } # model-specific params - pass them straight to the model/provider model, custom_llm_provider, dynamic_api_key, api_base = get_llm_provider( model=model, custom_llm_provider=custom_llm_provider, api_base=api_base, api_key=api_key, ) optional_params = get_optional_params_embeddings( model=model, user=user, dimensions=dimensions, encoding_format=encoding_format, custom_llm_provider=custom_llm_provider, **non_default_params, ) ### REGISTER CUSTOM MODEL PRICING -- IF GIVEN ### if input_cost_per_token is not None and output_cost_per_token is not None: litellm.register_model( { model: { "input_cost_per_token": input_cost_per_token, "output_cost_per_token": output_cost_per_token, "litellm_provider": custom_llm_provider, } } ) if input_cost_per_second is not None: # time based pricing just needs cost in place output_cost_per_second = output_cost_per_second or 0.0 litellm.register_model( { model: { "input_cost_per_second": input_cost_per_second, "output_cost_per_second": output_cost_per_second, "litellm_provider": custom_llm_provider, } } ) try: response = None logging = litellm_logging_obj logging.update_environment_variables( model=model, user=user, optional_params=optional_params, litellm_params={ "timeout": timeout, "azure": azure, "litellm_call_id": litellm_call_id, "logger_fn": logger_fn, "proxy_server_request": proxy_server_request, "model_info": model_info, "metadata": metadata, "aembedding": aembedding, "preset_cache_key": None, "stream_response": {}, }, ) if azure == True or custom_llm_provider == "azure": # azure configs api_type = get_secret("AZURE_API_TYPE") or "azure" api_base = api_base or litellm.api_base or get_secret("AZURE_API_BASE") api_version = ( api_version or litellm.api_version or get_secret("AZURE_API_VERSION") ) azure_ad_token = optional_params.pop("azure_ad_token", None) or get_secret( "AZURE_AD_TOKEN" ) api_key = ( api_key or litellm.api_key or litellm.azure_key or get_secret("AZURE_API_KEY") ) ## EMBEDDING CALL response = azure_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, api_version=api_version, azure_ad_token=azure_ad_token, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif ( model in litellm.open_ai_embedding_models or custom_llm_provider == "openai" ): api_base = ( api_base or litellm.api_base or get_secret("OPENAI_API_BASE") or "https://api.openai.com/v1" ) openai.organization = ( litellm.organization or get_secret("OPENAI_ORGANIZATION") or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 ) # set API KEY api_key = ( api_key or litellm.api_key or litellm.openai_key or get_secret("OPENAI_API_KEY") ) api_type = "openai" api_version = None ## EMBEDDING CALL response = openai_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "cohere": cohere_key = ( api_key or litellm.cohere_key or get_secret("COHERE_API_KEY") or get_secret("CO_API_KEY") or litellm.api_key ) response = cohere.embedding( model=model, input=input, optional_params=optional_params, encoding=encoding, api_key=cohere_key, logging_obj=logging, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "huggingface": api_key = ( api_key or litellm.huggingface_key or get_secret("HUGGINGFACE_API_KEY") or litellm.api_key ) response = huggingface.embedding( model=model, input=input, encoding=encoding, api_key=api_key, api_base=api_base, logging_obj=logging, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "bedrock": response = bedrock.embedding( model=model, input=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "triton": if api_base is None: raise ValueError( "api_base is required for triton. Please pass `api_base`" ) response = triton_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "vertex_ai": vertex_ai_project = ( optional_params.pop("vertex_project", None) or optional_params.pop("vertex_ai_project", None) or litellm.vertex_project or get_secret("VERTEXAI_PROJECT") or get_secret("VERTEX_PROJECT") ) vertex_ai_location = ( optional_params.pop("vertex_location", None) or optional_params.pop("vertex_ai_location", None) or litellm.vertex_location or get_secret("VERTEXAI_LOCATION") or get_secret("VERTEX_LOCATION") ) vertex_credentials = ( optional_params.pop("vertex_credentials", None) or optional_params.pop("vertex_ai_credentials", None) or get_secret("VERTEXAI_CREDENTIALS") or get_secret("VERTEX_CREDENTIALS") ) response = vertex_ai.embedding( model=model, input=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), vertex_project=vertex_ai_project, vertex_location=vertex_ai_location, vertex_credentials=vertex_credentials, aembedding=aembedding, print_verbose=print_verbose, ) elif custom_llm_provider == "oobabooga": response = oobabooga.embedding( model=model, input=input, encoding=encoding, api_base=api_base, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "ollama": api_base = ( litellm.api_base or api_base or get_secret("OLLAMA_API_BASE") or "http://localhost:11434" ) if isinstance(input, str): input = [input] if not all(isinstance(item, str) for item in input): raise litellm.BadRequestError( message=f"Invalid input for ollama embeddings. input={input}", model=model, # type: ignore llm_provider="ollama", # type: ignore ) ollama_embeddings_fn = ( ollama.ollama_aembeddings if aembedding else ollama.ollama_embeddings ) response = ollama_embeddings_fn( api_base=api_base, model=model, prompts=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "sagemaker": response = sagemaker.embedding( model=model, input=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), print_verbose=print_verbose, ) elif custom_llm_provider == "mistral": api_key = api_key or litellm.api_key or get_secret("MISTRAL_API_KEY") response = openai_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "voyage": api_key = api_key or litellm.api_key or get_secret("VOYAGE_API_KEY") response = openai_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "xinference": api_key = ( api_key or litellm.api_key or get_secret("XINFERENCE_API_KEY") or "stub-xinference-key" ) # xinference does not need an api key, pass a stub key if user did not set one api_base = ( api_base or litellm.api_base or get_secret("XINFERENCE_API_BASE") or "http://127.0.0.1:9997/v1" ) response = openai_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "watsonx": response = watsonx.IBMWatsonXAI().embedding( model=model, input=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), ) else: args = locals() raise ValueError(f"No valid embedding model args passed in - {args}") if response is not None and hasattr(response, "_hidden_params"): response._hidden_params["custom_llm_provider"] = custom_llm_provider return response except Exception as e: ## LOGGING logging.post_call( input=input, api_key=api_key, original_response=str(e), ) ## Map to OpenAI Exception raise exception_type( model=model, original_exception=e, custom_llm_provider=custom_llm_provider, extra_kwargs=kwargs, )
(prompt: Union[str, List[Union[str, List[Union[str, List[int]]]]]], model: Optional[str] = None, best_of: Optional[int] = None, echo: Optional[bool] = None, frequency_penalty: Optional[float] = None, logit_bias: Optional[Dict[int, int]] = None, logprobs: Optional[int] = None, max_tokens: Optional[int] = None, n: Optional[int] = None, presence_penalty: Optional[float] = None, stop: Union[str, List[str], NoneType] = None, stream: Optional[bool] = None, stream_options: Optional[dict] = None, suffix: Optional[str] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, user: Optional[str] = None, api_base: Optional[str] = None, api_version: Optional[str] = None, api_key: Optional[str] = None, model_list: Optional[list] = None, custom_llm_provider: Optional[str] = None, *args, **kwargs)
64,382
litellm.timeout
timeout
Wraps a function to raise the specified exception if execution time is greater than the specified timeout. Works with both synchronous and asynchronous callables, but with synchronous ones will introduce some overhead due to the backend use of threads and asyncio. :param float timeout_duration: Timeout duration in seconds. If none callable won't time out. :param OpenAIError exception_to_raise: Exception to raise when the callable times out. Defaults to TimeoutError. :return: The decorated function. :rtype: callable
def timeout(timeout_duration: float = 0.0, exception_to_raise=Timeout): """ Wraps a function to raise the specified exception if execution time is greater than the specified timeout. Works with both synchronous and asynchronous callables, but with synchronous ones will introduce some overhead due to the backend use of threads and asyncio. :param float timeout_duration: Timeout duration in seconds. If none callable won't time out. :param OpenAIError exception_to_raise: Exception to raise when the callable times out. Defaults to TimeoutError. :return: The decorated function. :rtype: callable """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): async def async_func(): return func(*args, **kwargs) thread = _LoopWrapper() thread.start() future = asyncio.run_coroutine_threadsafe(async_func(), thread.loop) local_timeout_duration = timeout_duration if "force_timeout" in kwargs and kwargs["force_timeout"] is not None: local_timeout_duration = kwargs["force_timeout"] elif "request_timeout" in kwargs and kwargs["request_timeout"] is not None: local_timeout_duration = kwargs["request_timeout"] try: result = future.result(timeout=local_timeout_duration) except futures.TimeoutError: thread.stop_loop() model = args[0] if len(args) > 0 else kwargs["model"] raise exception_to_raise( f"A timeout error occurred. The function call took longer than {local_timeout_duration} second(s).", model=model, # [TODO]: replace with logic for parsing out llm provider from model name llm_provider="openai", ) thread.stop_loop() return result @wraps(func) async def async_wrapper(*args, **kwargs): local_timeout_duration = timeout_duration if "force_timeout" in kwargs: local_timeout_duration = kwargs["force_timeout"] elif "request_timeout" in kwargs and kwargs["request_timeout"] is not None: local_timeout_duration = kwargs["request_timeout"] try: value = await asyncio.wait_for( func(*args, **kwargs), timeout=timeout_duration ) return value except asyncio.TimeoutError: model = args[0] if len(args) > 0 else kwargs["model"] raise exception_to_raise( f"A timeout error occurred. The function call took longer than {local_timeout_duration} second(s).", model=model, # [TODO]: replace with logic for parsing out llm provider from model name llm_provider="openai", ) if iscoroutinefunction(func): return async_wrapper return wrapper return decorator
(timeout_duration: float = 0.0, exception_to_raise=<class 'litellm.exceptions.Timeout'>)
64,384
litellm.utils
token_counter
Count the number of tokens in a given text using a specified model. Args: model (str): The name of the model to use for tokenization. Default is an empty string. custom_tokenizer (Optional[dict]): A custom tokenizer created with the `create_pretrained_tokenizer` or `create_tokenizer` method. Must be a dictionary with a string value for `type` and Tokenizer for `tokenizer`. Default is None. text (str): The raw text string to be passed to the model. Default is None. messages (Optional[List[Dict[str, str]]]): Alternative to passing in text. A list of dictionaries representing messages with "role" and "content" keys. Default is None. Returns: int: The number of tokens in the text.
def token_counter( model="", custom_tokenizer: Optional[dict] = None, text: Optional[Union[str, List[str]]] = None, messages: Optional[List] = None, count_response_tokens: Optional[bool] = False, ): """ Count the number of tokens in a given text using a specified model. Args: model (str): The name of the model to use for tokenization. Default is an empty string. custom_tokenizer (Optional[dict]): A custom tokenizer created with the `create_pretrained_tokenizer` or `create_tokenizer` method. Must be a dictionary with a string value for `type` and Tokenizer for `tokenizer`. Default is None. text (str): The raw text string to be passed to the model. Default is None. messages (Optional[List[Dict[str, str]]]): Alternative to passing in text. A list of dictionaries representing messages with "role" and "content" keys. Default is None. Returns: int: The number of tokens in the text. """ # use tiktoken, anthropic, cohere, llama2, or llama3's tokenizer depending on the model is_tool_call = False num_tokens = 0 if text == None: if messages is not None: print_verbose(f"token_counter messages received: {messages}") text = "" for message in messages: if message.get("content", None) is not None: content = message.get("content") if isinstance(content, str): text += message["content"] elif isinstance(content, List): for c in content: if c["type"] == "text": text += c["text"] elif c["type"] == "image_url": if isinstance(c["image_url"], dict): image_url_dict = c["image_url"] detail = image_url_dict.get("detail", "auto") url = image_url_dict.get("url") num_tokens += calculage_img_tokens( data=url, mode=detail ) elif isinstance(c["image_url"], str): image_url_str = c["image_url"] num_tokens += calculage_img_tokens( data=image_url_str, mode="auto" ) if "tool_calls" in message: is_tool_call = True for tool_call in message["tool_calls"]: if "function" in tool_call: function_arguments = tool_call["function"]["arguments"] text += function_arguments else: raise ValueError("text and messages cannot both be None") elif isinstance(text, List): text = "".join(t for t in text if isinstance(t, str)) elif isinstance(text, str): count_response_tokens = True # user just trying to count tokens for a text. don't add the chat_ml +3 tokens to this if model is not None or custom_tokenizer is not None: tokenizer_json = custom_tokenizer or _select_tokenizer(model=model) if tokenizer_json["type"] == "huggingface_tokenizer": print_verbose( f"Token Counter - using hugging face token counter, for model={model}" ) enc = tokenizer_json["tokenizer"].encode(text) num_tokens = len(enc.ids) elif tokenizer_json["type"] == "openai_tokenizer": if ( model in litellm.open_ai_chat_completion_models or model in litellm.azure_llms ): if model in litellm.azure_llms: # azure llms use gpt-35-turbo instead of gpt-3.5-turbo 🙃 model = model.replace("-35", "-3.5") print_verbose( f"Token Counter - using OpenAI token counter, for model={model}" ) num_tokens = openai_token_counter( text=text, # type: ignore model=model, messages=messages, is_tool_call=is_tool_call, count_response_tokens=count_response_tokens, ) else: print_verbose( f"Token Counter - using generic token counter, for model={model}" ) num_tokens = openai_token_counter( text=text, # type: ignore model="gpt-3.5-turbo", messages=messages, is_tool_call=is_tool_call, count_response_tokens=count_response_tokens, ) else: num_tokens = len(encoding.encode(text, disallowed_special=())) # type: ignore return num_tokens
(model='', custom_tokenizer: Optional[dict] = None, text: Union[str, List[str], NoneType] = None, messages: Optional[List] = None, count_response_tokens: Optional[bool] = False)
64,387
litellm.main
transcription
Calls openai + azure whisper endpoints. Allows router to load balance between them
def embedding( model, input=[], # Optional params dimensions: Optional[int] = None, timeout=600, # default to 10 minutes # set api_base, api_version, api_key api_base: Optional[str] = None, api_version: Optional[str] = None, api_key: Optional[str] = None, api_type: Optional[str] = None, caching: bool = False, user: Optional[str] = None, custom_llm_provider=None, litellm_call_id=None, litellm_logging_obj=None, logger_fn=None, **kwargs, ): """ Embedding function that calls an API to generate embeddings for the given input. Parameters: - model: The embedding model to use. - input: The input for which embeddings are to be generated. - dimensions: The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models. - timeout: The timeout value for the API call, default 10 mins - litellm_call_id: The call ID for litellm logging. - litellm_logging_obj: The litellm logging object. - logger_fn: The logger function. - api_base: Optional. The base URL for the API. - api_version: Optional. The version of the API. - api_key: Optional. The API key to use. - api_type: Optional. The type of the API. - caching: A boolean indicating whether to enable caching. - custom_llm_provider: The custom llm provider. Returns: - response: The response received from the API call. Raises: - exception_type: If an exception occurs during the API call. """ azure = kwargs.get("azure", None) client = kwargs.pop("client", None) rpm = kwargs.pop("rpm", None) tpm = kwargs.pop("tpm", None) max_parallel_requests = kwargs.pop("max_parallel_requests", None) model_info = kwargs.get("model_info", None) metadata = kwargs.get("metadata", None) encoding_format = kwargs.get("encoding_format", None) proxy_server_request = kwargs.get("proxy_server_request", None) aembedding = kwargs.get("aembedding", None) ### CUSTOM MODEL COST ### input_cost_per_token = kwargs.get("input_cost_per_token", None) output_cost_per_token = kwargs.get("output_cost_per_token", None) input_cost_per_second = kwargs.get("input_cost_per_second", None) output_cost_per_second = kwargs.get("output_cost_per_second", None) openai_params = [ "user", "dimensions", "request_timeout", "api_base", "api_version", "api_key", "deployment_id", "organization", "base_url", "default_headers", "timeout", "max_retries", "encoding_format", ] litellm_params = [ "metadata", "aembedding", "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", "retry_policy", "roles", "final_prompt_value", "bos_token", "eos_token", "request_timeout", "complete_response", "self", "client", "rpm", "tpm", "max_parallel_requests", "input_cost_per_token", "output_cost_per_token", "input_cost_per_second", "output_cost_per_second", "hf_model_name", "proxy_server_request", "model_info", "preset_cache_key", "caching_groups", "ttl", "cache", "no-log", "region_name", "allowed_model_region", ] default_params = openai_params + litellm_params non_default_params = { k: v for k, v in kwargs.items() if k not in default_params } # model-specific params - pass them straight to the model/provider model, custom_llm_provider, dynamic_api_key, api_base = get_llm_provider( model=model, custom_llm_provider=custom_llm_provider, api_base=api_base, api_key=api_key, ) optional_params = get_optional_params_embeddings( model=model, user=user, dimensions=dimensions, encoding_format=encoding_format, custom_llm_provider=custom_llm_provider, **non_default_params, ) ### REGISTER CUSTOM MODEL PRICING -- IF GIVEN ### if input_cost_per_token is not None and output_cost_per_token is not None: litellm.register_model( { model: { "input_cost_per_token": input_cost_per_token, "output_cost_per_token": output_cost_per_token, "litellm_provider": custom_llm_provider, } } ) if input_cost_per_second is not None: # time based pricing just needs cost in place output_cost_per_second = output_cost_per_second or 0.0 litellm.register_model( { model: { "input_cost_per_second": input_cost_per_second, "output_cost_per_second": output_cost_per_second, "litellm_provider": custom_llm_provider, } } ) try: response = None logging = litellm_logging_obj logging.update_environment_variables( model=model, user=user, optional_params=optional_params, litellm_params={ "timeout": timeout, "azure": azure, "litellm_call_id": litellm_call_id, "logger_fn": logger_fn, "proxy_server_request": proxy_server_request, "model_info": model_info, "metadata": metadata, "aembedding": aembedding, "preset_cache_key": None, "stream_response": {}, }, ) if azure == True or custom_llm_provider == "azure": # azure configs api_type = get_secret("AZURE_API_TYPE") or "azure" api_base = api_base or litellm.api_base or get_secret("AZURE_API_BASE") api_version = ( api_version or litellm.api_version or get_secret("AZURE_API_VERSION") ) azure_ad_token = optional_params.pop("azure_ad_token", None) or get_secret( "AZURE_AD_TOKEN" ) api_key = ( api_key or litellm.api_key or litellm.azure_key or get_secret("AZURE_API_KEY") ) ## EMBEDDING CALL response = azure_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, api_version=api_version, azure_ad_token=azure_ad_token, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif ( model in litellm.open_ai_embedding_models or custom_llm_provider == "openai" ): api_base = ( api_base or litellm.api_base or get_secret("OPENAI_API_BASE") or "https://api.openai.com/v1" ) openai.organization = ( litellm.organization or get_secret("OPENAI_ORGANIZATION") or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 ) # set API KEY api_key = ( api_key or litellm.api_key or litellm.openai_key or get_secret("OPENAI_API_KEY") ) api_type = "openai" api_version = None ## EMBEDDING CALL response = openai_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "cohere": cohere_key = ( api_key or litellm.cohere_key or get_secret("COHERE_API_KEY") or get_secret("CO_API_KEY") or litellm.api_key ) response = cohere.embedding( model=model, input=input, optional_params=optional_params, encoding=encoding, api_key=cohere_key, logging_obj=logging, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "huggingface": api_key = ( api_key or litellm.huggingface_key or get_secret("HUGGINGFACE_API_KEY") or litellm.api_key ) response = huggingface.embedding( model=model, input=input, encoding=encoding, api_key=api_key, api_base=api_base, logging_obj=logging, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "bedrock": response = bedrock.embedding( model=model, input=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "triton": if api_base is None: raise ValueError( "api_base is required for triton. Please pass `api_base`" ) response = triton_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "vertex_ai": vertex_ai_project = ( optional_params.pop("vertex_project", None) or optional_params.pop("vertex_ai_project", None) or litellm.vertex_project or get_secret("VERTEXAI_PROJECT") or get_secret("VERTEX_PROJECT") ) vertex_ai_location = ( optional_params.pop("vertex_location", None) or optional_params.pop("vertex_ai_location", None) or litellm.vertex_location or get_secret("VERTEXAI_LOCATION") or get_secret("VERTEX_LOCATION") ) vertex_credentials = ( optional_params.pop("vertex_credentials", None) or optional_params.pop("vertex_ai_credentials", None) or get_secret("VERTEXAI_CREDENTIALS") or get_secret("VERTEX_CREDENTIALS") ) response = vertex_ai.embedding( model=model, input=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), vertex_project=vertex_ai_project, vertex_location=vertex_ai_location, vertex_credentials=vertex_credentials, aembedding=aembedding, print_verbose=print_verbose, ) elif custom_llm_provider == "oobabooga": response = oobabooga.embedding( model=model, input=input, encoding=encoding, api_base=api_base, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "ollama": api_base = ( litellm.api_base or api_base or get_secret("OLLAMA_API_BASE") or "http://localhost:11434" ) if isinstance(input, str): input = [input] if not all(isinstance(item, str) for item in input): raise litellm.BadRequestError( message=f"Invalid input for ollama embeddings. input={input}", model=model, # type: ignore llm_provider="ollama", # type: ignore ) ollama_embeddings_fn = ( ollama.ollama_aembeddings if aembedding else ollama.ollama_embeddings ) response = ollama_embeddings_fn( api_base=api_base, model=model, prompts=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), ) elif custom_llm_provider == "sagemaker": response = sagemaker.embedding( model=model, input=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), print_verbose=print_verbose, ) elif custom_llm_provider == "mistral": api_key = api_key or litellm.api_key or get_secret("MISTRAL_API_KEY") response = openai_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "voyage": api_key = api_key or litellm.api_key or get_secret("VOYAGE_API_KEY") response = openai_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "xinference": api_key = ( api_key or litellm.api_key or get_secret("XINFERENCE_API_KEY") or "stub-xinference-key" ) # xinference does not need an api key, pass a stub key if user did not set one api_base = ( api_base or litellm.api_base or get_secret("XINFERENCE_API_BASE") or "http://127.0.0.1:9997/v1" ) response = openai_chat_completions.embedding( model=model, input=input, api_base=api_base, api_key=api_key, logging_obj=logging, timeout=timeout, model_response=EmbeddingResponse(), optional_params=optional_params, client=client, aembedding=aembedding, ) elif custom_llm_provider == "watsonx": response = watsonx.IBMWatsonXAI().embedding( model=model, input=input, encoding=encoding, logging_obj=logging, optional_params=optional_params, model_response=EmbeddingResponse(), ) else: args = locals() raise ValueError(f"No valid embedding model args passed in - {args}") if response is not None and hasattr(response, "_hidden_params"): response._hidden_params["custom_llm_provider"] = custom_llm_provider return response except Exception as e: ## LOGGING logging.post_call( input=input, api_key=api_key, original_response=str(e), ) ## Map to OpenAI Exception raise exception_type( model=model, original_exception=e, custom_llm_provider=custom_llm_provider, extra_kwargs=kwargs, )
(model: str, file: <class 'BinaryIO'>, language: Optional[str] = None, prompt: Optional[str] = None, response_format: Optional[Literal['json', 'text', 'srt', 'verbose_json', 'vtt']] = None, temperature: Optional[int] = None, user: Optional[str] = None, timeout=600, api_key: Optional[str] = None, api_base: Optional[str] = None, api_version: Optional[str] = None, max_retries: Optional[int] = None, litellm_logging_obj=None, custom_llm_provider=None, **kwargs)
64,390
litellm.types.router
updateDeployment
null
class updateDeployment(BaseModel): model_name: Optional[str] = None litellm_params: Optional[updateLiteLLMParams] = None model_info: Optional[ModelInfo] = None class Config: protected_namespaces = ()
(*, model_name: Optional[str] = None, litellm_params: Optional[litellm.types.router.updateLiteLLMParams] = None, model_info: Optional[litellm.types.router.ModelInfo] = None) -> None
64,419
litellm.types.router
updateLiteLLMParams
null
class updateLiteLLMParams(GenericLiteLLMParams): # This class is used to update the LiteLLM_Params # only differece is model is optional model: Optional[str] = None
(custom_llm_provider: Optional[str] = None, max_retries: Optional[int] = None, tpm: Optional[int] = None, rpm: Optional[int] = None, api_key: Optional[str] = None, api_base: Optional[str] = None, api_version: Optional[str] = None, timeout: Union[float, str, openai.Timeout, NoneType] = None, stream_timeout: Union[float, str, NoneType] = None, organization: Optional[str] = None, region_name: Optional[str] = None, vertex_project: Optional[str] = None, vertex_location: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_region_name: Optional[str] = None, watsonx_region_name: Optional[str] = None, input_cost_per_token: Optional[float] = None, output_cost_per_token: Optional[float] = None, input_cost_per_second: Optional[float] = None, output_cost_per_second: Optional[float] = None, *, model: Optional[str] = None, **params) -> None
64,452
litellm.caching
update_cache
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
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", "atranscription", "transcription", ] ] ] = [ "completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription", ], **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)}")
(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', 'atranscription', 'transcription']]] = ['completion', 'acompletion', 'embedding', 'aembedding', 'atranscription', 'transcription'], **kwargs)
64,455
litellm.utils
validate_environment
Checks if the environment variables are valid for the given model. Args: model (Optional[str]): The name of the model. Defaults to None. Returns: dict: A dictionary containing the following keys: - keys_in_environment (bool): True if all the required keys are present in the environment, False otherwise. - missing_keys (List[str]): A list of missing keys in the environment.
def validate_environment(model: Optional[str] = None) -> dict: """ Checks if the environment variables are valid for the given model. Args: model (Optional[str]): The name of the model. Defaults to None. Returns: dict: A dictionary containing the following keys: - keys_in_environment (bool): True if all the required keys are present in the environment, False otherwise. - missing_keys (List[str]): A list of missing keys in the environment. """ keys_in_environment = False missing_keys: List[str] = [] if model is None: return { "keys_in_environment": keys_in_environment, "missing_keys": missing_keys, } ## EXTRACT LLM PROVIDER - if model name provided try: _, custom_llm_provider, _, _ = get_llm_provider(model=model) except: custom_llm_provider = None # # check if llm provider part of model name # if model.split("/",1)[0] in litellm.provider_list: # custom_llm_provider = model.split("/", 1)[0] # model = model.split("/", 1)[1] # custom_llm_provider_passed_in = True if custom_llm_provider: if custom_llm_provider == "openai": if "OPENAI_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("OPENAI_API_KEY") elif custom_llm_provider == "azure": if ( "AZURE_API_BASE" in os.environ and "AZURE_API_VERSION" in os.environ and "AZURE_API_KEY" in os.environ ): keys_in_environment = True else: missing_keys.extend( ["AZURE_API_BASE", "AZURE_API_VERSION", "AZURE_API_KEY"] ) elif custom_llm_provider == "anthropic": if "ANTHROPIC_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("ANTHROPIC_API_KEY") elif custom_llm_provider == "cohere": if "COHERE_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("COHERE_API_KEY") elif custom_llm_provider == "replicate": if "REPLICATE_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("REPLICATE_API_KEY") elif custom_llm_provider == "openrouter": if "OPENROUTER_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("OPENROUTER_API_KEY") elif custom_llm_provider == "vertex_ai": if "VERTEXAI_PROJECT" in os.environ and "VERTEXAI_LOCATION" in os.environ: keys_in_environment = True else: missing_keys.extend(["VERTEXAI_PROJECT", "VERTEXAI_LOCATION"]) elif custom_llm_provider == "huggingface": if "HUGGINGFACE_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("HUGGINGFACE_API_KEY") elif custom_llm_provider == "ai21": if "AI21_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("AI21_API_KEY") elif custom_llm_provider == "together_ai": if "TOGETHERAI_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("TOGETHERAI_API_KEY") elif custom_llm_provider == "aleph_alpha": if "ALEPH_ALPHA_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("ALEPH_ALPHA_API_KEY") elif custom_llm_provider == "baseten": if "BASETEN_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("BASETEN_API_KEY") elif custom_llm_provider == "nlp_cloud": if "NLP_CLOUD_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("NLP_CLOUD_API_KEY") elif custom_llm_provider == "bedrock" or custom_llm_provider == "sagemaker": if ( "AWS_ACCESS_KEY_ID" in os.environ and "AWS_SECRET_ACCESS_KEY" in os.environ ): keys_in_environment = True else: missing_keys.append("AWS_ACCESS_KEY_ID") missing_keys.append("AWS_SECRET_ACCESS_KEY") elif custom_llm_provider in ["ollama", "ollama_chat"]: if "OLLAMA_API_BASE" in os.environ: keys_in_environment = True else: missing_keys.append("OLLAMA_API_BASE") elif custom_llm_provider == "anyscale": if "ANYSCALE_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("ANYSCALE_API_KEY") elif custom_llm_provider == "deepinfra": if "DEEPINFRA_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("DEEPINFRA_API_KEY") elif custom_llm_provider == "gemini": if "GEMINI_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("GEMINI_API_KEY") elif custom_llm_provider == "groq": if "GROQ_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("GROQ_API_KEY") elif custom_llm_provider == "deepseek": if "DEEPSEEK_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("DEEPSEEK_API_KEY") elif custom_llm_provider == "mistral": if "MISTRAL_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("MISTRAL_API_KEY") elif custom_llm_provider == "palm": if "PALM_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("PALM_API_KEY") elif custom_llm_provider == "perplexity": if "PERPLEXITYAI_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("PERPLEXITYAI_API_KEY") elif custom_llm_provider == "voyage": if "VOYAGE_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("VOYAGE_API_KEY") elif custom_llm_provider == "fireworks_ai": if ( "FIREWORKS_AI_API_KEY" in os.environ or "FIREWORKS_API_KEY" in os.environ or "FIREWORKSAI_API_KEY" in os.environ or "FIREWORKS_AI_TOKEN" in os.environ ): keys_in_environment = True else: missing_keys.append("FIREWORKS_AI_API_KEY") elif custom_llm_provider == "cloudflare": if "CLOUDFLARE_API_KEY" in os.environ and ( "CLOUDFLARE_ACCOUNT_ID" in os.environ or "CLOUDFLARE_API_BASE" in os.environ ): keys_in_environment = True else: missing_keys.append("CLOUDFLARE_API_KEY") missing_keys.append("CLOUDFLARE_API_BASE") else: ## openai - chatcompletion + text completion if ( model in litellm.open_ai_chat_completion_models or model in litellm.open_ai_text_completion_models or model in litellm.open_ai_embedding_models or model in litellm.openai_image_generation_models ): if "OPENAI_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("OPENAI_API_KEY") ## anthropic elif model in litellm.anthropic_models: if "ANTHROPIC_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("ANTHROPIC_API_KEY") ## cohere elif model in litellm.cohere_models: if "COHERE_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("COHERE_API_KEY") ## replicate elif model in litellm.replicate_models: if "REPLICATE_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("REPLICATE_API_KEY") ## openrouter elif model in litellm.openrouter_models: if "OPENROUTER_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("OPENROUTER_API_KEY") ## vertex - text + chat models elif ( model in litellm.vertex_chat_models or model in litellm.vertex_text_models or model in litellm.models_by_provider["vertex_ai"] ): if "VERTEXAI_PROJECT" in os.environ and "VERTEXAI_LOCATION" in os.environ: keys_in_environment = True else: missing_keys.extend(["VERTEXAI_PROJECT", "VERTEXAI_PROJECT"]) ## huggingface elif model in litellm.huggingface_models: if "HUGGINGFACE_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("HUGGINGFACE_API_KEY") ## ai21 elif model in litellm.ai21_models: if "AI21_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("AI21_API_KEY") ## together_ai elif model in litellm.together_ai_models: if "TOGETHERAI_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("TOGETHERAI_API_KEY") ## aleph_alpha elif model in litellm.aleph_alpha_models: if "ALEPH_ALPHA_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("ALEPH_ALPHA_API_KEY") ## baseten elif model in litellm.baseten_models: if "BASETEN_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("BASETEN_API_KEY") ## nlp_cloud elif model in litellm.nlp_cloud_models: if "NLP_CLOUD_API_KEY" in os.environ: keys_in_environment = True else: missing_keys.append("NLP_CLOUD_API_KEY") return {"keys_in_environment": keys_in_environment, "missing_keys": missing_keys}
(model: Optional[str] = None) -> dict
64,456
pydantic.deprecated.class_validators
validator
Decorate methods on the class indicating that they should be used to validate fields. Args: __field (str): The first field the validator should be called on; this is separate from `fields` to ensure an error is raised if you don't pass at least one. *fields (str): Additional field(s) the validator should be called on. pre (bool, optional): Whether this validator should be called before the standard validators (else after). Defaults to False. each_item (bool, optional): For complex objects (sets, lists etc.) whether to validate individual elements rather than the whole object. Defaults to False. always (bool, optional): Whether this method and other validators should be called even if the value is missing. Defaults to False. check_fields (bool | None, optional): Whether to check that the fields actually exist on the model. Defaults to None. allow_reuse (bool, optional): Whether to track and raise an error if another validator refers to the decorated function. Defaults to False. Returns: Callable: A decorator that can be used to decorate a function to be used as a validator.
@deprecated( 'Pydantic V1 style `@validator` validators are deprecated.' ' You should migrate to Pydantic V2 style `@field_validator` validators,' ' see the migration guide for more details', category=None, ) def validator( __field: str, *fields: str, pre: bool = False, each_item: bool = False, always: bool = False, check_fields: bool | None = None, allow_reuse: bool = False, ) -> Callable[[_V1ValidatorType], _V1ValidatorType]: """Decorate methods on the class indicating that they should be used to validate fields. Args: __field (str): The first field the validator should be called on; this is separate from `fields` to ensure an error is raised if you don't pass at least one. *fields (str): Additional field(s) the validator should be called on. pre (bool, optional): Whether this validator should be called before the standard validators (else after). Defaults to False. each_item (bool, optional): For complex objects (sets, lists etc.) whether to validate individual elements rather than the whole object. Defaults to False. always (bool, optional): Whether this method and other validators should be called even if the value is missing. Defaults to False. check_fields (bool | None, optional): Whether to check that the fields actually exist on the model. Defaults to None. allow_reuse (bool, optional): Whether to track and raise an error if another validator refers to the decorated function. Defaults to False. Returns: Callable: A decorator that can be used to decorate a function to be used as a validator. """ warn( 'Pydantic V1 style `@validator` validators are deprecated.' ' You should migrate to Pydantic V2 style `@field_validator` validators,' ' see the migration guide for more details', DeprecationWarning, stacklevel=2, ) if allow_reuse is True: # pragma: no cover warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning) fields = tuple((__field, *fields)) if isinstance(fields[0], FunctionType): raise PydanticUserError( '`@validator` should be used with fields and keyword arguments, not bare. ' "E.g. usage should be `@validator('<field_name>', ...)`", code='validator-no-fields', ) elif not all(isinstance(field, str) for field in fields): raise PydanticUserError( '`@validator` fields should be passed as separate string args. ' "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`", code='validator-invalid-fields', ) mode: Literal['before', 'after'] = 'before' if pre is True else 'after' def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]: if _decorators.is_instance_method_from_sig(f): raise PydanticUserError( '`@validator` cannot be applied to instance methods', code='validator-instance-method' ) # auto apply the @classmethod decorator f = _decorators.ensure_classmethod_based_on_signature(f) wrap = _decorators_v1.make_generic_v1_field_validator validator_wrapper_info = _decorators.ValidatorDecoratorInfo( fields=fields, mode=mode, each_item=each_item, always=always, check_fields=check_fields, ) return _decorators.PydanticDescriptorProxy(f, validator_wrapper_info, shim=wrap) return dec # type: ignore[return-value]
(__field: 'str', *fields: 'str', pre: 'bool' = False, each_item: 'bool' = False, always: 'bool' = False, check_fields: 'bool | None' = None, allow_reuse: 'bool' = False) -> 'Callable[[_V1ValidatorType], _V1ValidatorType]'
64,463
sniffio._impl
AsyncLibraryNotFoundError
null
class AsyncLibraryNotFoundError(RuntimeError): pass
null
64,466
sniffio._impl
current_async_library
Detect which async library is currently running. The following libraries are currently supported: ================ =========== ============================ Library Requires Magic string ================ =========== ============================ **Trio** Trio v0.6+ ``"trio"`` **Curio** - ``"curio"`` **asyncio** ``"asyncio"`` **Trio-asyncio** v0.8.2+ ``"trio"`` or ``"asyncio"``, depending on current mode ================ =========== ============================ Returns: A string like ``"trio"``. Raises: AsyncLibraryNotFoundError: if called from synchronous context, or if the current async library was not recognized. Examples: .. code-block:: python3 from sniffio import current_async_library async def generic_sleep(seconds): library = current_async_library() if library == "trio": import trio await trio.sleep(seconds) elif library == "asyncio": import asyncio await asyncio.sleep(seconds) # ... and so on ... else: raise RuntimeError(f"Unsupported library {library!r}")
def current_async_library() -> str: """Detect which async library is currently running. The following libraries are currently supported: ================ =========== ============================ Library Requires Magic string ================ =========== ============================ **Trio** Trio v0.6+ ``"trio"`` **Curio** - ``"curio"`` **asyncio** ``"asyncio"`` **Trio-asyncio** v0.8.2+ ``"trio"`` or ``"asyncio"``, depending on current mode ================ =========== ============================ Returns: A string like ``"trio"``. Raises: AsyncLibraryNotFoundError: if called from synchronous context, or if the current async library was not recognized. Examples: .. code-block:: python3 from sniffio import current_async_library async def generic_sleep(seconds): library = current_async_library() if library == "trio": import trio await trio.sleep(seconds) elif library == "asyncio": import asyncio await asyncio.sleep(seconds) # ... and so on ... else: raise RuntimeError(f"Unsupported library {library!r}") """ value = thread_local.name if value is not None: return value value = current_async_library_cvar.get() if value is not None: return value # Need to sniff for asyncio if "asyncio" in sys.modules: import asyncio try: current_task = asyncio.current_task # type: ignore[attr-defined] except AttributeError: current_task = asyncio.Task.current_task # type: ignore[attr-defined] try: if current_task() is not None: return "asyncio" except RuntimeError: pass # Sniff for curio (for now) if 'curio' in sys.modules: from curio.meta import curio_running if curio_running(): return 'curio' raise AsyncLibraryNotFoundError( "unknown async library, or not in async context" )
() -> str
64,467
chromedriver_py
_get_filename
null
def _get_filename(): path = os.path.join(_BASE_DIR, "chromedriver_") machine = platform.machine().lower() sys = platform.system().lower() # windows if sys == "windows": if machine.endswith("64"): path += "win64.exe" else: path += "win32.exe" # mac elif sys == "darwin": path += "mac" if "arm" in machine: path += "-arm64" else: path += "-x64" # linux elif sys == "linux": if "arm" in machine: raise Exception("Google doesn't compile chromedriver versions for Linux ARM. Sorry!") if machine.endswith("32"): raise Exception("Google doesn't compile 32bit chromedriver versions for Linux. Sorry!") path += "linux64" # undefined else: raise Exception("Could not identify your system: " + sys) if not path or not os.path.isfile(path): msg = "Couldn't find a binary for your system: " + sys + " / " + machine + ". " msg += "Please create an Issue on github.com/breuerfelix/chromedriver-py and include this Message." raise Exception(msg) return path
()
64,470
dynamodb_encryption_sdk.encrypted.client
EncryptedClient
High-level helper class to provide a familiar interface to encrypted tables. >>> import boto3 >>> from dynamodb_encryption_sdk.encrypted.client import EncryptedClient >>> from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider >>> client = boto3.client('dynamodb') >>> aws_kms_cmp = AwsKmsCryptographicMaterialsProvider('alias/MyKmsAlias') >>> encrypted_client = EncryptedClient( ... client=client, ... materials_provider=aws_kms_cmp ... ) .. note:: This class provides a superset of the boto3 DynamoDB client API, so should work as a drop-in replacement once configured. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#client If you want to provide per-request cryptographic details, the ``put_item``, ``get_item``, ``query``, ``scan``, ``batch_write_item``, and ``batch_get_item`` methods will also accept a ``crypto_config`` parameter, defining a custom :class:`CryptoConfig` instance for this request. .. warning:: We do not currently support the ``update_item`` method. :param client: Pre-configured boto3 DynamoDB client object :type client: boto3.resources.base.BaseClient :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param bool auto_refresh_table_indexes: Should we attempt to refresh information about table indexes? Requires ``dynamodb:DescribeTable`` permissions on each table. (default: True) :param bool expect_standard_dictionaries: Should we expect items to be standard Python dictionaries? This should only be set to True if you are using a client obtained from a service resource or table resource (ex: ``table.meta.client``). (default: False)
class EncryptedClient(object): # pylint: disable=too-few-public-methods,too-many-instance-attributes """High-level helper class to provide a familiar interface to encrypted tables. >>> import boto3 >>> from dynamodb_encryption_sdk.encrypted.client import EncryptedClient >>> from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider >>> client = boto3.client('dynamodb') >>> aws_kms_cmp = AwsKmsCryptographicMaterialsProvider('alias/MyKmsAlias') >>> encrypted_client = EncryptedClient( ... client=client, ... materials_provider=aws_kms_cmp ... ) .. note:: This class provides a superset of the boto3 DynamoDB client API, so should work as a drop-in replacement once configured. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#client If you want to provide per-request cryptographic details, the ``put_item``, ``get_item``, ``query``, ``scan``, ``batch_write_item``, and ``batch_get_item`` methods will also accept a ``crypto_config`` parameter, defining a custom :class:`CryptoConfig` instance for this request. .. warning:: We do not currently support the ``update_item`` method. :param client: Pre-configured boto3 DynamoDB client object :type client: boto3.resources.base.BaseClient :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param bool auto_refresh_table_indexes: Should we attempt to refresh information about table indexes? Requires ``dynamodb:DescribeTable`` permissions on each table. (default: True) :param bool expect_standard_dictionaries: Should we expect items to be standard Python dictionaries? This should only be set to True if you are using a client obtained from a service resource or table resource (ex: ``table.meta.client``). (default: False) """ _client = attr.ib(validator=attr.validators.instance_of(botocore.client.BaseClient)) _materials_provider = attr.ib(validator=attr.validators.instance_of(CryptographicMaterialsProvider)) _attribute_actions = attr.ib( validator=attr.validators.instance_of(AttributeActions), default=attr.Factory(AttributeActions) ) _auto_refresh_table_indexes = attr.ib(validator=attr.validators.instance_of(bool), default=True) _expect_standard_dictionaries = attr.ib(validator=attr.validators.instance_of(bool), default=False) def __init__( self, client, # type: botocore.client.BaseClient materials_provider, # type: CryptographicMaterialsProvider attribute_actions=None, # type: Optional[AttributeActions] auto_refresh_table_indexes=True, # type: Optional[bool] expect_standard_dictionaries=False, # type: Optional[bool] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if attribute_actions is None: attribute_actions = AttributeActions() self._client = client self._materials_provider = materials_provider self._attribute_actions = attribute_actions self._auto_refresh_table_indexes = auto_refresh_table_indexes self._expect_standard_dictionaries = expect_standard_dictionaries attr.validate(self) self.__attrs_post_init__() def __attrs_post_init__(self): """Set up the table info cache and translation methods.""" if self._expect_standard_dictionaries: self._encrypt_item = encrypt_python_item # attrs confuses pylint: disable=attribute-defined-outside-init self._decrypt_item = decrypt_python_item # attrs confuses pylint: disable=attribute-defined-outside-init else: self._encrypt_item = encrypt_dynamodb_item # attrs confuses pylint: disable=attribute-defined-outside-init self._decrypt_item = decrypt_dynamodb_item # attrs confuses pylint: disable=attribute-defined-outside-init self._table_info_cache = TableInfoCache( # attrs confuses pylint: disable=attribute-defined-outside-init client=self._client, auto_refresh_table_indexes=self._auto_refresh_table_indexes ) self._table_crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_cache, self._materials_provider, self._attribute_actions, self._table_info_cache ) self._item_crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_kwargs, self._table_crypto_config ) self.get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_get_item, self._decrypt_item, self._item_crypto_config, self._client.get_item ) self.put_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_put_item, self._encrypt_item, self._item_crypto_config, self._client.put_item ) self.query = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, self._decrypt_item, self._item_crypto_config, self._client.query ) self.scan = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, self._decrypt_item, self._item_crypto_config, self._client.scan ) self.batch_get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_batch_get_item, self._decrypt_item, self._table_crypto_config, self._client.batch_get_item ) self.batch_write_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_batch_write_item, self._encrypt_item, self._table_crypto_config, self._client.batch_write_item ) def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided client object. :param str name: Attribute name :returns: Result of asking the provided client object for that attribute name :raises AttributeError: if attribute is not found on provided client object """ return getattr(self._client, name) def update_item(self, **kwargs): """Update item is not yet supported. :raises NotImplementedError: if called """ raise NotImplementedError('"update_item" is not yet implemented') def get_paginator(self, operation_name): """Get a paginator from the underlying client. If the paginator requested is for "scan" or "query", the paginator returned will transparently decrypt the returned items. :param str operation_name: Name of operation for which to get paginator :returns: Paginator for name :rtype: :class:`botocore.paginate.Paginator` or :class:`EncryptedPaginator` """ paginator = self._client.get_paginator(operation_name) if operation_name in ("scan", "query"): return EncryptedPaginator( paginator=paginator, decrypt_method=self._decrypt_item, crypto_config_method=self._item_crypto_config ) return paginator
(client, materials_provider, attribute_actions=None, auto_refresh_table_indexes=True, expect_standard_dictionaries=False)
64,471
dynamodb_encryption_sdk.encrypted.client
__attrs_init__
Method generated by attrs for class EncryptedClient.
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. """High-level helper class to provide a familiar interface to encrypted tables.""" from functools import partial import attr import botocore from dynamodb_encryption_sdk.internal.utils import ( TableInfoCache, crypto_config_from_cache, crypto_config_from_kwargs, decrypt_batch_get_item, decrypt_get_item, decrypt_list_of_items, decrypt_multi_get, encrypt_batch_write_item, encrypt_put_item, validate_get_arguments, ) from dynamodb_encryption_sdk.internal.validators import callable_validator from dynamodb_encryption_sdk.material_providers import CryptographicMaterialsProvider from dynamodb_encryption_sdk.structures import AttributeActions from .item import decrypt_dynamodb_item, decrypt_python_item, encrypt_dynamodb_item, encrypt_python_item try: # Python 3.5.0 and 3.5.1 have incompatible typing modules from typing import Any, Callable, Dict, Iterator, Optional # noqa pylint: disable=unused-import except ImportError: # pragma: no cover # We only actually need these imports when running the mypy checks pass __all__ = ("EncryptedClient", "EncryptedPaginator") @attr.s(init=False) class EncryptedPaginator(object): """Paginator that decrypts returned items before returning them. :param paginator: Pre-configured boto3 DynamoDB paginator object :type paginator: botocore.paginate.Paginator :param decrypt_method: Item decryptor method from :mod:`dynamodb_encryption_sdk.encrypted.item` :param callable crypto_config_method: Callable that returns a :class:`CryptoConfig` """ _paginator = attr.ib(validator=attr.validators.instance_of(botocore.paginate.Paginator)) _decrypt_method = attr.ib() _crypto_config_method = attr.ib(validator=callable_validator) def __init__( self, paginator, # type: botocore.paginate.Paginator decrypt_method, # type: Callable crypto_config_method, # type: Callable ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self._paginator = paginator self._decrypt_method = decrypt_method self._crypto_config_method = crypto_config_method attr.validate(self) @_decrypt_method.validator def validate_decrypt_method(self, attribute, value): # pylint: disable=unused-argument """Validate that _decrypt_method is one of the item encryptors.""" if self._decrypt_method not in (decrypt_python_item, decrypt_dynamodb_item): raise ValueError( '"{name}" must be an item decryptor from dynamodb_encryption_sdk.encrypted.item'.format( name=attribute.name ) ) def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided client object. :param str name: Attribute name :returns: Result of asking the provided client object for that attribute name :raises AttributeError: if attribute is not found on provided client object """ return getattr(self._paginator, name) def paginate(self, **kwargs): # type: (**Any) -> Iterator[Dict] # narrow this down # https://github.com/aws/aws-dynamodb-encryption-python/issues/66 """Create an iterator that will paginate through responses from the underlying paginator, transparently decrypting any returned items. """ validate_get_arguments(kwargs) crypto_config, ddb_kwargs = self._crypto_config_method(**kwargs) for page in self._paginator.paginate(**ddb_kwargs): page["Items"] = list( decrypt_list_of_items( crypto_config=crypto_config, decrypt_method=self._decrypt_method, items=page["Items"] ) ) yield page
(self, client, materials_provider, attribute_actions=NOTHING, auto_refresh_table_indexes=True, expect_standard_dictionaries=False) -> NoneType
64,472
dynamodb_encryption_sdk.encrypted.client
__attrs_post_init__
Set up the table info cache and translation methods.
def __attrs_post_init__(self): """Set up the table info cache and translation methods.""" if self._expect_standard_dictionaries: self._encrypt_item = encrypt_python_item # attrs confuses pylint: disable=attribute-defined-outside-init self._decrypt_item = decrypt_python_item # attrs confuses pylint: disable=attribute-defined-outside-init else: self._encrypt_item = encrypt_dynamodb_item # attrs confuses pylint: disable=attribute-defined-outside-init self._decrypt_item = decrypt_dynamodb_item # attrs confuses pylint: disable=attribute-defined-outside-init self._table_info_cache = TableInfoCache( # attrs confuses pylint: disable=attribute-defined-outside-init client=self._client, auto_refresh_table_indexes=self._auto_refresh_table_indexes ) self._table_crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_cache, self._materials_provider, self._attribute_actions, self._table_info_cache ) self._item_crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_kwargs, self._table_crypto_config ) self.get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_get_item, self._decrypt_item, self._item_crypto_config, self._client.get_item ) self.put_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_put_item, self._encrypt_item, self._item_crypto_config, self._client.put_item ) self.query = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, self._decrypt_item, self._item_crypto_config, self._client.query ) self.scan = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, self._decrypt_item, self._item_crypto_config, self._client.scan ) self.batch_get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_batch_get_item, self._decrypt_item, self._table_crypto_config, self._client.batch_get_item ) self.batch_write_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_batch_write_item, self._encrypt_item, self._table_crypto_config, self._client.batch_write_item )
(self)
64,474
dynamodb_encryption_sdk.encrypted.client
__ge__
Method generated by attrs for class EncryptedClient.
null
(self, other)
64,475
dynamodb_encryption_sdk.encrypted.client
__getattr__
Catch any method/attribute lookups that are not defined in this class and try to find them on the provided client object. :param str name: Attribute name :returns: Result of asking the provided client object for that attribute name :raises AttributeError: if attribute is not found on provided client object
def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided client object. :param str name: Attribute name :returns: Result of asking the provided client object for that attribute name :raises AttributeError: if attribute is not found on provided client object """ return getattr(self._client, name)
(self, name)
64,477
dynamodb_encryption_sdk.encrypted.client
__init__
null
def __init__( self, client, # type: botocore.client.BaseClient materials_provider, # type: CryptographicMaterialsProvider attribute_actions=None, # type: Optional[AttributeActions] auto_refresh_table_indexes=True, # type: Optional[bool] expect_standard_dictionaries=False, # type: Optional[bool] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if attribute_actions is None: attribute_actions = AttributeActions() self._client = client self._materials_provider = materials_provider self._attribute_actions = attribute_actions self._auto_refresh_table_indexes = auto_refresh_table_indexes self._expect_standard_dictionaries = expect_standard_dictionaries attr.validate(self) self.__attrs_post_init__()
(self, client, materials_provider, attribute_actions=None, auto_refresh_table_indexes=True, expect_standard_dictionaries=False)
64,482
dynamodb_encryption_sdk.encrypted.client
get_paginator
Get a paginator from the underlying client. If the paginator requested is for "scan" or "query", the paginator returned will transparently decrypt the returned items. :param str operation_name: Name of operation for which to get paginator :returns: Paginator for name :rtype: :class:`botocore.paginate.Paginator` or :class:`EncryptedPaginator`
def get_paginator(self, operation_name): """Get a paginator from the underlying client. If the paginator requested is for "scan" or "query", the paginator returned will transparently decrypt the returned items. :param str operation_name: Name of operation for which to get paginator :returns: Paginator for name :rtype: :class:`botocore.paginate.Paginator` or :class:`EncryptedPaginator` """ paginator = self._client.get_paginator(operation_name) if operation_name in ("scan", "query"): return EncryptedPaginator( paginator=paginator, decrypt_method=self._decrypt_item, crypto_config_method=self._item_crypto_config ) return paginator
(self, operation_name)
64,483
dynamodb_encryption_sdk.encrypted.client
update_item
Update item is not yet supported. :raises NotImplementedError: if called
def update_item(self, **kwargs): """Update item is not yet supported. :raises NotImplementedError: if called """ raise NotImplementedError('"update_item" is not yet implemented')
(self, **kwargs)
64,484
dynamodb_encryption_sdk.encrypted.resource
EncryptedResource
High-level helper class to provide a familiar interface to encrypted tables. >>> import boto3 >>> from dynamodb_encryption_sdk.encrypted.resource import EncryptedResource >>> from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider >>> resource = boto3.resource('dynamodb') >>> aws_kms_cmp = AwsKmsCryptographicMaterialsProvider('alias/MyKmsAlias') >>> encrypted_resource = EncryptedResource( ... resource=resource, ... materials_provider=aws_kms_cmp ... ) .. note:: This class provides a superset of the boto3 DynamoDB service resource API, so should work as a drop-in replacement once configured. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#service-resource If you want to provide per-request cryptographic details, the ``batch_write_item`` and ``batch_get_item`` methods will also accept a ``crypto_config`` parameter, defining a custom :class:`CryptoConfig` instance for this request. :param resource: Pre-configured boto3 DynamoDB service resource object :type resource: boto3.resources.base.ServiceResource :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param bool auto_refresh_table_indexes: Should we attempt to refresh information about table indexes? Requires ``dynamodb:DescribeTable`` permissions on each table. (default: True)
class EncryptedResource(object): # pylint: disable=too-few-public-methods,too-many-instance-attributes """High-level helper class to provide a familiar interface to encrypted tables. >>> import boto3 >>> from dynamodb_encryption_sdk.encrypted.resource import EncryptedResource >>> from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider >>> resource = boto3.resource('dynamodb') >>> aws_kms_cmp = AwsKmsCryptographicMaterialsProvider('alias/MyKmsAlias') >>> encrypted_resource = EncryptedResource( ... resource=resource, ... materials_provider=aws_kms_cmp ... ) .. note:: This class provides a superset of the boto3 DynamoDB service resource API, so should work as a drop-in replacement once configured. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#service-resource If you want to provide per-request cryptographic details, the ``batch_write_item`` and ``batch_get_item`` methods will also accept a ``crypto_config`` parameter, defining a custom :class:`CryptoConfig` instance for this request. :param resource: Pre-configured boto3 DynamoDB service resource object :type resource: boto3.resources.base.ServiceResource :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param bool auto_refresh_table_indexes: Should we attempt to refresh information about table indexes? Requires ``dynamodb:DescribeTable`` permissions on each table. (default: True) """ _resource = attr.ib(validator=attr.validators.instance_of(ServiceResource)) _materials_provider = attr.ib(validator=attr.validators.instance_of(CryptographicMaterialsProvider)) _attribute_actions = attr.ib( validator=attr.validators.instance_of(AttributeActions), default=attr.Factory(AttributeActions) ) _auto_refresh_table_indexes = attr.ib(validator=attr.validators.instance_of(bool), default=True) def __init__( self, resource, # type: ServiceResource materials_provider, # type: CryptographicMaterialsProvider attribute_actions=None, # type: Optional[AttributeActions] auto_refresh_table_indexes=True, # type: Optional[bool] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if attribute_actions is None: attribute_actions = AttributeActions() self._resource = resource self._materials_provider = materials_provider self._attribute_actions = attribute_actions self._auto_refresh_table_indexes = auto_refresh_table_indexes attr.validate(self) self.__attrs_post_init__() def __attrs_post_init__(self): """Set up the table info cache, encrypted tables collection manager, and translation methods.""" self._table_info_cache = TableInfoCache( # attrs confuses pylint: disable=attribute-defined-outside-init client=self._resource.meta.client, auto_refresh_table_indexes=self._auto_refresh_table_indexes ) self._crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_cache, self._materials_provider, self._attribute_actions, self._table_info_cache ) self.tables = EncryptedTablesCollectionManager( # attrs confuses pylint: disable=attribute-defined-outside-init collection=self._resource.tables, materials_provider=self._materials_provider, attribute_actions=self._attribute_actions, table_info_cache=self._table_info_cache, ) self.batch_get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_batch_get_item, decrypt_python_item, self._crypto_config, self._resource.batch_get_item ) self.batch_write_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_batch_write_item, encrypt_python_item, self._crypto_config, self._resource.batch_write_item ) def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided resource object. :param str name: Attribute name :returns: Result of asking the provided resource object for that attribute name :raises AttributeError: if attribute is not found on provided resource object """ return getattr(self._resource, name) def Table(self, name, **kwargs): # naming chosen to align with boto3 resource name, so pylint: disable=invalid-name """Creates an EncryptedTable resource. If any of the optional configuration values are not provided, the corresponding values for this ``EncryptedResource`` will be used. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.ServiceResource.Table :param name: The table name. :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use (optional) :param TableInfo table_info: Information about the target DynamoDB table (optional) :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes (optional) """ table_kwargs = dict( table=self._resource.Table(name), materials_provider=kwargs.get("materials_provider", self._materials_provider), attribute_actions=kwargs.get("attribute_actions", self._attribute_actions), auto_refresh_table_indexes=kwargs.get("auto_refresh_table_indexes", self._auto_refresh_table_indexes), table_info=self._table_info_cache.table_info(name), ) return EncryptedTable(**table_kwargs)
(resource, materials_provider, attribute_actions=None, auto_refresh_table_indexes=True)
64,485
dynamodb_encryption_sdk.encrypted.resource
Table
Creates an EncryptedTable resource. If any of the optional configuration values are not provided, the corresponding values for this ``EncryptedResource`` will be used. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.ServiceResource.Table :param name: The table name. :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use (optional) :param TableInfo table_info: Information about the target DynamoDB table (optional) :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes (optional)
def Table(self, name, **kwargs): # naming chosen to align with boto3 resource name, so pylint: disable=invalid-name """Creates an EncryptedTable resource. If any of the optional configuration values are not provided, the corresponding values for this ``EncryptedResource`` will be used. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.ServiceResource.Table :param name: The table name. :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use (optional) :param TableInfo table_info: Information about the target DynamoDB table (optional) :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes (optional) """ table_kwargs = dict( table=self._resource.Table(name), materials_provider=kwargs.get("materials_provider", self._materials_provider), attribute_actions=kwargs.get("attribute_actions", self._attribute_actions), auto_refresh_table_indexes=kwargs.get("auto_refresh_table_indexes", self._auto_refresh_table_indexes), table_info=self._table_info_cache.table_info(name), ) return EncryptedTable(**table_kwargs)
(self, name, **kwargs)
64,486
dynamodb_encryption_sdk.encrypted.resource
__attrs_init__
Method generated by attrs for class EncryptedResource.
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. """High-level helper class to provide a familiar interface to encrypted tables.""" from functools import partial import attr from boto3.resources.base import ServiceResource from boto3.resources.collection import CollectionManager from dynamodb_encryption_sdk.internal.utils import ( TableInfoCache, crypto_config_from_cache, decrypt_batch_get_item, encrypt_batch_write_item, ) from dynamodb_encryption_sdk.material_providers import CryptographicMaterialsProvider from dynamodb_encryption_sdk.structures import AttributeActions from .item import decrypt_python_item, encrypt_python_item from .table import EncryptedTable try: # Python 3.5.0 and 3.5.1 have incompatible typing modules from typing import Optional # noqa pylint: disable=unused-import except ImportError: # pragma: no cover # We only actually need these imports when running the mypy checks pass __all__ = ("EncryptedResource", "EncryptedTablesCollectionManager") @attr.s(init=False) class EncryptedTablesCollectionManager(object): # pylint: disable=too-few-public-methods,too-many-instance-attributes """Tables collection manager that provides :class:`EncryptedTable` objects. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.ServiceResource.tables :param collection: Pre-configured boto3 DynamoDB table collection manager :type collection: boto3.resources.collection.CollectionManager :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param TableInfoCache table_info_cache: Local cache from which to obtain TableInfo data """ _collection = attr.ib(validator=attr.validators.instance_of(CollectionManager)) _materials_provider = attr.ib(validator=attr.validators.instance_of(CryptographicMaterialsProvider)) _attribute_actions = attr.ib(validator=attr.validators.instance_of(AttributeActions)) _table_info_cache = attr.ib(validator=attr.validators.instance_of(TableInfoCache)) def __init__( self, collection, # type: CollectionManager materials_provider, # type: CryptographicMaterialsProvider attribute_actions, # type: AttributeActions table_info_cache, # type: TableInfoCache ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self._collection = collection self._materials_provider = materials_provider self._attribute_actions = attribute_actions self._table_info_cache = table_info_cache attr.validate(self) self.__attrs_post_init__() def __attrs_post_init__(self): """Set up the translation methods.""" self.all = partial( # attrs confuses pylint: disable=attribute-defined-outside-init self._transform_table, self._collection.all ) self.filter = partial( # attrs confuses pylint: disable=attribute-defined-outside-init self._transform_table, self._collection.filter ) self.limit = partial( # attrs confuses pylint: disable=attribute-defined-outside-init self._transform_table, self._collection.limit ) self.page_size = partial( # attrs confuses pylint: disable=attribute-defined-outside-init self._transform_table, self._collection.page_size ) def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided collection object. :param str name: Attribute name :returns: Result of asking the provided collection object for that attribute name :raises AttributeError: if attribute is not found on provided collection object """ return getattr(self._collection, name) def _transform_table(self, method, **kwargs): """Transform a Table from the underlying collection manager to an EncryptedTable. :param method: Method on underlying collection manager to call :type method: callable :param **kwargs: Keyword arguments to pass to ``method`` """ for table in method(**kwargs): yield EncryptedTable( table=table, materials_provider=self._materials_provider, table_info=self._table_info_cache.table_info(table.name), attribute_actions=self._attribute_actions, )
(self, resource, materials_provider, attribute_actions=NOTHING, auto_refresh_table_indexes=True) -> NoneType
64,487
dynamodb_encryption_sdk.encrypted.resource
__attrs_post_init__
Set up the table info cache, encrypted tables collection manager, and translation methods.
def __attrs_post_init__(self): """Set up the table info cache, encrypted tables collection manager, and translation methods.""" self._table_info_cache = TableInfoCache( # attrs confuses pylint: disable=attribute-defined-outside-init client=self._resource.meta.client, auto_refresh_table_indexes=self._auto_refresh_table_indexes ) self._crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_cache, self._materials_provider, self._attribute_actions, self._table_info_cache ) self.tables = EncryptedTablesCollectionManager( # attrs confuses pylint: disable=attribute-defined-outside-init collection=self._resource.tables, materials_provider=self._materials_provider, attribute_actions=self._attribute_actions, table_info_cache=self._table_info_cache, ) self.batch_get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_batch_get_item, decrypt_python_item, self._crypto_config, self._resource.batch_get_item ) self.batch_write_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_batch_write_item, encrypt_python_item, self._crypto_config, self._resource.batch_write_item )
(self)
64,489
dynamodb_encryption_sdk.encrypted.resource
__ge__
Method generated by attrs for class EncryptedResource.
null
(self, other)
64,490
dynamodb_encryption_sdk.encrypted.resource
__getattr__
Catch any method/attribute lookups that are not defined in this class and try to find them on the provided resource object. :param str name: Attribute name :returns: Result of asking the provided resource object for that attribute name :raises AttributeError: if attribute is not found on provided resource object
def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided resource object. :param str name: Attribute name :returns: Result of asking the provided resource object for that attribute name :raises AttributeError: if attribute is not found on provided resource object """ return getattr(self._resource, name)
(self, name)
64,492
dynamodb_encryption_sdk.encrypted.resource
__init__
null
def __init__( self, resource, # type: ServiceResource materials_provider, # type: CryptographicMaterialsProvider attribute_actions=None, # type: Optional[AttributeActions] auto_refresh_table_indexes=True, # type: Optional[bool] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if attribute_actions is None: attribute_actions = AttributeActions() self._resource = resource self._materials_provider = materials_provider self._attribute_actions = attribute_actions self._auto_refresh_table_indexes = auto_refresh_table_indexes attr.validate(self) self.__attrs_post_init__()
(self, resource, materials_provider, attribute_actions=None, auto_refresh_table_indexes=True)
64,497
dynamodb_encryption_sdk.encrypted.table
EncryptedTable
High-level helper class to provide a familiar interface to encrypted tables. >>> import boto3 >>> from dynamodb_encryption_sdk.encrypted.table import EncryptedTable >>> from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider >>> table = boto3.resource('dynamodb').Table('my_table') >>> aws_kms_cmp = AwsKmsCryptographicMaterialsProvider('alias/MyKmsAlias') >>> encrypted_table = EncryptedTable( ... table=table, ... materials_provider=aws_kms_cmp ... ) .. note:: This class provides a superset of the boto3 DynamoDB Table API, so should work as a drop-in replacement once configured. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#table If you want to provide per-request cryptographic details, the ``put_item``, ``get_item``, ``query``, and ``scan`` methods will also accept a ``crypto_config`` parameter, defining a custom :class:`CryptoConfig` instance for this request. .. warning:: We do not currently support the ``update_item`` method. :param table: Pre-configured boto3 DynamoDB Table object :type table: boto3.resources.base.ServiceResource :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param TableInfo table_info: Information about the target DynamoDB table :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param bool auto_refresh_table_indexes: Should we attempt to refresh information about table indexes? Requires ``dynamodb:DescribeTable`` permissions on each table. (default: True)
class EncryptedTable(object): # pylint: disable=too-few-public-methods,too-many-instance-attributes """High-level helper class to provide a familiar interface to encrypted tables. >>> import boto3 >>> from dynamodb_encryption_sdk.encrypted.table import EncryptedTable >>> from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider >>> table = boto3.resource('dynamodb').Table('my_table') >>> aws_kms_cmp = AwsKmsCryptographicMaterialsProvider('alias/MyKmsAlias') >>> encrypted_table = EncryptedTable( ... table=table, ... materials_provider=aws_kms_cmp ... ) .. note:: This class provides a superset of the boto3 DynamoDB Table API, so should work as a drop-in replacement once configured. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#table If you want to provide per-request cryptographic details, the ``put_item``, ``get_item``, ``query``, and ``scan`` methods will also accept a ``crypto_config`` parameter, defining a custom :class:`CryptoConfig` instance for this request. .. warning:: We do not currently support the ``update_item`` method. :param table: Pre-configured boto3 DynamoDB Table object :type table: boto3.resources.base.ServiceResource :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param TableInfo table_info: Information about the target DynamoDB table :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param bool auto_refresh_table_indexes: Should we attempt to refresh information about table indexes? Requires ``dynamodb:DescribeTable`` permissions on each table. (default: True) """ _table = attr.ib(validator=attr.validators.instance_of(ServiceResource)) _materials_provider = attr.ib(validator=attr.validators.instance_of(CryptographicMaterialsProvider)) _table_info = attr.ib(validator=attr.validators.optional(attr.validators.instance_of(TableInfo)), default=None) _attribute_actions = attr.ib( validator=attr.validators.instance_of(AttributeActions), default=attr.Factory(AttributeActions) ) _auto_refresh_table_indexes = attr.ib(validator=attr.validators.instance_of(bool), default=True) def __init__( self, table, # type: ServiceResource materials_provider, # type: CryptographicMaterialsProvider table_info=None, # type: Optional[TableInfo] attribute_actions=None, # type: Optional[AttributeActions] auto_refresh_table_indexes=True, # type: Optional[bool] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if attribute_actions is None: attribute_actions = AttributeActions() self._table = table self._materials_provider = materials_provider self._table_info = table_info self._attribute_actions = attribute_actions self._auto_refresh_table_indexes = auto_refresh_table_indexes attr.validate(self) self.__attrs_post_init__() def __attrs_post_init__(self): """Prepare table info is it was not set and set up translation methods.""" if self._table_info is None: self._table_info = TableInfo(name=self._table.name) if self._auto_refresh_table_indexes: self._table_info.refresh_indexed_attributes(self._table.meta.client) # Clone the attribute actions before we modify them self._attribute_actions = self._attribute_actions.copy() self._attribute_actions.set_index_keys(*self._table_info.protected_index_keys()) self._crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_kwargs, partial(crypto_config_from_table_info, self._materials_provider, self._attribute_actions, self._table_info), ) self.get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_get_item, decrypt_python_item, self._crypto_config, self._table.get_item ) self.put_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_put_item, encrypt_python_item, self._crypto_config, self._table.put_item ) self.query = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, decrypt_python_item, self._crypto_config, self._table.query ) self.scan = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, decrypt_python_item, self._crypto_config, self._table.scan ) def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided bridge object. :param str name: Attribute name :returns: Result of asking the provided table object for that attribute name :raises AttributeError: if attribute is not found on provided bridge object """ return getattr(self._table, name) def update_item(self, **kwargs): """Update item is not yet supported.""" raise NotImplementedError('"update_item" is not yet implemented') def batch_writer(self, overwrite_by_pkeys=None): """Create a batch writer object. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Table.batch_writer :type overwrite_by_pkeys: list(string) :param overwrite_by_pkeys: De-duplicate request items in buffer if match new request item on specified primary keys. i.e ``["partition_key1", "sort_key2", "sort_key3"]`` """ encrypted_client = EncryptedClient( client=self._table.meta.client, materials_provider=self._materials_provider, attribute_actions=self._attribute_actions, auto_refresh_table_indexes=self._auto_refresh_table_indexes, expect_standard_dictionaries=True, ) return BatchWriter(table_name=self._table.name, client=encrypted_client, overwrite_by_pkeys=overwrite_by_pkeys)
(table, materials_provider, table_info=None, attribute_actions=None, auto_refresh_table_indexes=True)
64,498
dynamodb_encryption_sdk.encrypted.table
__attrs_init__
Method generated by attrs for class EncryptedTable.
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. """High-level helper class to provide a familiar interface to encrypted tables.""" from functools import partial import attr from boto3.dynamodb.table import BatchWriter from boto3.resources.base import ServiceResource from dynamodb_encryption_sdk.internal.utils import ( crypto_config_from_kwargs, crypto_config_from_table_info, decrypt_get_item, decrypt_multi_get, encrypt_put_item, ) from dynamodb_encryption_sdk.material_providers import CryptographicMaterialsProvider from dynamodb_encryption_sdk.structures import AttributeActions, TableInfo from .client import EncryptedClient from .item import decrypt_python_item, encrypt_python_item try: # Python 3.5.0 and 3.5.1 have incompatible typing modules from typing import Optional # noqa pylint: disable=unused-import except ImportError: # pragma: no cover # We only actually need these imports when running the mypy checks pass __all__ = ("EncryptedTable",) @attr.s(init=False) class EncryptedTable(object): # pylint: disable=too-few-public-methods,too-many-instance-attributes """High-level helper class to provide a familiar interface to encrypted tables. >>> import boto3 >>> from dynamodb_encryption_sdk.encrypted.table import EncryptedTable >>> from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider >>> table = boto3.resource('dynamodb').Table('my_table') >>> aws_kms_cmp = AwsKmsCryptographicMaterialsProvider('alias/MyKmsAlias') >>> encrypted_table = EncryptedTable( ... table=table, ... materials_provider=aws_kms_cmp ... ) .. note:: This class provides a superset of the boto3 DynamoDB Table API, so should work as a drop-in replacement once configured. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#table If you want to provide per-request cryptographic details, the ``put_item``, ``get_item``, ``query``, and ``scan`` methods will also accept a ``crypto_config`` parameter, defining a custom :class:`CryptoConfig` instance for this request. .. warning:: We do not currently support the ``update_item`` method. :param table: Pre-configured boto3 DynamoDB Table object :type table: boto3.resources.base.ServiceResource :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param TableInfo table_info: Information about the target DynamoDB table :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param bool auto_refresh_table_indexes: Should we attempt to refresh information about table indexes? Requires ``dynamodb:DescribeTable`` permissions on each table. (default: True) """ _table = attr.ib(validator=attr.validators.instance_of(ServiceResource)) _materials_provider = attr.ib(validator=attr.validators.instance_of(CryptographicMaterialsProvider)) _table_info = attr.ib(validator=attr.validators.optional(attr.validators.instance_of(TableInfo)), default=None) _attribute_actions = attr.ib( validator=attr.validators.instance_of(AttributeActions), default=attr.Factory(AttributeActions) ) _auto_refresh_table_indexes = attr.ib(validator=attr.validators.instance_of(bool), default=True) def __init__( self, table, # type: ServiceResource materials_provider, # type: CryptographicMaterialsProvider table_info=None, # type: Optional[TableInfo] attribute_actions=None, # type: Optional[AttributeActions] auto_refresh_table_indexes=True, # type: Optional[bool] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if attribute_actions is None: attribute_actions = AttributeActions() self._table = table self._materials_provider = materials_provider self._table_info = table_info self._attribute_actions = attribute_actions self._auto_refresh_table_indexes = auto_refresh_table_indexes attr.validate(self) self.__attrs_post_init__() def __attrs_post_init__(self): """Prepare table info is it was not set and set up translation methods.""" if self._table_info is None: self._table_info = TableInfo(name=self._table.name) if self._auto_refresh_table_indexes: self._table_info.refresh_indexed_attributes(self._table.meta.client) # Clone the attribute actions before we modify them self._attribute_actions = self._attribute_actions.copy() self._attribute_actions.set_index_keys(*self._table_info.protected_index_keys()) self._crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_kwargs, partial(crypto_config_from_table_info, self._materials_provider, self._attribute_actions, self._table_info), ) self.get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_get_item, decrypt_python_item, self._crypto_config, self._table.get_item ) self.put_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_put_item, encrypt_python_item, self._crypto_config, self._table.put_item ) self.query = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, decrypt_python_item, self._crypto_config, self._table.query ) self.scan = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, decrypt_python_item, self._crypto_config, self._table.scan ) def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided bridge object. :param str name: Attribute name :returns: Result of asking the provided table object for that attribute name :raises AttributeError: if attribute is not found on provided bridge object """ return getattr(self._table, name) def update_item(self, **kwargs): """Update item is not yet supported.""" raise NotImplementedError('"update_item" is not yet implemented') def batch_writer(self, overwrite_by_pkeys=None): """Create a batch writer object. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Table.batch_writer :type overwrite_by_pkeys: list(string) :param overwrite_by_pkeys: De-duplicate request items in buffer if match new request item on specified primary keys. i.e ``["partition_key1", "sort_key2", "sort_key3"]`` """ encrypted_client = EncryptedClient( client=self._table.meta.client, materials_provider=self._materials_provider, attribute_actions=self._attribute_actions, auto_refresh_table_indexes=self._auto_refresh_table_indexes, expect_standard_dictionaries=True, ) return BatchWriter(table_name=self._table.name, client=encrypted_client, overwrite_by_pkeys=overwrite_by_pkeys)
(self, table, materials_provider, table_info=None, attribute_actions=NOTHING, auto_refresh_table_indexes=True) -> NoneType
64,499
dynamodb_encryption_sdk.encrypted.table
__attrs_post_init__
Prepare table info is it was not set and set up translation methods.
def __attrs_post_init__(self): """Prepare table info is it was not set and set up translation methods.""" if self._table_info is None: self._table_info = TableInfo(name=self._table.name) if self._auto_refresh_table_indexes: self._table_info.refresh_indexed_attributes(self._table.meta.client) # Clone the attribute actions before we modify them self._attribute_actions = self._attribute_actions.copy() self._attribute_actions.set_index_keys(*self._table_info.protected_index_keys()) self._crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_kwargs, partial(crypto_config_from_table_info, self._materials_provider, self._attribute_actions, self._table_info), ) self.get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_get_item, decrypt_python_item, self._crypto_config, self._table.get_item ) self.put_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_put_item, encrypt_python_item, self._crypto_config, self._table.put_item ) self.query = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, decrypt_python_item, self._crypto_config, self._table.query ) self.scan = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, decrypt_python_item, self._crypto_config, self._table.scan )
(self)
64,501
dynamodb_encryption_sdk.encrypted.table
__ge__
Method generated by attrs for class EncryptedTable.
null
(self, other)
64,502
dynamodb_encryption_sdk.encrypted.table
__getattr__
Catch any method/attribute lookups that are not defined in this class and try to find them on the provided bridge object. :param str name: Attribute name :returns: Result of asking the provided table object for that attribute name :raises AttributeError: if attribute is not found on provided bridge object
def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided bridge object. :param str name: Attribute name :returns: Result of asking the provided table object for that attribute name :raises AttributeError: if attribute is not found on provided bridge object """ return getattr(self._table, name)
(self, name)
64,504
dynamodb_encryption_sdk.encrypted.table
__init__
null
def __init__( self, table, # type: ServiceResource materials_provider, # type: CryptographicMaterialsProvider table_info=None, # type: Optional[TableInfo] attribute_actions=None, # type: Optional[AttributeActions] auto_refresh_table_indexes=True, # type: Optional[bool] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if attribute_actions is None: attribute_actions = AttributeActions() self._table = table self._materials_provider = materials_provider self._table_info = table_info self._attribute_actions = attribute_actions self._auto_refresh_table_indexes = auto_refresh_table_indexes attr.validate(self) self.__attrs_post_init__()
(self, table, materials_provider, table_info=None, attribute_actions=None, auto_refresh_table_indexes=True)
64,509
dynamodb_encryption_sdk.encrypted.table
batch_writer
Create a batch writer object. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Table.batch_writer :type overwrite_by_pkeys: list(string) :param overwrite_by_pkeys: De-duplicate request items in buffer if match new request item on specified primary keys. i.e ``["partition_key1", "sort_key2", "sort_key3"]``
def batch_writer(self, overwrite_by_pkeys=None): """Create a batch writer object. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Table.batch_writer :type overwrite_by_pkeys: list(string) :param overwrite_by_pkeys: De-duplicate request items in buffer if match new request item on specified primary keys. i.e ``["partition_key1", "sort_key2", "sort_key3"]`` """ encrypted_client = EncryptedClient( client=self._table.meta.client, materials_provider=self._materials_provider, attribute_actions=self._attribute_actions, auto_refresh_table_indexes=self._auto_refresh_table_indexes, expect_standard_dictionaries=True, ) return BatchWriter(table_name=self._table.name, client=encrypted_client, overwrite_by_pkeys=overwrite_by_pkeys)
(self, overwrite_by_pkeys=None)
64,510
dynamodb_encryption_sdk.encrypted.table
update_item
Update item is not yet supported.
def update_item(self, **kwargs): """Update item is not yet supported.""" raise NotImplementedError('"update_item" is not yet implemented')
(self, **kwargs)
64,511
dynamodb_encryption_sdk.compatability
_warn_deprecated_python
Template for deprecation of Python warning.
def _warn_deprecated_python(): """Template for deprecation of Python warning.""" deprecated_versions = { (2, 7): {"date": DEPRECATION_DATE_MAP["2.x"]}, (3, 4): {"date": DEPRECATION_DATE_MAP["2.x"]}, (3, 5): {"date": "2021-11-10"}, (3, 6): {"date": "2021-12-19"}, } py_version = (sys.version_info.major, sys.version_info.minor) minimum_version = (3, 7) if py_version in deprecated_versions: params = deprecated_versions[py_version] warning = ( "aws-dynamodb-encryption will no longer support Python {}.{} " "starting {}. To continue receiving service updates, " "bug fixes, and security updates please upgrade to Python {}.{} or " "later. For more information, see SUPPORT_POLICY.rst: " "https://github.com/aws/aws-dynamodb-encryption-python/blob/master/SUPPORT_POLICY.rst" ).format(py_version[0], py_version[1], minimum_version[0], minimum_version[1], params["date"]) warnings.warn(warning, DeprecationWarning)
()
64,513
dynamodb_encryption_sdk.encrypted.item
decrypt_dynamodb_item
Decrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': {'B': b'ENCRYPTED_DATA'}, ... 'more': {'B': b'ENCRYPTED_DATA'} ... } >>> decrypted_item = decrypt_python_item( ... item=encrypted_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles DynamoDB-formatted items and is for use with the boto3 DynamoDB client. :param dict item: Encrypted and signed DynamoDB item :param CryptoConfig crypto_config: Cryptographic configuration :returns: Plaintext DynamoDB item :rtype: dict
def decrypt_dynamodb_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Decrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': {'B': b'ENCRYPTED_DATA'}, ... 'more': {'B': b'ENCRYPTED_DATA'} ... } >>> decrypted_item = decrypt_python_item( ... item=encrypted_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles DynamoDB-formatted items and is for use with the boto3 DynamoDB client. :param dict item: Encrypted and signed DynamoDB item :param CryptoConfig crypto_config: Cryptographic configuration :returns: Plaintext DynamoDB item :rtype: dict """ unique_actions = set([crypto_config.attribute_actions.default_action.name]) unique_actions.update({action.name for action in crypto_config.attribute_actions.attribute_actions.values()}) if crypto_config.attribute_actions.take_no_actions: # If we explicitly have been told not to do anything to this item, just copy it. return item.copy() try: signature_attribute = item.pop(ReservedAttributes.SIGNATURE.value) except KeyError: # The signature is always written, so if no signature is found then the item was not # encrypted or signed. raise DecryptionError("No signature attribute found in item") inner_crypto_config = crypto_config.copy() # Retrieve the material description from the item if found. try: material_description_attribute = item.pop(ReservedAttributes.MATERIAL_DESCRIPTION.value) except KeyError: # If no material description is found, we use inner_crypto_config as-is. pass else: # If material description is found, override the material description in inner_crypto_config. material_description = deserialize_material_description(material_description_attribute) inner_crypto_config.encryption_context.material_description = material_description decryption_materials = inner_crypto_config.decryption_materials() verify_item_signature(signature_attribute, item, decryption_materials.verification_key, inner_crypto_config) try: decryption_key = decryption_materials.decryption_key except AttributeError: if inner_crypto_config.attribute_actions.contains_action(CryptoAction.ENCRYPT_AND_SIGN): raise DecryptionError( "Attribute actions ask for some attributes to be decrypted but no decryption key is available" ) return item.copy() decryption_mode = inner_crypto_config.encryption_context.material_description.get( MaterialDescriptionKeys.ATTRIBUTE_ENCRYPTION_MODE.value ) algorithm_descriptor = decryption_key.algorithm + decryption_mode # Once the signature has been verified, actually decrypt the item attributes. decrypted_item = {} for name, attribute in item.items(): if inner_crypto_config.attribute_actions.action(name) is CryptoAction.ENCRYPT_AND_SIGN: decrypted_item[name] = decrypt_attribute( attribute_name=name, attribute=attribute, decryption_key=decryption_key, algorithm=algorithm_descriptor ) else: decrypted_item[name] = attribute.copy() return decrypted_item
(item, crypto_config)
64,514
dynamodb_encryption_sdk.encrypted.item
decrypt_python_item
Decrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': Binary(b'ENCRYPTED_DATA'), ... 'more': Binary(b'ENCRYPTED_DATA') ... } >>> decrypted_item = decrypt_python_item( ... item=encrypted_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles human-friendly dictionaries and is for use with the boto3 DynamoDB service or table resource. :param dict item: Encrypted and signed dictionary :param CryptoConfig crypto_config: Cryptographic configuration :returns: Plaintext dictionary :rtype: dict
def decrypt_python_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Decrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': Binary(b'ENCRYPTED_DATA'), ... 'more': Binary(b'ENCRYPTED_DATA') ... } >>> decrypted_item = decrypt_python_item( ... item=encrypted_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles human-friendly dictionaries and is for use with the boto3 DynamoDB service or table resource. :param dict item: Encrypted and signed dictionary :param CryptoConfig crypto_config: Cryptographic configuration :returns: Plaintext dictionary :rtype: dict """ ddb_item = dict_to_ddb(item) decrypted_ddb_item = decrypt_dynamodb_item(ddb_item, crypto_config) return ddb_to_dict(decrypted_ddb_item)
(item, crypto_config)
64,516
dynamodb_encryption_sdk.encrypted.item
encrypt_dynamodb_item
Encrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item >>> plaintext_item = { ... 'some': {'S': 'data'}, ... 'more': {'N': '5'} ... } >>> encrypted_item = encrypt_dynamodb_item( ... item=plaintext_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles DynamoDB-formatted items and is for use with the boto3 DynamoDB client. :param dict item: Plaintext DynamoDB item :param CryptoConfig crypto_config: Cryptographic configuration :returns: Encrypted and signed DynamoDB item :rtype: dict
def encrypt_dynamodb_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Encrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item >>> plaintext_item = { ... 'some': {'S': 'data'}, ... 'more': {'N': '5'} ... } >>> encrypted_item = encrypt_dynamodb_item( ... item=plaintext_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles DynamoDB-formatted items and is for use with the boto3 DynamoDB client. :param dict item: Plaintext DynamoDB item :param CryptoConfig crypto_config: Cryptographic configuration :returns: Encrypted and signed DynamoDB item :rtype: dict """ if crypto_config.attribute_actions.take_no_actions: # If we explicitly have been told not to do anything to this item, just copy it. return item.copy() for reserved_name in ReservedAttributes: if reserved_name.value in item: raise EncryptionError( 'Reserved attribute name "{}" is not allowed in plaintext item.'.format(reserved_name.value) ) encryption_materials = crypto_config.encryption_materials() inner_material_description = encryption_materials.material_description.copy() try: encryption_materials.encryption_key except AttributeError: if crypto_config.attribute_actions.contains_action(CryptoAction.ENCRYPT_AND_SIGN): raise EncryptionError( "Attribute actions ask for some attributes to be encrypted but no encryption key is available" ) encrypted_item = item.copy() else: # Add the attribute encryption mode to the inner material description encryption_mode = MaterialDescriptionValues.CBC_PKCS5_ATTRIBUTE_ENCRYPTION.value inner_material_description[MaterialDescriptionKeys.ATTRIBUTE_ENCRYPTION_MODE.value] = encryption_mode algorithm_descriptor = encryption_materials.encryption_key.algorithm + encryption_mode encrypted_item = {} for name, attribute in item.items(): if crypto_config.attribute_actions.action(name) is CryptoAction.ENCRYPT_AND_SIGN: encrypted_item[name] = encrypt_attribute( attribute_name=name, attribute=attribute, encryption_key=encryption_materials.encryption_key, algorithm=algorithm_descriptor, ) else: encrypted_item[name] = attribute.copy() signature_attribute = sign_item(encrypted_item, encryption_materials.signing_key, crypto_config) encrypted_item[ReservedAttributes.SIGNATURE.value] = signature_attribute try: # Add the signing key algorithm identifier to the inner material description if provided inner_material_description[ MaterialDescriptionKeys.SIGNING_KEY_ALGORITHM.value ] = encryption_materials.signing_key.signing_algorithm() except NotImplementedError: # Not all signing keys will provide this value pass material_description_attribute = serialize_material_description(inner_material_description) encrypted_item[ReservedAttributes.MATERIAL_DESCRIPTION.value] = material_description_attribute return encrypted_item
(item, crypto_config)
64,517
dynamodb_encryption_sdk.encrypted.item
encrypt_python_item
Encrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item >>> plaintext_item = { ... 'some': 'data', ... 'more': 5 ... } >>> encrypted_item = encrypt_python_item( ... item=plaintext_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles human-friendly dictionaries and is for use with the boto3 DynamoDB service or table resource. :param dict item: Plaintext dictionary :param CryptoConfig crypto_config: Cryptographic configuration :returns: Encrypted and signed dictionary :rtype: dict
def encrypt_python_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Encrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item >>> plaintext_item = { ... 'some': 'data', ... 'more': 5 ... } >>> encrypted_item = encrypt_python_item( ... item=plaintext_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles human-friendly dictionaries and is for use with the boto3 DynamoDB service or table resource. :param dict item: Plaintext dictionary :param CryptoConfig crypto_config: Cryptographic configuration :returns: Encrypted and signed dictionary :rtype: dict """ ddb_item = dict_to_ddb(item) encrypted_ddb_item = encrypt_dynamodb_item(ddb_item, crypto_config) return ddb_to_dict(encrypted_ddb_item)
(item, crypto_config)
64,527
sqlalchemy_mate.engine_creator
EngineCreator
Tired of looking up docs on https://docs.sqlalchemy.org/en/latest/core/engines.html? ``EngineCreator`` creates sqlalchemy engine in one line: Example:: from sqlalchemy_mate import EngineCreator # sqlite in memory engine = EngineCreator.create_sqlite() # connect to postgresql, credential stored at ``~/.db.json`` # content of ``.db.json`` { "mydb": { "host": "example.com", "port": 1234, "database": "test", "username": "admin", "password": "admin" }, ... } engine = EngineCreator.from_home_db_json("mydb").create_postgresql()
class EngineCreator: # pragma: no cover """ Tired of looking up docs on https://docs.sqlalchemy.org/en/latest/core/engines.html? ``EngineCreator`` creates sqlalchemy engine in one line: Example:: from sqlalchemy_mate import EngineCreator # sqlite in memory engine = EngineCreator.create_sqlite() # connect to postgresql, credential stored at ``~/.db.json`` # content of ``.db.json`` { "mydb": { "host": "example.com", "port": 1234, "database": "test", "username": "admin", "password": "admin" }, ... } engine = EngineCreator.from_home_db_json("mydb").create_postgresql() """ def __init__( self, host=None, port=None, database=None, username=None, password=None, ): self.host = host self.port = port self.database = database self.username = username self.password = password uri_template = "{username}{has_password}{password}@{host}{has_port}{port}/{database}" path_db_json = os.path.join(os.path.expanduser("~"), ".db.json") local_home = os.path.basename(os.path.expanduser("~")) def __repr__(self): return "{classname}(host='{host}', port={port}, database='{database}', username={username}, password='xxxxxxxxxxxx')".format( classname=self.__class__.__name__, host=self.host, port=self.port, database=self.database, username=self.username, ) @property def uri(self) -> str: """ Return sqlalchemy connect string URI. """ return self.uri_template.format( host=self.host, port="" if self.port is None else self.port, database=self.database, username=self.username, password="" if self.password is None else self.password, has_password="" if self.password is None else ":", has_port="" if self.port is None else ":", ) @classmethod def _validate_key_mapping(cls, key_mapping): if key_mapping is not None: keys = list(key_mapping) keys.sort() if keys != ["database", "host", "password", "port", "username"]: msg = ("`key_mapping` is the credential field mapping from `Credential` to custom json! " "it has to be a dictionary with 5 keys: " "host, port, password, port, username!") raise ValueError(msg) @classmethod def _transform(cls, data, key_mapping): if key_mapping is None: return data else: return {actual: data[custom] for actual, custom in key_mapping.items()} @classmethod def _from_json_data(cls, data, json_path=None, key_mapping=None): if json_path is not None: for p in json_path.split("."): data = data[p] return cls(**cls._transform(data, key_mapping)) @classmethod def from_json( cls, json_file: str, json_path: str = None, key_mapping: dict = None, ) -> 'EngineCreator': """ Load connection credential from json file. :param json_file: str, path to json file :param json_path: str, dot notation of the path to the credential dict. :param key_mapping: dict, map 'host', 'port', 'database', 'username', 'password' to custom alias, for example ``{'host': 'h', 'port': 'p', 'database': 'db', 'username': 'user', 'password': 'pwd'}``. This params are used to adapt any json data. :rtype: :return: Example: Your json file:: { "credentials": { "db1": { "h": "example.com", "p": 1234, "db": "test", "user": "admin", "pwd": "admin", }, "db2": { ... } } } Usage:: cred = Credential.from_json( "path-to-json-file", "credentials.db1", dict(host="h", port="p", database="db", username="user", password="pwd") ) """ cls._validate_key_mapping(key_mapping) with open(json_file, "rb") as f: data = json.loads(f.read().decode("utf-8")) return cls._from_json_data(data, json_path, key_mapping) @classmethod def from_home_db_json( cls, identifier: str, key_mapping: dict = None, ) -> 'EngineCreator': # pragma: no cover """ Read credential from $HOME/.db.json file. :type identifier: str :param identifier: str, database identifier. :type key_mapping: Dict[str, str] :param key_mapping: dict ``.db.json````:: { "identifier1": { "host": "example.com", "port": 1234, "database": "test", "username": "admin", "password": "admin", }, "identifier2": { ... } } """ return cls.from_json( json_file=cls.path_db_json, json_path=identifier, key_mapping=key_mapping) @classmethod def from_s3_json( cls, bucket_name: str, key: str, json_path: str = None, key_mapping: dict = None, aws_profile: str = None, aws_access_key_id: str = None, aws_secret_access_key: str = None, region_name: str = None, ) -> 'EngineCreator': # pragma: no cover """ Load database credential from json on s3. :param bucket_name: str :param key: str :param aws_profile: if None, assume that you are using this from AWS cloud. (service on the same cloud doesn't need profile name) :param aws_access_key_id: str, not recommend to use :param aws_secret_access_key: str, not recommend to use :param region_name: str """ import boto3 ses = boto3.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name, profile_name=aws_profile, ) s3 = ses.resource("s3") bucket = s3.Bucket(bucket_name) object = bucket.Object(key) data = json.loads(object.get()["Body"].read().decode("utf-8")) return cls._from_json_data(data, json_path, key_mapping) @classmethod def from_env( cls, prefix: str, kms_decrypt: bool = False, aws_profile: str = None, ) -> 'EngineCreator': """ Load database credential from env variable. - host: ENV.{PREFIX}_HOST - port: ENV.{PREFIX}_PORT - database: ENV.{PREFIX}_DATABASE - username: ENV.{PREFIX}_USERNAME - password: ENV.{PREFIX}_PASSWORD :param prefix: str :param kms_decrypt: bool :param aws_profile: str """ if len(prefix) < 1: raise ValueError("prefix can't be empty") if len(set(prefix).difference(set(string.ascii_uppercase + "_"))): raise ValueError("prefix can only use [A-Z] and '_'!") if not prefix.endswith("_"): prefix = prefix + "_" data = dict( host=os.getenv(prefix + "HOST"), port=os.getenv(prefix + "PORT"), database=os.getenv(prefix + "DATABASE"), username=os.getenv(prefix + "USERNAME"), password=os.getenv(prefix + "PASSWORD"), ) if kms_decrypt is True: # pragma: no cover import boto3 from base64 import b64decode if aws_profile is not None: kms = boto3.client("kms") else: ses = boto3.Session(profile_name=aws_profile) kms = ses.client("kms") def decrypt(kms, text): return kms.decrypt( CiphertextBlob=b64decode(text.encode("utf-8")) )["Plaintext"].decode("utf-8") data = { key: value if value is None else decrypt(kms, str(value)) for key, value in data.items() } return cls(**data) def to_dict(self): """ Convert credentials into a dict. """ return dict( host=self.host, port=self.port, database=self.database, username=self.username, password=self.password, ) # --- engine creator logic def create_connect_str(self, dialect_and_driver) -> str: return "{}://{}".format(dialect_and_driver, self.uri) _ccs = create_connect_str def create_engine(self, conn_str, **kwargs) -> Engine: """ :rtype: Engine """ return sa.create_engine(conn_str, **kwargs) _ce = create_engine @classmethod def create_sqlite(cls, path=":memory:", **kwargs): """ Create sqlite engine. """ return sa.create_engine("sqlite:///{path}".format(path=path), **kwargs) class DialectAndDriver(object): """ DB dialect and DB driver mapping. """ psql = "postgresql" psql_psycopg2 = "postgresql+psycopg2" psql_pg8000 = "postgresql+pg8000" psql_pygresql = "postgresql+pygresql" psql_psycopg2cffi = "postgresql+psycopg2cffi" psql_pypostgresql = "postgresql+pypostgresql" mysql = "mysql" mysql_mysqldb = "mysql+mysqldb" mysql_mysqlconnector = "mysql+mysqlconnector" mysql_oursql = "mysql+oursql" mysql_pymysql = "mysql+pymysql" mysql_cymysql = "mysql+cymysql" oracle = "oracle" oracle_cx_oracle = "oracle+cx_oracle" mssql_pyodbc = "mssql+pyodbc" mssql_pymssql = "mssql+pymssql" redshift_psycopg2 = "redshift+psycopg2" # postgresql def create_postgresql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql), **kwargs ) def create_postgresql_psycopg2(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_psycopg2), **kwargs ) def create_postgresql_pg8000(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_pg8000), **kwargs ) def _create_postgresql_pygresql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_pygresql), **kwargs ) def create_postgresql_psycopg2cffi(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_psycopg2cffi), **kwargs ) def create_postgresql_pypostgresql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_pypostgresql), **kwargs ) # mysql def create_mysql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql), **kwargs ) def create_mysql_mysqldb(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_mysqldb), **kwargs ) def create_mysql_mysqlconnector(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_mysqlconnector), **kwargs ) def create_mysql_oursql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_oursql), **kwargs ) def create_mysql_pymysql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_pymysql), **kwargs ) def create_mysql_cymysql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_cymysql), **kwargs ) # oracle def create_oracle(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.oracle), **kwargs ) def create_oracle_cx_oracle(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.oracle_cx_oracle), **kwargs ) # mssql def create_mssql_pyodbc(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mssql_pyodbc), **kwargs ) def create_mssql_pymssql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mssql_pymssql), **kwargs ) # redshift def create_redshift(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.redshift_psycopg2), **kwargs )
(host=None, port=None, database=None, username=None, password=None)
64,528
sqlalchemy_mate.engine_creator
__init__
null
def __init__( self, host=None, port=None, database=None, username=None, password=None, ): self.host = host self.port = port self.database = database self.username = username self.password = password
(self, host=None, port=None, database=None, username=None, password=None)
64,529
sqlalchemy_mate.engine_creator
__repr__
null
def __repr__(self): return "{classname}(host='{host}', port={port}, database='{database}', username={username}, password='xxxxxxxxxxxx')".format( classname=self.__class__.__name__, host=self.host, port=self.port, database=self.database, username=self.username, )
(self)
64,530
sqlalchemy_mate.engine_creator
create_connect_str
null
def create_connect_str(self, dialect_and_driver) -> str: return "{}://{}".format(dialect_and_driver, self.uri)
(self, dialect_and_driver) -> str
64,531
sqlalchemy_mate.engine_creator
create_engine
:rtype: Engine
def create_engine(self, conn_str, **kwargs) -> Engine: """ :rtype: Engine """ return sa.create_engine(conn_str, **kwargs)
(self, conn_str, **kwargs) -> sqlalchemy.engine.base.Engine
64,532
sqlalchemy_mate.engine_creator
_create_postgresql_pygresql
:rtype: Engine
def _create_postgresql_pygresql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_pygresql), **kwargs )
(self, **kwargs)
64,535
sqlalchemy_mate.engine_creator
create_mssql_pymssql
:rtype: Engine
def create_mssql_pymssql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mssql_pymssql), **kwargs )
(self, **kwargs)
64,536
sqlalchemy_mate.engine_creator
create_mssql_pyodbc
:rtype: Engine
def create_mssql_pyodbc(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mssql_pyodbc), **kwargs )
(self, **kwargs)
64,537
sqlalchemy_mate.engine_creator
create_mysql
:rtype: Engine
def create_mysql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql), **kwargs )
(self, **kwargs)
64,538
sqlalchemy_mate.engine_creator
create_mysql_cymysql
:rtype: Engine
def create_mysql_cymysql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_cymysql), **kwargs )
(self, **kwargs)
64,539
sqlalchemy_mate.engine_creator
create_mysql_mysqlconnector
:rtype: Engine
def create_mysql_mysqlconnector(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_mysqlconnector), **kwargs )
(self, **kwargs)
64,540
sqlalchemy_mate.engine_creator
create_mysql_mysqldb
:rtype: Engine
def create_mysql_mysqldb(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_mysqldb), **kwargs )
(self, **kwargs)
64,541
sqlalchemy_mate.engine_creator
create_mysql_oursql
:rtype: Engine
def create_mysql_oursql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_oursql), **kwargs )
(self, **kwargs)
64,542
sqlalchemy_mate.engine_creator
create_mysql_pymysql
:rtype: Engine
def create_mysql_pymysql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql_pymysql), **kwargs )
(self, **kwargs)
64,543
sqlalchemy_mate.engine_creator
create_oracle
:rtype: Engine
def create_oracle(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.oracle), **kwargs )
(self, **kwargs)
64,544
sqlalchemy_mate.engine_creator
create_oracle_cx_oracle
:rtype: Engine
def create_oracle_cx_oracle(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.oracle_cx_oracle), **kwargs )
(self, **kwargs)
64,545
sqlalchemy_mate.engine_creator
create_postgresql
:rtype: Engine
def create_postgresql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql), **kwargs )
(self, **kwargs)
64,546
sqlalchemy_mate.engine_creator
create_postgresql_pg8000
:rtype: Engine
def create_postgresql_pg8000(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_pg8000), **kwargs )
(self, **kwargs)
64,547
sqlalchemy_mate.engine_creator
create_postgresql_psycopg2
:rtype: Engine
def create_postgresql_psycopg2(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_psycopg2), **kwargs )
(self, **kwargs)
64,548
sqlalchemy_mate.engine_creator
create_postgresql_psycopg2cffi
:rtype: Engine
def create_postgresql_psycopg2cffi(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_psycopg2cffi), **kwargs )
(self, **kwargs)
64,549
sqlalchemy_mate.engine_creator
create_postgresql_pypostgresql
:rtype: Engine
def create_postgresql_pypostgresql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.psql_pypostgresql), **kwargs )
(self, **kwargs)
64,550
sqlalchemy_mate.engine_creator
create_redshift
:rtype: Engine
def create_redshift(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.redshift_psycopg2), **kwargs )
(self, **kwargs)
64,551
sqlalchemy_mate.engine_creator
to_dict
Convert credentials into a dict.
def to_dict(self): """ Convert credentials into a dict. """ return dict( host=self.host, port=self.port, database=self.database, username=self.username, password=self.password, )
(self)
64,552
sqlalchemy_mate.orm.extended_declarative_base
ExtendedBase
Provide additional method. Example:: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base, ExtendedBase): ... do what you do with sqlalchemy ORM **中文文档** 提供了三个快捷函数, 分别用于获得列表形式的 primary key names, fields, values - :meth:`ExtendedBase.pk_names` - :meth:`ExtendedBase.pk_fields` - :meth:`ExtendedBase.pk_values` 另外提供了三个快捷函数, 专门针对只有一个 primary key 的情况, 分别用于获得单个形式的 primary key name, field, value. - :meth:`ExtendedBase.id_field_name` - :meth:`ExtendedBase.id_field` - :meth:`ExtendedBase.id_field_value` 所有参数包括 ``engine_or_session`` 的函数需返回 - 所有的 insert / update - 所有的 select 相关的 method 返回的不是 ResultProxy, 因为有 engine_or_session 这个参数如果输入是 engine, 用于执行的 session 都是临时对象, 离开了这个 method, session 将被摧毁. 而返回的 Result 是跟当前的 session 绑定相关的, session 一旦 被关闭, Result 理应不进行任何后续操作. 所以建议全部返回所有结果的列表而不是迭代器.
class ExtendedBase(Base): """ Provide additional method. Example:: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base, ExtendedBase): ... do what you do with sqlalchemy ORM **中文文档** 提供了三个快捷函数, 分别用于获得列表形式的 primary key names, fields, values - :meth:`ExtendedBase.pk_names` - :meth:`ExtendedBase.pk_fields` - :meth:`ExtendedBase.pk_values` 另外提供了三个快捷函数, 专门针对只有一个 primary key 的情况, 分别用于获得单个形式的 primary key name, field, value. - :meth:`ExtendedBase.id_field_name` - :meth:`ExtendedBase.id_field` - :meth:`ExtendedBase.id_field_value` 所有参数包括 ``engine_or_session`` 的函数需返回 - 所有的 insert / update - 所有的 select 相关的 method 返回的不是 ResultProxy, 因为有 engine_or_session 这个参数如果输入是 engine, 用于执行的 session 都是临时对象, 离开了这个 method, session 将被摧毁. 而返回的 Result 是跟当前的 session 绑定相关的, session 一旦 被关闭, Result 理应不进行任何后续操作. 所以建议全部返回所有结果的列表而不是迭代器. """ __abstract__ = True _settings_major_attrs: list = None _cache_pk_names: tuple = None # --- No DB interaction APIs --- @classmethod def pk_names(cls) -> Tuple[str]: """ Primary key column name list. """ if cls._cache_pk_names is None: cls._cache_pk_names = tuple([ col.name for col in inspect(cls).primary_key ]) return cls._cache_pk_names _cache_pk_fields: tuple = None @classmethod def pk_fields(cls) -> Tuple[InstrumentedAttribute]: """ Primary key columns instance. For example:: class User(Base): id = Column(..., primary_key=True) name = Column(...) User.pk_fields() # (User.id,) :rtype: tuple """ if cls._cache_pk_fields is None: cls._cache_pk_fields = tuple([ getattr(cls, name) for name in cls.pk_names() ]) return cls._cache_pk_fields def pk_values(self) -> tuple: """ Primary key values :rtype: tuple """ return tuple([getattr(self, name) for name in self.pk_names()]) # id_field_xxx() method are only valid if there's only one primary key _id_field_name: str = None @classmethod def id_field_name(cls) -> str: """ If only one primary_key, then return the name of it. Otherwise, raise ValueError. """ if cls._id_field_name is None: if len(cls.pk_names()) == 1: cls._id_field_name = cls.pk_names()[0] else: raise ValueError( "{classname} has more than 1 primary key!" .format(classname=cls.__name__) ) return cls._id_field_name _id_field = None @classmethod def id_field(cls) -> InstrumentedAttribute: """ If only one primary_key, then return the Class.field name object. Otherwise, raise ValueError. """ if cls._id_field is None: cls._id_field = getattr(cls, cls.id_field_name()) return cls._id_field def id_field_value(self): """ If only one primary_key, then return the value of primary key. Otherwise, raise ValueError """ return getattr(self, self.id_field_name()) _cache_keys: List[str] = None @classmethod def keys(cls) -> List[str]: """ return list of all declared columns. :rtype: List[str] """ if cls._cache_keys is None: cls._cache_keys = [c.name for c in cls.__table__.columns] return cls._cache_keys def values(self) -> list: """ return list of value of all declared columns. """ return [getattr(self, c.name, None) for c in self.__table__.columns] def items(self) -> List[Tuple[str, Any]]: """ return list of pair of name and value of all declared columns. """ return [ (c.name, getattr(self, c.name, None)) for c in self.__table__.columns ] def __repr__(self): kwargs = list() for attr, value in self.items(): kwargs.append("%s=%r" % (attr, value)) return "%s(%s)" % (self.__class__.__name__, ", ".join(kwargs)) def __str__(self): return self.__repr__() def to_dict(self, include_null=True) -> Dict[str, Any]: """ Convert to dict. :rtype: dict """ if include_null: return dict(self.items()) else: return { attr: value for attr, value in self.__dict__.items() if not attr.startswith("_sa_") } def to_OrderedDict( self, include_null: bool = True, ) -> OrderedDict: """ Convert to OrderedDict. """ if include_null: return OrderedDict(self.items()) else: items = list() for c in self.__table__._columns: try: items.append((c.name, self.__dict__[c.name])) except KeyError: pass return OrderedDict(items) _cache_major_attrs: tuple = None @classmethod def _major_attrs(cls): if cls._cache_major_attrs is None: l = list() for item in cls._settings_major_attrs: if isinstance(item, Column): l.append(item.name) elif isinstance(item, str): l.append(item) else: # pragma: no cover raise TypeError if len(set(l)) != len(l): # pragma: no cover raise ValueError cls._cache_major_attrs = tuple(l) return cls._cache_major_attrs def glance(self, _verbose: bool = True): # pragma: no cover """ Print itself, only display attributes defined in :attr:`ExtendedBase._settings_major_attrs` :param _verbose: internal param for unit testing """ if self._settings_major_attrs is None: msg = ("Please specify attributes you want to include " "in `class._settings_major_attrs`!") raise NotImplementedError(msg) kwargs = [ (attr, getattr(self, attr)) for attr in self._major_attrs() ] text = "{classname}({kwargs})".format( classname=self.__class__.__name__, kwargs=", ".join([ "%s=%r" % (attr, value) for attr, value in kwargs ]) ) if _verbose: # pragma: no cover print(text) def absorb( self, other: 'ExtendedBase', ignore_none: bool = True, ) -> 'ExtendedBase': """ For attributes of others that value is not None, assign it to self. **中文文档** 将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。 """ if not isinstance(other, self.__class__): raise TypeError("`other` has to be a instance of %s!" % self.__class__) if ignore_none: for attr, value in other.items(): if value is not None: setattr(self, attr, deepcopy(value)) else: for attr, value in other.items(): setattr(self, attr, deepcopy(value)) return self def revise( self, data: dict, ignore_none: bool = True, ) -> 'ExtendedBase': """ Revise attributes value with dictionary data. **中文文档** 将一个字典中的数据更新到本条文档. 当且仅当数据值不为 None 时. """ if not isinstance(data, dict): raise TypeError("`data` has to be a dict!") if ignore_none: for key, value in data.items(): if value is not None: setattr(self, key, deepcopy(value)) else: for key, value in data.items(): setattr(self, key, deepcopy(value)) return self # --- DB interaction APIs --- @classmethod def by_pk( cls, engine_or_session: Union[Engine, Session], id_: Union[Any, List[Any], Tuple], ): """ Get one object by primary_key values. Examples:: class User(Base): id = Column(Integer, primary_key) name = Column(String) with Session(engine) as session: session.add(User(id=1, name="Alice") session.commit() # User(id=1, name="Alice") print(User.by_pk(1, engine)) print(User.by_pk((1,), engine)) print(User.by_pk([1,), engine)) with Session(engine) as session: print(User.by_pk(1, session)) print(User.by_pk((1,), session)) print(User.by_pk([1,), session)) **中文文档** 一个简单的语法糖, 允许用户直接用 primary key column 的值访问单个对象. """ ses, auto_close = ensure_session(engine_or_session) obj = ses.get(cls, id_) clean_session(ses, auto_close) return obj @classmethod def by_sql( cls, engine_or_session: Union[Engine, Session], sql: Union[str, TextClause], ) -> List['ExtendedBase']: """ Query with sql statement or texture sql. Examples:: class User(Base): id = Column(Integer, primary_key) name = Column(String) with Session(engine) as session: user_list = [ User(id=1, name="Alice"), User(id=2, name="Bob"), User(id=3, name="Cathy"), ] session.add_all(user_list) session.commit() results = User.by_sql( "SELECT * FROM extended_declarative_base_user", engine, ) # [User(id=1, name="Alice"), User(id=2, name="Bob"), User(id=3, name="Cathy")] print(results) **中文文档** 一个简单的语法糖, 允许用户直接用 SQL 的字符串进行查询. """ if isinstance(sql, str): sql_stmt = text(sql) elif isinstance(sql, TextClause): sql_stmt = sql else: # pragma: no cover raise TypeError ses, auto_close = ensure_session(engine_or_session) results = ses.scalars(select(cls).from_statement(sql_stmt)).all() clean_session(ses, auto_close) return results @classmethod def smart_insert( cls, engine_or_session: Union[Engine, Session], obj_or_objs: Union['ExtendedBase', List['ExtendedBase']], minimal_size: int = 5, _op_counter: int = 0, _insert_counter: int = 0, ) -> Tuple[int, int]: """ An optimized Insert strategy. \ :param minimal_size: internal bulk size for each attempts :param _op_counter: number of successful bulk INSERT sql invoked :param _insert_counter: number of successfully inserted objects. :return: number of bulk INSERT sql invoked. Usually it is greatly smaller than ``len(data)``. and also return the number of successfully inserted objects. .. warning:: This operation is not atomic, if you force stop the program, then it could be only partially completed **中文文档** 在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要 远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略: 1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。 2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。 3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。 直到成功为止。 该 Insert 策略在内存上需要额外的 sqrt(n) 的开销, 跟原数据相比体积很小。 但时间上是各种情况下平均最优的。 1.4 以后的重要变化: session 变得更聪明了. """ ses, auto_close = ensure_session(engine_or_session) if isinstance(obj_or_objs, list): # 首先进行尝试bulk insert try: ses.add_all(obj_or_objs) ses.commit() _op_counter += 1 _insert_counter += len(obj_or_objs) # 失败了 except (IntegrityError, FlushError): ses.rollback() # 分析数据量 n = len(obj_or_objs) # 如果数据条数多于一定数量 if n >= minimal_size ** 2: # 则进行分包 n_chunk = math.floor(math.sqrt(n)) for chunk in grouper_list(obj_or_objs, n_chunk): ( _op_counter, _insert_counter, ) = cls.smart_insert( engine_or_session=ses, obj_or_objs=chunk, minimal_size=minimal_size, _op_counter=_op_counter, _insert_counter=_insert_counter, ) # 否则则一条条地逐条插入 else: for obj in obj_or_objs: try: ses.add(obj) ses.commit() _op_counter += 1 _insert_counter += 1 except (IntegrityError, FlushError): ses.rollback() else: try: ses.add(obj_or_objs) ses.commit() _op_counter += 1 _insert_counter += 1 except (IntegrityError, FlushError): ses.rollback() clean_session(ses, auto_close) return _op_counter, _insert_counter @classmethod def update_all( cls, engine_or_session: Union[Engine, Session], obj_or_objs: Union['ExtendedBase', List['ExtendedBase']], include_null: bool = True, upsert: bool = False, ) -> Tuple[int, int]: """ The :meth:`sqlalchemy.crud.updating.update_all` function in ORM syntax. This operation **IS NOT ATOMIC**. It is a greedy operation, trying to update as much as it can. :param engine_or_session: an engine created by``sqlalchemy.create_engine``. :param obj_or_objs: single object or list of object :param include_null: update those None value field or not :param upsert: if True, then do insert also. :return: number of row been changed """ update_counter = 0 insert_counter = 0 ses, auto_close = ensure_session(engine_or_session) obj_or_objs = ensure_list(obj_or_objs) # type: List[ExtendedBase] objs_to_insert = list() for obj in obj_or_objs: res = ses.execute( update(cls). where(*[ field == value for field, value in zip(obj.pk_fields(), obj.pk_values()) ]). values(**obj.to_dict(include_null=include_null)) ) if res.rowcount: update_counter += 1 else: objs_to_insert.append(obj) if upsert: try: ses.add_all(objs_to_insert) ses.commit() insert_counter += len(objs_to_insert) except (IntegrityError, FlushError): # pragma: no cover ses.rollback() else: ses.commit() clean_session(ses, auto_close) return update_counter, insert_counter @classmethod def upsert_all( cls, engine_or_session: Union[Engine, Session], obj_or_objs: Union['ExtendedBase', List['ExtendedBase']], include_null: bool = True, ) -> Tuple[int, int]: """ The :meth:`sqlalchemy.crud.updating.upsert_all` function in ORM syntax. :param engine_or_session: an engine created by``sqlalchemy.create_engine``. :param obj_or_objs: single object or list of object :param include_null: update those None value field or not :return: number of row been changed """ return cls.update_all( engine_or_session=engine_or_session, obj_or_objs=obj_or_objs, include_null=include_null, upsert=True, ) @classmethod def delete_all( cls, engine_or_session: Union[Engine, Session], ): # pragma: no cover """ Delete all data in this table. TODO: add a boolean flag for cascade remove """ ses, auto_close = ensure_session(engine_or_session) ses.execute(cls.__table__.delete()) ses.commit() clean_session(ses, auto_close) @classmethod def count_all( cls, engine_or_session: Union[Engine, Session], ) -> int: """ Return number of rows in this table. """ ses, auto_close = ensure_session(engine_or_session) count = ses.execute(select(func.count()).select_from(cls)).one()[0] clean_session(ses, auto_close) return count @classmethod def select_all( cls, engine_or_session: Union[Engine, Session], ) -> List['ExtendedBase']: """ """ ses, auto_close = ensure_session(engine_or_session) results = ses.scalars(select(cls)).all() clean_session(ses, auto_close) return results @classmethod def random_sample( cls, engine_or_session: Union[Engine, Session], limit: int = None, perc: int = None, ) -> List['ExtendedBase']: """ Return random ORM instance. :rtype: List[ExtendedBase] """ ses, auto_close = ensure_session(engine_or_session) ensure_exact_one_arg_is_not_none(limit, perc) if limit is not None: results = ses.scalars( select(cls).order_by(func.random()).limit(limit) ).all() elif perc is not None: selectable = cls.__table__.tablesample( func.bernoulli(perc), name="alias", seed=func.random() ) args = [ getattr(selectable.c, column.name) for column in cls.__table__.columns ] stmt = select(*args) results = [cls(**dict(row)) for row in ses.execute(stmt)] else: raise ValueError clean_session(ses, auto_close) return results
(**kwargs)
64,553
sqlalchemy.orm.decl_base
__init__
A simple constructor that allows initialization from kwargs. Sets attributes on the constructed instance using the names and values in ``kwargs``. Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.
def _declarative_constructor(self, **kwargs): """A simple constructor that allows initialization from kwargs. Sets attributes on the constructed instance using the names and values in ``kwargs``. Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships. """ cls_ = type(self) for k in kwargs: if not hasattr(cls_, k): raise TypeError( "%r is an invalid keyword argument for %s" % (k, cls_.__name__) ) setattr(self, k, kwargs[k])
(self, **kwargs)
64,554
sqlalchemy_mate.orm.extended_declarative_base
__repr__
null
def __repr__(self): kwargs = list() for attr, value in self.items(): kwargs.append("%s=%r" % (attr, value)) return "%s(%s)" % (self.__class__.__name__, ", ".join(kwargs))
(self)
64,556
sqlalchemy_mate.orm.extended_declarative_base
absorb
For attributes of others that value is not None, assign it to self. **中文文档** 将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。
def absorb( self, other: 'ExtendedBase', ignore_none: bool = True, ) -> 'ExtendedBase': """ For attributes of others that value is not None, assign it to self. **中文文档** 将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。 """ if not isinstance(other, self.__class__): raise TypeError("`other` has to be a instance of %s!" % self.__class__) if ignore_none: for attr, value in other.items(): if value is not None: setattr(self, attr, deepcopy(value)) else: for attr, value in other.items(): setattr(self, attr, deepcopy(value)) return self
(self, other: sqlalchemy_mate.orm.extended_declarative_base.ExtendedBase, ignore_none: bool = True) -> sqlalchemy_mate.orm.extended_declarative_base.ExtendedBase
64,557
sqlalchemy_mate.orm.extended_declarative_base
glance
Print itself, only display attributes defined in :attr:`ExtendedBase._settings_major_attrs` :param _verbose: internal param for unit testing
def glance(self, _verbose: bool = True): # pragma: no cover """ Print itself, only display attributes defined in :attr:`ExtendedBase._settings_major_attrs` :param _verbose: internal param for unit testing """ if self._settings_major_attrs is None: msg = ("Please specify attributes you want to include " "in `class._settings_major_attrs`!") raise NotImplementedError(msg) kwargs = [ (attr, getattr(self, attr)) for attr in self._major_attrs() ] text = "{classname}({kwargs})".format( classname=self.__class__.__name__, kwargs=", ".join([ "%s=%r" % (attr, value) for attr, value in kwargs ]) ) if _verbose: # pragma: no cover print(text)
(self, _verbose: bool = True)
64,558
sqlalchemy_mate.orm.extended_declarative_base
id_field_value
If only one primary_key, then return the value of primary key. Otherwise, raise ValueError
def id_field_value(self): """ If only one primary_key, then return the value of primary key. Otherwise, raise ValueError """ return getattr(self, self.id_field_name())
(self)
64,559
sqlalchemy_mate.orm.extended_declarative_base
items
return list of pair of name and value of all declared columns.
def items(self) -> List[Tuple[str, Any]]: """ return list of pair of name and value of all declared columns. """ return [ (c.name, getattr(self, c.name, None)) for c in self.__table__.columns ]
(self) -> List[Tuple[str, Any]]
64,560
sqlalchemy_mate.orm.extended_declarative_base
pk_values
Primary key values :rtype: tuple
def pk_values(self) -> tuple: """ Primary key values :rtype: tuple """ return tuple([getattr(self, name) for name in self.pk_names()])
(self) -> tuple
64,561
sqlalchemy_mate.orm.extended_declarative_base
revise
Revise attributes value with dictionary data. **中文文档** 将一个字典中的数据更新到本条文档. 当且仅当数据值不为 None 时.
def revise( self, data: dict, ignore_none: bool = True, ) -> 'ExtendedBase': """ Revise attributes value with dictionary data. **中文文档** 将一个字典中的数据更新到本条文档. 当且仅当数据值不为 None 时. """ if not isinstance(data, dict): raise TypeError("`data` has to be a dict!") if ignore_none: for key, value in data.items(): if value is not None: setattr(self, key, deepcopy(value)) else: for key, value in data.items(): setattr(self, key, deepcopy(value)) return self
(self, data: dict, ignore_none: bool = True) -> sqlalchemy_mate.orm.extended_declarative_base.ExtendedBase
64,562
sqlalchemy_mate.orm.extended_declarative_base
to_OrderedDict
Convert to OrderedDict.
def to_OrderedDict( self, include_null: bool = True, ) -> OrderedDict: """ Convert to OrderedDict. """ if include_null: return OrderedDict(self.items()) else: items = list() for c in self.__table__._columns: try: items.append((c.name, self.__dict__[c.name])) except KeyError: pass return OrderedDict(items)
(self, include_null: bool = True) -> collections.OrderedDict
64,563
sqlalchemy_mate.orm.extended_declarative_base
to_dict
Convert to dict. :rtype: dict
def to_dict(self, include_null=True) -> Dict[str, Any]: """ Convert to dict. :rtype: dict """ if include_null: return dict(self.items()) else: return { attr: value for attr, value in self.__dict__.items() if not attr.startswith("_sa_") }
(self, include_null=True) -> Dict[str, Any]
64,564
sqlalchemy_mate.orm.extended_declarative_base
values
return list of value of all declared columns.
def values(self) -> list: """ return list of value of all declared columns. """ return [getattr(self, c.name, None) for c in self.__table__.columns]
(self) -> list
64,565
sqlalchemy_mate.pkg.timeout_decorator.timeout_decorator
TimeoutError
Thrown when a timeout occurs in the `timeout` context manager.
class TimeoutError(AssertionError): """Thrown when a timeout occurs in the `timeout` context manager.""" def __init__(self, value="Timed Out"): self.value = value def __str__(self): return repr(self.value)
(value='Timed Out')
64,566
sqlalchemy_mate.pkg.timeout_decorator.timeout_decorator
__init__
null
def __init__(self, value="Timed Out"): self.value = value
(self, value='Timed Out')
64,578
sqlalchemy_mate.utils
test_connection
null
def test_connection(engine, timeout=3): @timeout_decorator.timeout(timeout) def _test_connection(engine): v = engine.execute(sa.text("SELECT 1;")).fetchall()[0][0] assert v == 1 try: _test_connection(engine) return True except timeout_decorator.TimeoutError: raise timeout_decorator.TimeoutError( "time out in %s seconds!" % timeout) except AssertionError: # pragma: no cover raise ValueError except Exception as e: raise e
(engine, timeout=3)
64,582
humanize.i18n
activate
Activate internationalisation. Set `locale` as current locale. Search for locale in directory `path`. Args: locale (str): Language name, e.g. `en_GB`. path (str): Path to search for locales. Returns: dict: Translations. Raises: Exception: If humanize cannot find the locale folder.
def activate(locale: str, path: str | None = None) -> gettext_module.NullTranslations: """Activate internationalisation. Set `locale` as current locale. Search for locale in directory `path`. Args: locale (str): Language name, e.g. `en_GB`. path (str): Path to search for locales. Returns: dict: Translations. Raises: Exception: If humanize cannot find the locale folder. """ if path is None: path = _get_default_locale_path() if path is None: msg = ( "Humanize cannot determinate the default location of the 'locale' folder. " "You need to pass the path explicitly." ) raise Exception(msg) if locale not in _TRANSLATIONS: translation = gettext_module.translation("humanize", path, [locale]) _TRANSLATIONS[locale] = translation _CURRENT.locale = locale return _TRANSLATIONS[locale]
(locale: str, path: Optional[str] = None) -> gettext.NullTranslations
64,583
humanize.number
apnumber
Converts an integer to Associated Press style. Examples: ```pycon >>> apnumber(0) 'zero' >>> apnumber(5) 'five' >>> apnumber(10) '10' >>> apnumber("7") 'seven' >>> apnumber("foo") 'foo' >>> apnumber(None) 'None' ``` Args: value (int, float, str): Integer to convert. Returns: str: For numbers 0-9, the number spelled out. Otherwise, the number. This always returns a string unless the value was not `int`-able, then `str(value)` is returned.
def apnumber(value: NumberOrString) -> str: """Converts an integer to Associated Press style. Examples: ```pycon >>> apnumber(0) 'zero' >>> apnumber(5) 'five' >>> apnumber(10) '10' >>> apnumber("7") 'seven' >>> apnumber("foo") 'foo' >>> apnumber(None) 'None' ``` Args: value (int, float, str): Integer to convert. Returns: str: For numbers 0-9, the number spelled out. Otherwise, the number. This always returns a string unless the value was not `int`-able, then `str(value)` is returned. """ try: if not math.isfinite(float(value)): return _format_not_finite(float(value)) value = int(value) except (TypeError, ValueError): return str(value) if not 0 <= value < 10: return str(value) return ( _("zero"), _("one"), _("two"), _("three"), _("four"), _("five"), _("six"), _("seven"), _("eight"), _("nine"), )[value]
(value: float | str) -> str
64,584
humanize.number
clamp
Returns number with the specified format, clamped between floor and ceil. If the number is larger than ceil or smaller than floor, then the respective limit will be returned, formatted and prepended with a token specifying as such. Examples: ```pycon >>> clamp(123.456) '123.456' >>> clamp(0.0001, floor=0.01) '<0.01' >>> clamp(0.99, format="{:.0%}", ceil=0.99) '99%' >>> clamp(0.999, format="{:.0%}", ceil=0.99) '>99%' >>> clamp(1, format=intword, floor=1e6, floor_token="under ") 'under 1.0 million' >>> clamp(None) is None True ``` Args: value (int, float): Input number. format (str OR callable): Can either be a formatting string, or a callable function that receives value and returns a string. floor (int, float): Smallest value before clamping. ceil (int, float): Largest value before clamping. floor_token (str): If value is smaller than floor, token will be prepended to output. ceil_token (str): If value is larger than ceil, token will be prepended to output. Returns: str: Formatted number. The output is clamped between the indicated floor and ceil. If the number is larger than ceil or smaller than floor, the output will be prepended with a token indicating as such.
def clamp( value: float, format: str = "{:}", floor: float | None = None, ceil: float | None = None, floor_token: str = "<", ceil_token: str = ">", ) -> str: """Returns number with the specified format, clamped between floor and ceil. If the number is larger than ceil or smaller than floor, then the respective limit will be returned, formatted and prepended with a token specifying as such. Examples: ```pycon >>> clamp(123.456) '123.456' >>> clamp(0.0001, floor=0.01) '<0.01' >>> clamp(0.99, format="{:.0%}", ceil=0.99) '99%' >>> clamp(0.999, format="{:.0%}", ceil=0.99) '>99%' >>> clamp(1, format=intword, floor=1e6, floor_token="under ") 'under 1.0 million' >>> clamp(None) is None True ``` Args: value (int, float): Input number. format (str OR callable): Can either be a formatting string, or a callable function that receives value and returns a string. floor (int, float): Smallest value before clamping. ceil (int, float): Largest value before clamping. floor_token (str): If value is smaller than floor, token will be prepended to output. ceil_token (str): If value is larger than ceil, token will be prepended to output. Returns: str: Formatted number. The output is clamped between the indicated floor and ceil. If the number is larger than ceil or smaller than floor, the output will be prepended with a token indicating as such. """ if value is None: return None if not math.isfinite(value): return _format_not_finite(value) if floor is not None and value < floor: value = floor token = floor_token elif ceil is not None and value > ceil: value = ceil token = ceil_token else: token = "" if isinstance(format, str): return token + format.format(value) if callable(format): return token + format(value) msg = ( "Invalid format. Must be either a valid formatting string, or a function " "that accepts value and returns a string." ) raise ValueError(msg)
(value: float, format: str = '{:}', floor: Optional[float] = None, ceil: Optional[float] = None, floor_token: str = '<', ceil_token: str = '>') -> str
64,585
humanize.i18n
deactivate
Deactivate internationalisation.
def deactivate() -> None: """Deactivate internationalisation.""" _CURRENT.locale = None
() -> NoneType
64,586
humanize.i18n
decimal_separator
Return the decimal separator for a locale, default to dot. Returns: str: Decimal separator.
def decimal_separator() -> str: """Return the decimal separator for a locale, default to dot. Returns: str: Decimal separator. """ try: sep = _DECIMAL_SEPARATOR[_CURRENT.locale] except (AttributeError, KeyError): sep = "." return sep
() -> str