EasyTL Documentation

Contents

EasyTL Documentation#

Subpackages#

Submodules#

easytl.easytl module#

class easytl.easytl.EasyTL#

Bases: object

EasyTL global client, used to interact with Translation APIs.

Use set_credentials() to set the credentials for the specified API type. (e.g. set_credentials("deepl", "your_api_key")() or set_credentials("google translate", "path/to/your/credentials.json")())

Use test_credentials() to test the validity of the credentials for the specified API type. (e.g. test_credentials("deepl")()) (Optional) Done automatically when translating.

Use translate() to translate text using the specified service with its appropriate kwargs. Or specify the service by calling the specific translation function. (e.g. openai_translate())

Use calculate_cost() to calculate the cost of translating text using the specified service. (Optional)

See the documentation for each function for more information.

static anthropic_translate(text: str | Iterable[str] | ModelTranslationMessage | Iterable[ModelTranslationMessage], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', response_schema: str | Mapping[str, Any] | None = None, translation_delay: float | None = None, translation_instructions: str | None = None, model: str = 'claude-3-haiku-20240307', temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, stop_sequences: List[str] | NotGiven = NOT_GIVEN, max_output_tokens: int | NotGiven = NOT_GIVEN) List[str] | str | Message | List[Message] | ToolsBetaMessage | List[ToolsBetaMessage]#

Translates the given text using Anthropic.

This function assumes that the API key has already been set.

Translation instructions default to translating the text to English. To change this, specify the instructions.

This function is not for use for real-time translation, nor for generating multiple translation candidates. Another function may be implemented for this given demand.

Due to how Anthropic’s API works, NOT_GIVEN is treated differently than None. If a parameter is set to NOT_GIVEN, it is not passed to the API.

Anthropic’s JSON response is quite unsophisticated and also in Beta, it costs a lot of extra tokens to return a json response. It’s also inconsistent. Be careful when using it.

Parameters:
  • text (Union[str, Iterable[str], ModelTranslationMessage, Iterable[ModelTranslationMessage]]) – The text to translate. It can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an Anthropic translation function.

  • decorator (Callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this is None, Anthropic will retry the request twice if it fails.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal["text", "raw", "json", "raw_json"] or None) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, an AnthropicMessage object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, an AnthropicMessage object, but with the content as a json-parseable string.

  • response_schema (str or Mapping[str, Any] or None) – The schema to use for the response. If None, no schema is used. This is only used if the response type is ‘json’ or ‘json_raw’. EasyTL only validates the schema to the extend that it is None or a valid json. It does not validate the contents of the json.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or SystemTranslationMessage or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘claude-3-haiku-20240307’, ‘claude-3-sonnet-20240229’ or ‘claude-3-opus-20240229’)

  • temperature (float or NotGiven) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float or NotGiven) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • top_k (int or NotGiven) – The top k tokens to consider. Generally, alter this or temperature or top_p, not all three.

  • stop_sequences (List[str] or NotGiven) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_output_tokens (int or NotGiven) – The maximum number of tokens to output.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of AnthropicMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

Return type:

Union[List[str], str, AnthropicMessage, List[AnthropicMessage], AnthropicToolsBetaMessage, List[AnthropicToolsBetaMessage]]

async static anthropic_translate_async(text: str | Iterable[str] | ModelTranslationMessage | Iterable[ModelTranslationMessage], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', response_schema: str | Mapping[str, Any] | None = None, semaphore: int | None = 5, translation_delay: float | None = None, translation_instructions: str | None = None, model: str = 'claude-3-haiku-20240307', temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, stop_sequences: List[str] | NotGiven = NOT_GIVEN, max_output_tokens: int | NotGiven = NOT_GIVEN) List[str] | str | Message | List[Message] | ToolsBetaMessage | List[ToolsBetaMessage]#

Asynchronous version of anthropic_translate().

Translates the given text using Anthropic.

This function assumes that the API key has already been set.

Translation instructions default to translating the text to English. To change this, specify the instructions.

This function is not for use for real-time translation, nor for generating multiple translation candidates. Another function may be implemented for this given demand.

Due to how Anthropic’s API works, NOT_GIVEN is treated differently than None. If a parameter is set to NOT_GIVEN, it is not passed to the API.

Anthropic’s JSON response is quite unsophisticated and also in Beta, it costs a lot of extra tokens to return a json response. It’s also inconsistent. Be careful when using it.

Parameters:
  • text (Union[str, Iterable[str], ModelTranslationMessage, Iterable[ModelTranslationMessage]]) – The text to translate. It can be a string, a ModelTranslationMessage, or an iterable of strings or ModelTranslationMessages.

  • override_previous_settings (bool, optional) – Whether to override the previous settings that were used during the last call to an Anthropic translation function.

  • decorator (Callable or None, optional) – The decorator to use when translating. Typically for exponential backoff retrying. If this is None, Anthropic will retry the request twice if it fails.

  • logging_directory (str or None, optional) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal["text", "raw", "json", "raw_json"] or None, optional) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, an AnthropicMessage object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, an AnthropicMessage object, but with the content as a json-parseable string.

  • response_schema (str or Mapping[str, Any] or None, optional) – The schema to use for the response. If None, no schema is used. This is only used if the response type is ‘json’ or ‘json_raw’. EasyTL only validates the schema to the extend that it is None or a valid json. It does not validate the contents of the json.

  • semaphore (int or None, optional) – The number of concurrent requests to make. Default is 5.

  • translation_delay (float or None, optional) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or SystemTranslationMessage or None, optional) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str, optional) – The model to use. (E.g. ‘claude-3-haiku-20240307’, ‘claude-3-sonnet-20240229’ or ‘claude-3-opus-20240229’)

  • temperature (float or NotGiven, optional) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float or NotGiven, optional) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • top_k (int or NotGiven, optional) – The top k tokens to consider. Generally, alter this or temperature or top_p, not all three.

  • stop_sequences (List[str] or NotGiven, optional) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_output_tokens (int or NotGiven, optional) – The maximum number of tokens to output.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of AnthropicMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

Return type:

Union[List[str], str, AnthropicMessage, List[AnthropicMessage], AnthropicToolsBetaMessage, List[AnthropicToolsBetaMessage]]

static azure_translate(text: str | Iterable[str], target_lang: str = 'en', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'json'] | None = 'text', translation_delay: float | None = None, api_version: str = '3.0', azure_region: str = 'global', azure_endpoint: str = 'https://api.cognitive.microsofttranslator.com/', source_lang: str | None = None) List[str] | str#

Translates the given text to the target language using Azure.

This function assumes that the API key has already been set.

It is unknown whether Azure Translate has backoff retrying implemented. Assume it does not exist.

Default api_version, azure_region, and azure_endpoint values should be fine for most users.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable of strings.

  • target_lang (str) – The target language for translation. Default is ‘en’. These are ISO 639-1 language codes.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an Azure translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (literal["text", "json"]) – The type of response to return. ‘text’ returns the translated text, ‘json’ returns the original response in json format.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • api_version (str) – The version of the Azure Translator API. Default is ‘3.0’.

  • azure_region (str) – The Azure region to use for translation. Default is ‘global’.

  • azure_endpoint (str) – The Azure Translator API endpoint. Default is ‘https://api.cognitive.microsofttranslator.com/’.

  • source_lang (str or None) – The source language of the text. If None, the service will attempt to detect the language.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise.

Return type:

str or list[str]

async static azure_translate_async(text: str | Iterable[str], target_lang: str = 'en', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'json'] | None = 'text', semaphore: int | None = 15, translation_delay: float | None = None, api_version: str = '3.0', azure_region: str = 'global', azure_endpoint: str = 'https://api.cognitive.microsofttranslator.com/', source_lang: str | None = None) List[str] | str#

Asynchronous version of azure_translate().

Translates the given text to the target language using Azure.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable of strings.

  • target_lang (str) – The target language for translation. Default is ‘en’. These are ISO 639-1 language codes.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an Azure translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (literal["text", "json"]) – The type of response to return. ‘text’ returns the translated text, ‘json’ returns the original response in json format.

  • semaphore (int) – The number of concurrent requests to make. Default is 15.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • api_version (str) – The version of the Azure Translator API. Default is ‘3.0’.

  • azure_region (str) – The Azure region to use for translation. Default is ‘global’.

  • azure_endpoint (str) – The Azure Translator API endpoint. Default is ‘https://api.cognitive.microsofttranslator.com/’.

  • source_lang (str or None) – The source language of the text. If None, the service will attempt to detect the language.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise.

Return type:

str or list[str]

static calculate_cost(text: str | Iterable[str], service: Literal['deepl', 'openai', 'gemini', 'google translate', 'anthropic', 'azure'] | None = 'deepl', model: str | None = None, translation_instructions: str | None = None) Tuple[int, float, str]#

Calculates the cost of translating the given text using the specified service.

For LLMs, the cost is based on the default model unless specified.

Model and Translation Instructions are ignored for DeepL, Google Translate, and Azure.

For DeepL, Azure, and Google Translate, the number of tokens is the number of characters in the text. The returned model is the name of the service.

Note that Anthropic’s cost estimate is pretty sketchy and can be inaccurate. Refer to the actual response object for the cost or the API panel. This is because their tokenizer is not public, and we’re forced to estimate.

Parameters:
  • text (str or iterable) – The text to translate.

  • service (str) – The service to use for translation.

  • model (str or None) – The model to use for translation. If None, the default model is used.

  • translation_instructions (str or None) – The translation instructions to use.

Returns:

The number of tokens/characters in the text, the cost of translating the text, and the model used for translation.

Return type:

tuple[int, float, str]

static deepl_translate(text: str | Iterable[str], target_lang: str | Language = 'EN-US', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw'] | None = 'text', translation_delay: float | None = None, source_lang: str | Language | None = None, context: str | None = None, split_sentences: Literal['OFF', 'ALL', 'NO_NEWLINES'] | SplitSentences | None = 'ALL', preserve_formatting: bool | None = None, formality: Literal['default', 'more', 'less', 'prefer_more', 'prefer_less'] | Formality | None = None, glossary: str | GlossaryInfo | None = None, tag_handling: Literal['xml', 'html'] | None = None, outline_detection: bool | None = None, non_splitting_tags: str | List[str] | None = None, splitting_tags: str | List[str] | None = None, ignore_tags: str | List[str] | None = None) List[str] | str | List[TextResult] | TextResult#

Translates the given text to the target language using DeepL.

This function assumes that the API key has already been set.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable.

  • target_lang (str or Language) – The target language to translate to.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a DeepL translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this parameter is None, DeepL will retry your request 5 times before failing. Otherwise, the given decorator will be used.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (literal["text", "raw"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a TextResult object.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • source_lang (str or Language or None) – The source language to translate from.

  • context (str or None) – Additional information for the translator to be considered when translating. Not translated itself. This is a DeepL alpha feature and may be removed at any time.

  • split_sentences (literal or SplitSentences or None) – How to split sentences.

  • preserve_formatting (bool or None) – Whether to preserve formatting.

  • formality (literal or Formality or None) – The formality level to use.

  • glossary (str or GlossaryInfo or None) – The glossary to use.

  • tag_handling (literal or None) – How to handle tags.

  • outline_detection (bool or None) – Whether to detect outlines.

  • non_splitting_tags (str or list or None) – Tags that should not be split.

  • splitting_tags (str or list or None) – Tags that should be split.

  • ignore_tags (str or list or None) – Tags that should be ignored.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of TextResult objects if the response type is ‘raw’ and input was an iterable, a TextResult object otherwise.

Return type:

str or list - str or TextResult or list - TextResult

async static deepl_translate_async(text: str | Iterable[str], target_lang: str | Language = 'EN-US', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw'] | None = 'text', semaphore: int | None = 15, translation_delay: float | None = None, source_lang: str | Language | None = None, context: str | None = None, split_sentences: Literal['OFF', 'ALL', 'NO_NEWLINES'] | SplitSentences | None = 'ALL', preserve_formatting: bool | None = None, formality: Literal['default', 'more', 'less', 'prefer_more', 'prefer_less'] | Formality | None = None, glossary: str | GlossaryInfo | None = None, tag_handling: Literal['xml', 'html'] | None = None, outline_detection: bool | None = None, non_splitting_tags: str | List[str] | None = None, splitting_tags: str | List[str] | None = None, ignore_tags: str | List[str] | None = None) List[str] | str | List[TextResult] | TextResult#

Asynchronous version of deepl_translate().

Translates the given text to the target language using DeepL.

Will generally be faster for iterables. Order is preserved.

This function assumes that the API key has already been set.

Parameters:
  • text (Union[str, Iterable[str]]) – The text to translate. It can be a string or an iterable of strings.

  • target_lang (Union[str, Language]) – The target language to translate to.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a DeepL translation function.

  • decorator (Callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this parameter is None, DeepL will retry your request 5 times before failing. Otherwise, the given decorator will be used.

  • logging_directory (Union[str, None]) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal['text', 'raw']) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a TextResult object.

  • semaphore (int) – The number of concurrent requests to make. Default is 15.

  • translation_delay (Union[float, None]) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • source_lang (Union[str, Language, None]) – The source language to translate from.

  • context (Union[str, None]) – Additional information for the translator to be considered when translating. Not translated itself. This is a DeepL alpha feature and may be removed at any time.

  • split_sentences (Literal['OFF', 'ALL', 'NO_NEWLINES', SplitSentences, None]) – How to split sentences.

  • preserve_formatting (Union[bool, None]) – Whether to preserve formatting.

  • formality (Literal['default', 'more', 'less', 'prefer_more', 'prefer_less', Formality, None]) – The formality level to use.

  • glossary (Union[str, GlossaryInfo, None]) – The glossary to use.

  • tag_handling (Union[Literal['xml', 'html'], None]) – How to handle tags.

  • outline_detection (Union[bool, None]) – Whether to detect outlines.

  • non_splitting_tags (Union[str, List[str], None]) – Tags that should not be split.

  • splitting_tags (Union[str, List[str], None]) – Tags that should be split.

  • ignore_tags (Union[str, List[str], None]) – Tags that should be ignored.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of TextResult objects if the response type is ‘raw’ and input was an iterable, a TextResult object otherwise.

Return type:

Union[List[str], str, List[TextResult], TextResult]

static gemini_translate(text: str | Iterable[str], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', response_schema: str | Mapping[str, Any] | None = None, translation_delay: float | None = None, translation_instructions: str | None = None, model: str = 'gemini-pro', temperature: float = 0.5, top_p: float = 0.9, top_k: int = 40, stop_sequences: List[str] | None = None, max_output_tokens: int | None = None) List[str] | str | GenerateContentResponse | List[GenerateContentResponse]#

Translates the given text using Gemini.

This function assumes that the API key has already been set.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a Gemini translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (str, literal["text", "raw", "json", "raw_json"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a GenerateContentResponse object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, a GenerateContentResponse object, but with the content as a json-parseable string.

  • response_schema (str or mapping or None) – The schema to use for the response. If None, no schema is used. This is only used if the response type is ‘json’ or ‘json_raw’. EasyTL only validates the schema to the extend that it is None or a valid json. It does not validate the contents of the json.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘gemini-pro’ or ‘gemini-pro-1.5-latest’)

  • temperature (float) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • top_k (int) – The top k tokens to consider. Generally, alter this or temperature or top_p, not all three.

  • stop_sequences (list or None) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_output_tokens (int or None) – The maximum number of tokens to output.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of GenerateContentResponse objects if the response type is ‘raw’ and input was an iterable, a GenerateContentResponse object otherwise.

Return type:

str or list[str] or GenerateContentResponse or list[GenerateContentResponse]

async static gemini_translate_async(text: str | Iterable[str], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', response_schema: str | Mapping[str, Any] | None = None, semaphore: int | None = 5, translation_delay: float | None = None, translation_instructions: str | None = None, model: str = 'gemini-pro', temperature: float = 0.5, top_p: float = 0.9, top_k: int = 40, stop_sequences: List[str] | None = None, max_output_tokens: int | None = None) List[str] | str | AsyncGenerateContentResponse | List[AsyncGenerateContentResponse]#

Asynchronous version of gemini_translate().

Translates the given text using Gemini.

This function assumes that the API key has already been set.

Translation instructions default to translating the text to English. To change this, specify the instructions.

This function is not for use for real-time translation, nor for generating multiple translation candidates. Another function may be implemented for this given demand.

It is not known whether Gemini has backoff retrying implemented. Assume it does not exist.

Parameters:
  • text (str or iterable) – The text to translate. Can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a Gemini translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (str) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, an AsyncGenerateContentResponse object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, an AsyncGenerateContentResponse object, but with the content as a json-parseable string.

  • response_schema (str or mapping or None) – The schema to use for the response. If None, no schema is used. This is only used if the response type is ‘json’ or ‘json_raw’. EasyTL only validates the schema to the extend that it is None or a valid json. It does not validate the contents of the json.

  • semaphore (int) – The number of concurrent requests to make. Default is 5 for 1.0 and 2 for 1.5 gemini models. For Gemini, it is recommend to use translation_delay along with the semaphore to prevent rate limiting.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘gemini-pro’ or ‘gemini-pro-1.5-latest’)

  • temperature (float) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • top_k (int) – The top k tokens to consider. Generally, alter this or temperature or top_p, not all three.

  • stop_sequences (list or None) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_output_tokens (int or None) – The maximum number of tokens to output.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of AsyncGenerateContentResponse objects if the response type is ‘raw’ and input was an iterable, a AsyncGenerateContentResponse object otherwise.

Return type:

str or list or AsyncGenerateContentResponse

static googletl_translate(text: str | Iterable[str], target_lang: str = 'en', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw'] | None = 'text', translation_delay: float | None = None, format: Literal['text', 'html'] = 'text', source_lang: str | None = None) List[str] | str | List[Any] | Any#

Translates the given text to the target language using Google Translate.

This function assumes that the credentials have already been set.

It is unknown whether Google Translate has backoff retrying implemented. Assume it does not exist.

Google Translate v2 API is poorly documented and type hints are near non-existent. typing.Any return types are used for the raw response type.

Parameters:
  • text (Union[str, Iterable[str]]) – The text to translate. It can be a string or an iterable.

  • target_lang (str) – The target language to translate to.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a Google Translate function.

  • decorator (Callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal["text", "raw"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • format (Literal["text", "html"]) – The format of the text. Can be ‘text’ or ‘html’. Default is ‘text’. Google Translate appears to be able to translate html but this has not been tested thoroughly by EasyTL.

  • source_lang (str or None) – The source language to translate from.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of any objects if the response type is ‘raw’ and input was an iterable, an any object otherwise.

Return type:

Union[str, List[str], Any, List[Any]]

async static googletl_translate_async(text: str | Iterable[str], target_lang: str = 'en', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw'] | None = 'text', semaphore: int | None = 15, translation_delay: float | None = None, format: Literal['text', 'html'] = 'text', source_lang: str | None = None) List[str] | str | List[Any] | Any#

Asynchronous version of googletl_translate().

Translates the given text to the target language using Google Translate. Will generally be faster for iterables. Order is preserved.

This function assumes that the credentials have already been set.

It is unknown whether Google Translate has backoff retrying implemented. Assume it does not exist.

Google Translate v2 API is poorly documented and type hints are near non-existent. typing.Any return types are used for the raw response type.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable.

  • target_lang (str) – The target language to translate to.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a Google Translate function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (literal["text", "raw"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response.

  • semaphore (int) – The number of concurrent requests to make. Default is 15.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • format (str or None) – The format of the text. Can be ‘text’ or ‘html’. Default is ‘text’. Google Translate appears to be able to translate html but this has not been tested thoroughly by EasyTL.

  • source_lang (str or None) – The source language to translate from.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of any objects if the response type is ‘raw’ and input was an iterable, an any object otherwise.

Return type:

str or list[str] or any or list[any]

static openai_translate(text: str | Iterable[str] | ModelTranslationMessage | Iterable[ModelTranslationMessage], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', translation_delay: float | None = None, translation_instructions: str | SystemTranslationMessage | None = None, model: str = 'gpt-4', temperature: float | None | NotGiven = NOT_GIVEN, top_p: float | None | NotGiven = NOT_GIVEN, stop: List[str] | None | NotGiven = NOT_GIVEN, max_tokens: int | None | NotGiven = NOT_GIVEN, presence_penalty: float | None | NotGiven = NOT_GIVEN, frequency_penalty: float | None | NotGiven = NOT_GIVEN) List[str] | str | List[ChatCompletion] | ChatCompletion#

Translates the given text using OpenAI.

This function assumes that the API key has already been set.

Translation instructions default to translating the text to English. To change this, specify the instructions.

Due to how OpenAI’s API works, NOT_GIVEN is treated differently than None. If a parameter is set to NOT_GIVEN, it is not passed to the API. If it is set to None, it is passed to the API as None.

This function is not for use for real-time translation, nor for generating multiple translation candidates. Another function may be implemented for this given demand.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an OpenAI translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this is None, OpenAI will retry the request twice if it fails.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (str, literal["text", "raw", "json", "raw_json"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a ChatCompletion object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, a ChatCompletion object, but with the content as a json-parseable string.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or SystemTranslationMessage or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘gpt-4’, ‘gpt-3.5-turbo-0125’, ‘gpt-4o’, etc.)

  • temperature (float) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • stop (list or None) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_tokens (int or None) – The maximum number of tokens to output.

  • presence_penalty (float) – The presence penalty to use. This penalizes the model from repeating the same content in the output. Shouldn’t be messed with for translation.

  • frequency_penalty (float) – The frequency penalty to use. This penalizes the model from using the same words too frequently in the output. Shouldn’t be messed with for translation.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of ChatCompletion objects if the response type is ‘raw’ and input was an iterable, a ChatCompletion object otherwise.

Return type:

str or list[str] or ChatCompletion or list[ChatCompletion]

async static openai_translate_async(text: str | Iterable[str] | ModelTranslationMessage | Iterable[ModelTranslationMessage], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', semaphore: int | None = 5, translation_delay: float | None = None, translation_instructions: str | SystemTranslationMessage | None = None, model: str = 'gpt-4', temperature: float | None | NotGiven = NOT_GIVEN, top_p: float | None | NotGiven = NOT_GIVEN, stop: List[str] | None | NotGiven = NOT_GIVEN, max_tokens: int | None | NotGiven = NOT_GIVEN, presence_penalty: float | None | NotGiven = NOT_GIVEN, frequency_penalty: float | None | NotGiven = NOT_GIVEN) List[str] | str | List[ChatCompletion] | ChatCompletion#

Asynchronous version of openai_translate().

Translates the given text using OpenAI.

Parameters:
  • text (Union[str, Iterable[str]]) – The text to translate. It can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an OpenAI translation function.

  • decorator (Callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this is None, OpenAI will retry the request twice if it fails.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal["text", "raw", "json", "raw_json"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a ChatCompletion object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, a ChatCompletion object, but with the content as a json-parseable string.

  • semaphore (int) – The number of concurrent requests to make. Default is 5.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or SystemTranslationMessage or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘gpt-4’, ‘gpt-3.5-turbo-0125’, ‘gpt-4o’, etc.)

  • temperature (float) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • stop (List[str] or None) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_tokens (int or None) – The maximum number of tokens to output.

  • presence_penalty (float) – The presence penalty to use. This penalizes the model from repeating the same content in the output. Shouldn’t be messed with for translation.

  • frequency_penalty (float) – The frequency penalty to use. This penalizes the model from using the same words too frequently in the output. Shouldn’t be messed with for translation.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of ChatCompletion objects if the response type is ‘raw’ and input was an iterable, a ChatCompletion object otherwise.

Return type:

Union[List[str], str, List[ChatCompletion], ChatCompletion]

static set_credentials(api_type: Literal['deepl', 'gemini', 'openai', 'google translate', 'anthropic', 'azure'], credentials: str) None#

Sets the credentials for the specified API type.

Parameters:
  • api_type (literal["deepl", "gemini", "openai", "google translate", "anthropic", "azure"]) – The API type to set the credentials for. Supported types are ‘deepl’, ‘gemini’, ‘openai’, ‘google translate’, ‘anthropic’, and ‘azure’.

  • credentials (str) – The credentials to set. This is an API key for deepl, gemini, anthropic, azure, and openai. For google translate, this is a path to your JSON that has your service account key.

static test_credentials(api_type: Literal['deepl', 'gemini', 'openai', 'google translate', 'anthropic', 'azure']) Tuple[bool, Exception | None]#

Tests the validity of the credentials for the specified API type.

Parameters:

api_type (str) – The API type to test the credentials for. (literal[“deepl”, “gemini”, “openai”, “google translate”, “anthropic”, “azure”])

Returns:

Whether the credentials are valid. (bool)

Return type:

bool

Returns:

The exception that was raised, if any. None otherwise. (Exception)

Return type:

Exception

static translate(text: str | Iterable[str], service: Literal['deepl', 'openai', 'gemini', 'google translate', 'anthropic', 'azure'] | None = 'deepl', **kwargs) List[str] | str | List[TextResult] | TextResult | List[ChatCompletion] | ChatCompletion | List[GenerateContentResponse] | GenerateContentResponse | List[Any] | Any | List[Message] | Message#

Translates the given text to the target language using the specified service.

Please see the documentation for the specific translation function for the service you want to use.

DeepL: deepl_translate() OpenAI: openai_translate() Gemini: gemini_translate() Google Translate: googletl_translate() Anthropic: anthropic_translate() Azure: azure_translate()

All functions can return a list of strings or a string, depending on the input. The response type can be specified to return the raw response instead: DeepL: TextResult OpenAI: ChatCompletion Gemini: GenerateContentResponse Google Translate: any Anthropic: AnthropicMessage or AnthropicToolsBetaMessage Azure: str

Parameters:
  • service (str) – The service to use for translation.

  • text (str or Iterable[str]) – The text to translate.

  • ~*~*kwargs – The keyword arguments to pass to the translation function.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of TextResult objects if the response type is ‘raw’ and input was an iterable, a TextResult object otherwise. A list of GenerateContentResponse objects if the response type is ‘raw’ and input was an iterable, a GenerateContentResponse object otherwise. A list of ChatCompletion objects if the response type is ‘raw’ and input was an iterable, a ChatCompletion object otherwise. A list of any objects if the response type is ‘raw’ and input was an iterable, an any object otherwise. A list of AnthropicMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

Return type:

str or List[str] or TextResult or List[TextResult] or GenerateContentResponse or List[GenerateContentResponse] or ChatCompletion or List[ChatCompletion] or Any or List[Any] or AnthropicMessage or List[AnthropicMessage] or AnthropicToolsBetaMessage or List[AnthropicToolsBetaMessage]

async static translate_async(text: str | Iterable[str], service: Literal['deepl', 'openai', 'gemini', 'google translate', 'anthropic', 'azure'] | None = 'deepl', **kwargs) List[str] | str | List[TextResult] | TextResult | List[ChatCompletion] | ChatCompletion | List[AsyncGenerateContentResponse] | AsyncGenerateContentResponse | List[Any] | Any | List[Message] | Message#

Asynchronous version of translate().

Translates the given text to the target language using the specified service. This function assumes that the API key has already been set. translate_async() will generally be faster for iterables. Order is preserved.

Please see the documentation for the specific translation function for the service you want to use.

All functions can return a list of strings or a string, depending on the input. The response type can be specified to return the raw response instead:

  • DeepL: TextResult

  • OpenAI: ChatCompletion

  • Gemini: AsyncGenerateContentResponse

  • Google Translate: any

  • Anthropic: AnthropicMessage or AnthropicToolsBetaMessage

  • Azure: str

Parameters:
  • service (str) – The service to use for translation.

  • text (str or Iterable[str]) – The text to translate.

  • kwargs – The keyword arguments to pass to the translation function.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of TextResult objects if the response type is ‘raw’ and input was an iterable, a TextResult object otherwise. A list of AsyncGenerateContentResponse objects if the response type is ‘raw’ and input was an iterable, an AsyncGenerateContentResponse object otherwise. A list of ChatCompletion objects if the response type is ‘raw’ and input was an iterable, a ChatCompletion object otherwise. A list of any objects if the response type is ‘raw’ and input was an iterable, an any object otherwise. A list of AnthropicMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

Return type:

Union[List[str], str, List[TextResult], TextResult, List[ChatCompletion], ChatCompletion, List[AsyncGenerateContentResponse], AsyncGenerateContentResponse, List[Any], Any, List[AnthropicMessage], AnthropicMessage, List[AnthropicToolsBetaMessage], AnthropicToolsBetaMessage]terable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

easytl.exceptions module#

exception easytl.exceptions.EasyTLException#

Bases: Exception

EasyTLException is the base exception class for all exceptions in the EasyTL package.

exception easytl.exceptions.InvalidAPIKeyException(model_name: str)#

Bases: EasyTLException

InvalidAPIKeyException is an exception that is raised when the API key is invalid.

Parameters: model_name (string) : The name of the model that the API key is invalid for.

exception easytl.exceptions.InvalidAPITypeException(message: str)#

Bases: EasyTLException

InvalidAPITypeException is an exception that is raised when the API type provided to the EasyTL class is invalid

Parameters: message (string) : The message to display when the exception is raised.

exception easytl.exceptions.InvalidEasyTLSettingsException(message: str)#

Bases: EasyTLException

InvalidEasyTLSettingsException is an exception that is raised when the settings provided to the EasyTL class are invalid

Parameters: message (string) : The message to display when the exception is raised.

exception easytl.exceptions.InvalidResponseFormatException(message: str)#

Bases: EasyTLException

InvalidResponseFormatException is an exception that is raised when the response format is invalid

Parameters: message (string) : The message to display when the exception is raised.

exception easytl.exceptions.InvalidTextInputException(message: str)#

Bases: EasyTLException

InvalidTextInputException is an exception that is raised when the text input is invalid

Parameters: message (string) : The message to display when the exception is raised.

exception easytl.exceptions.TooManyInputTokensException(message: str)#

Bases: EasyTLException

TooManyInputTokensException is an exception that is raised when the input text contains too many tokens to be accepted by the API

Parameters: message (string) : The message to display when the exception is raised.

easytl.version module#

Module contents#

easytl.AnthropicAPIConnectionError#

alias of APIConnectionError

easytl.AnthropicAPIError#

alias of APIError

easytl.AnthropicAPIResponseValidationError#

alias of APIResponseValidationError

easytl.AnthropicAPIStatusError#

alias of APIStatusError

easytl.AnthropicAPITimeoutError#

alias of APITimeoutError

easytl.AnthropicAuthenticationError#

alias of AuthenticationError

easytl.AnthropicBadRequestError#

alias of BadRequestError

easytl.AnthropicConflictError#

alias of ConflictError

exception easytl.AnthropicError#

Bases: Exception

easytl.AnthropicInternalServerError#

alias of InternalServerError

easytl.AnthropicMessage#

alias of Message

easytl.AnthropicNotFoundError#

alias of NotFoundError

easytl.AnthropicPermissionDeniedError#

alias of PermissionDeniedError

easytl.AnthropicRateLimitError#

alias of RateLimitError

easytl.AnthropicTextBlock#

alias of TextBlock

easytl.AnthropicToolUseBlock#

alias of ToolUseBlock

easytl.AnthropicToolsBetaMessage#

alias of ToolsBetaMessage

easytl.AnthropicUnprocessableEntityError#

alias of UnprocessableEntityError

class easytl.AsyncGenerateContentResponse(done: bool, iterator: None | Iterable[GenerateContentResponse] | AsyncIterable[GenerateContentResponse], result: GenerateContentResponse, chunks: Iterable[GenerateContentResponse] | None = None)#

Bases: BaseGenerateContentResponse

This is the async version of genai.GenerateContentResponse.

async classmethod from_aiterator(iterator: AsyncIterable[GenerateContentResponse])#
classmethod from_response(response: GenerateContentResponse)#
async resolve()#
class easytl.ChatCompletion(**data: Any)#

Bases: BaseModel

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

choices: List[Choice]#

A list of chat completion choices.

Can be more than one if n is greater than 1.

created: int#

The Unix timestamp (in seconds) of when the chat completion was created.

id: str#

A unique identifier for the chat completion.

model: str#

The model used for the chat completion.

model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}#

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_config: ClassVar[ConfigDict] = {'defer_build': True, 'extra': 'allow'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[dict[str, FieldInfo]] = {'choices': FieldInfo(annotation=List[Choice], required=True), 'created': FieldInfo(annotation=int, required=True), 'id': FieldInfo(annotation=str, required=True), 'model': FieldInfo(annotation=str, required=True), 'object': FieldInfo(annotation=Literal['chat.completion'], required=True), 'system_fingerprint': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'usage': FieldInfo(annotation=Union[CompletionUsage, NoneType], required=False, default=None)}#

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].

This replaces Model.__fields__ from Pydantic V1.

object: Literal['chat.completion']#

The object type, which is always chat.completion.

system_fingerprint: str | None#

This fingerprint represents the backend configuration that the model runs with.

Can be used in conjunction with the seed request parameter to understand when backend changes have been made that might impact determinism.

usage: CompletionUsage | None#

Usage statistics for the completion request.

easytl.DeepLAuthorizationException#

alias of AuthorizationException

easytl.DeepLConnectionException#

alias of ConnectionException

easytl.DeepLDocumentNotReadyException#

alias of DocumentNotReadyException

easytl.DeepLDocumentTranslationException#

alias of DocumentTranslationException

exception easytl.DeepLException(message: str, should_retry: bool = False, http_status_code: int | None = None)#

Bases: Exception

Base class for deepl module exceptions.

Parameters:
  • message – Message describing the error that occurred.

  • should_retry – True if the request would normally be retried following this error, otherwise false.

  • http_status_code – The HTTP status code in the response, if applicable, otherwise None.

easytl.DeepLGlossaryNotFoundException#

alias of GlossaryNotFoundException

easytl.DeepLQuotaExceededException#

alias of QuotaExceededException

easytl.DeepLTooManyRequestsException#

alias of TooManyRequestsException

class easytl.EasyTL#

Bases: object

EasyTL global client, used to interact with Translation APIs.

Use set_credentials() to set the credentials for the specified API type. (e.g. set_credentials("deepl", "your_api_key")() or set_credentials("google translate", "path/to/your/credentials.json")())

Use test_credentials() to test the validity of the credentials for the specified API type. (e.g. test_credentials("deepl")()) (Optional) Done automatically when translating.

Use translate() to translate text using the specified service with its appropriate kwargs. Or specify the service by calling the specific translation function. (e.g. openai_translate())

Use calculate_cost() to calculate the cost of translating text using the specified service. (Optional)

See the documentation for each function for more information.

static anthropic_translate(text: str | Iterable[str] | ModelTranslationMessage | Iterable[ModelTranslationMessage], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', response_schema: str | Mapping[str, Any] | None = None, translation_delay: float | None = None, translation_instructions: str | None = None, model: str = 'claude-3-haiku-20240307', temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, stop_sequences: List[str] | NotGiven = NOT_GIVEN, max_output_tokens: int | NotGiven = NOT_GIVEN) List[str] | str | Message | List[Message] | ToolsBetaMessage | List[ToolsBetaMessage]#

Translates the given text using Anthropic.

This function assumes that the API key has already been set.

Translation instructions default to translating the text to English. To change this, specify the instructions.

This function is not for use for real-time translation, nor for generating multiple translation candidates. Another function may be implemented for this given demand.

Due to how Anthropic’s API works, NOT_GIVEN is treated differently than None. If a parameter is set to NOT_GIVEN, it is not passed to the API.

Anthropic’s JSON response is quite unsophisticated and also in Beta, it costs a lot of extra tokens to return a json response. It’s also inconsistent. Be careful when using it.

Parameters:
  • text (Union[str, Iterable[str], ModelTranslationMessage, Iterable[ModelTranslationMessage]]) – The text to translate. It can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an Anthropic translation function.

  • decorator (Callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this is None, Anthropic will retry the request twice if it fails.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal["text", "raw", "json", "raw_json"] or None) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, an AnthropicMessage object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, an AnthropicMessage object, but with the content as a json-parseable string.

  • response_schema (str or Mapping[str, Any] or None) – The schema to use for the response. If None, no schema is used. This is only used if the response type is ‘json’ or ‘json_raw’. EasyTL only validates the schema to the extend that it is None or a valid json. It does not validate the contents of the json.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or SystemTranslationMessage or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘claude-3-haiku-20240307’, ‘claude-3-sonnet-20240229’ or ‘claude-3-opus-20240229’)

  • temperature (float or NotGiven) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float or NotGiven) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • top_k (int or NotGiven) – The top k tokens to consider. Generally, alter this or temperature or top_p, not all three.

  • stop_sequences (List[str] or NotGiven) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_output_tokens (int or NotGiven) – The maximum number of tokens to output.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of AnthropicMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

Return type:

Union[List[str], str, AnthropicMessage, List[AnthropicMessage], AnthropicToolsBetaMessage, List[AnthropicToolsBetaMessage]]

async static anthropic_translate_async(text: str | Iterable[str] | ModelTranslationMessage | Iterable[ModelTranslationMessage], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', response_schema: str | Mapping[str, Any] | None = None, semaphore: int | None = 5, translation_delay: float | None = None, translation_instructions: str | None = None, model: str = 'claude-3-haiku-20240307', temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, stop_sequences: List[str] | NotGiven = NOT_GIVEN, max_output_tokens: int | NotGiven = NOT_GIVEN) List[str] | str | Message | List[Message] | ToolsBetaMessage | List[ToolsBetaMessage]#

Asynchronous version of anthropic_translate().

Translates the given text using Anthropic.

This function assumes that the API key has already been set.

Translation instructions default to translating the text to English. To change this, specify the instructions.

This function is not for use for real-time translation, nor for generating multiple translation candidates. Another function may be implemented for this given demand.

Due to how Anthropic’s API works, NOT_GIVEN is treated differently than None. If a parameter is set to NOT_GIVEN, it is not passed to the API.

Anthropic’s JSON response is quite unsophisticated and also in Beta, it costs a lot of extra tokens to return a json response. It’s also inconsistent. Be careful when using it.

Parameters:
  • text (Union[str, Iterable[str], ModelTranslationMessage, Iterable[ModelTranslationMessage]]) – The text to translate. It can be a string, a ModelTranslationMessage, or an iterable of strings or ModelTranslationMessages.

  • override_previous_settings (bool, optional) – Whether to override the previous settings that were used during the last call to an Anthropic translation function.

  • decorator (Callable or None, optional) – The decorator to use when translating. Typically for exponential backoff retrying. If this is None, Anthropic will retry the request twice if it fails.

  • logging_directory (str or None, optional) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal["text", "raw", "json", "raw_json"] or None, optional) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, an AnthropicMessage object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, an AnthropicMessage object, but with the content as a json-parseable string.

  • response_schema (str or Mapping[str, Any] or None, optional) – The schema to use for the response. If None, no schema is used. This is only used if the response type is ‘json’ or ‘json_raw’. EasyTL only validates the schema to the extend that it is None or a valid json. It does not validate the contents of the json.

  • semaphore (int or None, optional) – The number of concurrent requests to make. Default is 5.

  • translation_delay (float or None, optional) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or SystemTranslationMessage or None, optional) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str, optional) – The model to use. (E.g. ‘claude-3-haiku-20240307’, ‘claude-3-sonnet-20240229’ or ‘claude-3-opus-20240229’)

  • temperature (float or NotGiven, optional) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float or NotGiven, optional) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • top_k (int or NotGiven, optional) – The top k tokens to consider. Generally, alter this or temperature or top_p, not all three.

  • stop_sequences (List[str] or NotGiven, optional) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_output_tokens (int or NotGiven, optional) – The maximum number of tokens to output.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of AnthropicMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

Return type:

Union[List[str], str, AnthropicMessage, List[AnthropicMessage], AnthropicToolsBetaMessage, List[AnthropicToolsBetaMessage]]

static azure_translate(text: str | Iterable[str], target_lang: str = 'en', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'json'] | None = 'text', translation_delay: float | None = None, api_version: str = '3.0', azure_region: str = 'global', azure_endpoint: str = 'https://api.cognitive.microsofttranslator.com/', source_lang: str | None = None) List[str] | str#

Translates the given text to the target language using Azure.

This function assumes that the API key has already been set.

It is unknown whether Azure Translate has backoff retrying implemented. Assume it does not exist.

Default api_version, azure_region, and azure_endpoint values should be fine for most users.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable of strings.

  • target_lang (str) – The target language for translation. Default is ‘en’. These are ISO 639-1 language codes.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an Azure translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (literal["text", "json"]) – The type of response to return. ‘text’ returns the translated text, ‘json’ returns the original response in json format.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • api_version (str) – The version of the Azure Translator API. Default is ‘3.0’.

  • azure_region (str) – The Azure region to use for translation. Default is ‘global’.

  • azure_endpoint (str) – The Azure Translator API endpoint. Default is ‘https://api.cognitive.microsofttranslator.com/’.

  • source_lang (str or None) – The source language of the text. If None, the service will attempt to detect the language.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise.

Return type:

str or list[str]

async static azure_translate_async(text: str | Iterable[str], target_lang: str = 'en', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'json'] | None = 'text', semaphore: int | None = 15, translation_delay: float | None = None, api_version: str = '3.0', azure_region: str = 'global', azure_endpoint: str = 'https://api.cognitive.microsofttranslator.com/', source_lang: str | None = None) List[str] | str#

Asynchronous version of azure_translate().

Translates the given text to the target language using Azure.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable of strings.

  • target_lang (str) – The target language for translation. Default is ‘en’. These are ISO 639-1 language codes.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an Azure translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (literal["text", "json"]) – The type of response to return. ‘text’ returns the translated text, ‘json’ returns the original response in json format.

  • semaphore (int) – The number of concurrent requests to make. Default is 15.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • api_version (str) – The version of the Azure Translator API. Default is ‘3.0’.

  • azure_region (str) – The Azure region to use for translation. Default is ‘global’.

  • azure_endpoint (str) – The Azure Translator API endpoint. Default is ‘https://api.cognitive.microsofttranslator.com/’.

  • source_lang (str or None) – The source language of the text. If None, the service will attempt to detect the language.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise.

Return type:

str or list[str]

static calculate_cost(text: str | Iterable[str], service: Literal['deepl', 'openai', 'gemini', 'google translate', 'anthropic', 'azure'] | None = 'deepl', model: str | None = None, translation_instructions: str | None = None) Tuple[int, float, str]#

Calculates the cost of translating the given text using the specified service.

For LLMs, the cost is based on the default model unless specified.

Model and Translation Instructions are ignored for DeepL, Google Translate, and Azure.

For DeepL, Azure, and Google Translate, the number of tokens is the number of characters in the text. The returned model is the name of the service.

Note that Anthropic’s cost estimate is pretty sketchy and can be inaccurate. Refer to the actual response object for the cost or the API panel. This is because their tokenizer is not public, and we’re forced to estimate.

Parameters:
  • text (str or iterable) – The text to translate.

  • service (str) – The service to use for translation.

  • model (str or None) – The model to use for translation. If None, the default model is used.

  • translation_instructions (str or None) – The translation instructions to use.

Returns:

The number of tokens/characters in the text, the cost of translating the text, and the model used for translation.

Return type:

tuple[int, float, str]

static deepl_translate(text: str | Iterable[str], target_lang: str | Language = 'EN-US', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw'] | None = 'text', translation_delay: float | None = None, source_lang: str | Language | None = None, context: str | None = None, split_sentences: Literal['OFF', 'ALL', 'NO_NEWLINES'] | SplitSentences | None = 'ALL', preserve_formatting: bool | None = None, formality: Literal['default', 'more', 'less', 'prefer_more', 'prefer_less'] | Formality | None = None, glossary: str | GlossaryInfo | None = None, tag_handling: Literal['xml', 'html'] | None = None, outline_detection: bool | None = None, non_splitting_tags: str | List[str] | None = None, splitting_tags: str | List[str] | None = None, ignore_tags: str | List[str] | None = None) List[str] | str | List[TextResult] | TextResult#

Translates the given text to the target language using DeepL.

This function assumes that the API key has already been set.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable.

  • target_lang (str or Language) – The target language to translate to.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a DeepL translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this parameter is None, DeepL will retry your request 5 times before failing. Otherwise, the given decorator will be used.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (literal["text", "raw"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a TextResult object.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • source_lang (str or Language or None) – The source language to translate from.

  • context (str or None) – Additional information for the translator to be considered when translating. Not translated itself. This is a DeepL alpha feature and may be removed at any time.

  • split_sentences (literal or SplitSentences or None) – How to split sentences.

  • preserve_formatting (bool or None) – Whether to preserve formatting.

  • formality (literal or Formality or None) – The formality level to use.

  • glossary (str or GlossaryInfo or None) – The glossary to use.

  • tag_handling (literal or None) – How to handle tags.

  • outline_detection (bool or None) – Whether to detect outlines.

  • non_splitting_tags (str or list or None) – Tags that should not be split.

  • splitting_tags (str or list or None) – Tags that should be split.

  • ignore_tags (str or list or None) – Tags that should be ignored.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of TextResult objects if the response type is ‘raw’ and input was an iterable, a TextResult object otherwise.

Return type:

str or list - str or TextResult or list - TextResult

async static deepl_translate_async(text: str | Iterable[str], target_lang: str | Language = 'EN-US', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw'] | None = 'text', semaphore: int | None = 15, translation_delay: float | None = None, source_lang: str | Language | None = None, context: str | None = None, split_sentences: Literal['OFF', 'ALL', 'NO_NEWLINES'] | SplitSentences | None = 'ALL', preserve_formatting: bool | None = None, formality: Literal['default', 'more', 'less', 'prefer_more', 'prefer_less'] | Formality | None = None, glossary: str | GlossaryInfo | None = None, tag_handling: Literal['xml', 'html'] | None = None, outline_detection: bool | None = None, non_splitting_tags: str | List[str] | None = None, splitting_tags: str | List[str] | None = None, ignore_tags: str | List[str] | None = None) List[str] | str | List[TextResult] | TextResult#

Asynchronous version of deepl_translate().

Translates the given text to the target language using DeepL.

Will generally be faster for iterables. Order is preserved.

This function assumes that the API key has already been set.

Parameters:
  • text (Union[str, Iterable[str]]) – The text to translate. It can be a string or an iterable of strings.

  • target_lang (Union[str, Language]) – The target language to translate to.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a DeepL translation function.

  • decorator (Callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this parameter is None, DeepL will retry your request 5 times before failing. Otherwise, the given decorator will be used.

  • logging_directory (Union[str, None]) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal['text', 'raw']) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a TextResult object.

  • semaphore (int) – The number of concurrent requests to make. Default is 15.

  • translation_delay (Union[float, None]) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • source_lang (Union[str, Language, None]) – The source language to translate from.

  • context (Union[str, None]) – Additional information for the translator to be considered when translating. Not translated itself. This is a DeepL alpha feature and may be removed at any time.

  • split_sentences (Literal['OFF', 'ALL', 'NO_NEWLINES', SplitSentences, None]) – How to split sentences.

  • preserve_formatting (Union[bool, None]) – Whether to preserve formatting.

  • formality (Literal['default', 'more', 'less', 'prefer_more', 'prefer_less', Formality, None]) – The formality level to use.

  • glossary (Union[str, GlossaryInfo, None]) – The glossary to use.

  • tag_handling (Union[Literal['xml', 'html'], None]) – How to handle tags.

  • outline_detection (Union[bool, None]) – Whether to detect outlines.

  • non_splitting_tags (Union[str, List[str], None]) – Tags that should not be split.

  • splitting_tags (Union[str, List[str], None]) – Tags that should be split.

  • ignore_tags (Union[str, List[str], None]) – Tags that should be ignored.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of TextResult objects if the response type is ‘raw’ and input was an iterable, a TextResult object otherwise.

Return type:

Union[List[str], str, List[TextResult], TextResult]

static gemini_translate(text: str | Iterable[str], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', response_schema: str | Mapping[str, Any] | None = None, translation_delay: float | None = None, translation_instructions: str | None = None, model: str = 'gemini-pro', temperature: float = 0.5, top_p: float = 0.9, top_k: int = 40, stop_sequences: List[str] | None = None, max_output_tokens: int | None = None) List[str] | str | GenerateContentResponse | List[GenerateContentResponse]#

Translates the given text using Gemini.

This function assumes that the API key has already been set.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a Gemini translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (str, literal["text", "raw", "json", "raw_json"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a GenerateContentResponse object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, a GenerateContentResponse object, but with the content as a json-parseable string.

  • response_schema (str or mapping or None) – The schema to use for the response. If None, no schema is used. This is only used if the response type is ‘json’ or ‘json_raw’. EasyTL only validates the schema to the extend that it is None or a valid json. It does not validate the contents of the json.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘gemini-pro’ or ‘gemini-pro-1.5-latest’)

  • temperature (float) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • top_k (int) – The top k tokens to consider. Generally, alter this or temperature or top_p, not all three.

  • stop_sequences (list or None) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_output_tokens (int or None) – The maximum number of tokens to output.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of GenerateContentResponse objects if the response type is ‘raw’ and input was an iterable, a GenerateContentResponse object otherwise.

Return type:

str or list[str] or GenerateContentResponse or list[GenerateContentResponse]

async static gemini_translate_async(text: str | Iterable[str], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', response_schema: str | Mapping[str, Any] | None = None, semaphore: int | None = 5, translation_delay: float | None = None, translation_instructions: str | None = None, model: str = 'gemini-pro', temperature: float = 0.5, top_p: float = 0.9, top_k: int = 40, stop_sequences: List[str] | None = None, max_output_tokens: int | None = None) List[str] | str | AsyncGenerateContentResponse | List[AsyncGenerateContentResponse]#

Asynchronous version of gemini_translate().

Translates the given text using Gemini.

This function assumes that the API key has already been set.

Translation instructions default to translating the text to English. To change this, specify the instructions.

This function is not for use for real-time translation, nor for generating multiple translation candidates. Another function may be implemented for this given demand.

It is not known whether Gemini has backoff retrying implemented. Assume it does not exist.

Parameters:
  • text (str or iterable) – The text to translate. Can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a Gemini translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (str) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, an AsyncGenerateContentResponse object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, an AsyncGenerateContentResponse object, but with the content as a json-parseable string.

  • response_schema (str or mapping or None) – The schema to use for the response. If None, no schema is used. This is only used if the response type is ‘json’ or ‘json_raw’. EasyTL only validates the schema to the extend that it is None or a valid json. It does not validate the contents of the json.

  • semaphore (int) – The number of concurrent requests to make. Default is 5 for 1.0 and 2 for 1.5 gemini models. For Gemini, it is recommend to use translation_delay along with the semaphore to prevent rate limiting.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘gemini-pro’ or ‘gemini-pro-1.5-latest’)

  • temperature (float) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • top_k (int) – The top k tokens to consider. Generally, alter this or temperature or top_p, not all three.

  • stop_sequences (list or None) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_output_tokens (int or None) – The maximum number of tokens to output.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of AsyncGenerateContentResponse objects if the response type is ‘raw’ and input was an iterable, a AsyncGenerateContentResponse object otherwise.

Return type:

str or list or AsyncGenerateContentResponse

static googletl_translate(text: str | Iterable[str], target_lang: str = 'en', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw'] | None = 'text', translation_delay: float | None = None, format: Literal['text', 'html'] = 'text', source_lang: str | None = None) List[str] | str | List[Any] | Any#

Translates the given text to the target language using Google Translate.

This function assumes that the credentials have already been set.

It is unknown whether Google Translate has backoff retrying implemented. Assume it does not exist.

Google Translate v2 API is poorly documented and type hints are near non-existent. typing.Any return types are used for the raw response type.

Parameters:
  • text (Union[str, Iterable[str]]) – The text to translate. It can be a string or an iterable.

  • target_lang (str) – The target language to translate to.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a Google Translate function.

  • decorator (Callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal["text", "raw"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • format (Literal["text", "html"]) – The format of the text. Can be ‘text’ or ‘html’. Default is ‘text’. Google Translate appears to be able to translate html but this has not been tested thoroughly by EasyTL.

  • source_lang (str or None) – The source language to translate from.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of any objects if the response type is ‘raw’ and input was an iterable, an any object otherwise.

Return type:

Union[str, List[str], Any, List[Any]]

async static googletl_translate_async(text: str | Iterable[str], target_lang: str = 'en', override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw'] | None = 'text', semaphore: int | None = 15, translation_delay: float | None = None, format: Literal['text', 'html'] = 'text', source_lang: str | None = None) List[str] | str | List[Any] | Any#

Asynchronous version of googletl_translate().

Translates the given text to the target language using Google Translate. Will generally be faster for iterables. Order is preserved.

This function assumes that the credentials have already been set.

It is unknown whether Google Translate has backoff retrying implemented. Assume it does not exist.

Google Translate v2 API is poorly documented and type hints are near non-existent. typing.Any return types are used for the raw response type.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable.

  • target_lang (str) – The target language to translate to.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to a Google Translate function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (literal["text", "raw"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response.

  • semaphore (int) – The number of concurrent requests to make. Default is 15.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • format (str or None) – The format of the text. Can be ‘text’ or ‘html’. Default is ‘text’. Google Translate appears to be able to translate html but this has not been tested thoroughly by EasyTL.

  • source_lang (str or None) – The source language to translate from.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of any objects if the response type is ‘raw’ and input was an iterable, an any object otherwise.

Return type:

str or list[str] or any or list[any]

static openai_translate(text: str | Iterable[str] | ModelTranslationMessage | Iterable[ModelTranslationMessage], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', translation_delay: float | None = None, translation_instructions: str | SystemTranslationMessage | None = None, model: str = 'gpt-4', temperature: float | None | NotGiven = NOT_GIVEN, top_p: float | None | NotGiven = NOT_GIVEN, stop: List[str] | None | NotGiven = NOT_GIVEN, max_tokens: int | None | NotGiven = NOT_GIVEN, presence_penalty: float | None | NotGiven = NOT_GIVEN, frequency_penalty: float | None | NotGiven = NOT_GIVEN) List[str] | str | List[ChatCompletion] | ChatCompletion#

Translates the given text using OpenAI.

This function assumes that the API key has already been set.

Translation instructions default to translating the text to English. To change this, specify the instructions.

Due to how OpenAI’s API works, NOT_GIVEN is treated differently than None. If a parameter is set to NOT_GIVEN, it is not passed to the API. If it is set to None, it is passed to the API as None.

This function is not for use for real-time translation, nor for generating multiple translation candidates. Another function may be implemented for this given demand.

Parameters:
  • text (str or iterable) – The text to translate. It can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an OpenAI translation function.

  • decorator (callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this is None, OpenAI will retry the request twice if it fails.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (str, literal["text", "raw", "json", "raw_json"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a ChatCompletion object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, a ChatCompletion object, but with the content as a json-parseable string.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or SystemTranslationMessage or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘gpt-4’, ‘gpt-3.5-turbo-0125’, ‘gpt-4o’, etc.)

  • temperature (float) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • stop (list or None) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_tokens (int or None) – The maximum number of tokens to output.

  • presence_penalty (float) – The presence penalty to use. This penalizes the model from repeating the same content in the output. Shouldn’t be messed with for translation.

  • frequency_penalty (float) – The frequency penalty to use. This penalizes the model from using the same words too frequently in the output. Shouldn’t be messed with for translation.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of ChatCompletion objects if the response type is ‘raw’ and input was an iterable, a ChatCompletion object otherwise.

Return type:

str or list[str] or ChatCompletion or list[ChatCompletion]

async static openai_translate_async(text: str | Iterable[str] | ModelTranslationMessage | Iterable[ModelTranslationMessage], override_previous_settings: bool = True, decorator: Callable | None = None, logging_directory: str | None = None, response_type: Literal['text', 'raw', 'json', 'raw_json'] | None = 'text', semaphore: int | None = 5, translation_delay: float | None = None, translation_instructions: str | SystemTranslationMessage | None = None, model: str = 'gpt-4', temperature: float | None | NotGiven = NOT_GIVEN, top_p: float | None | NotGiven = NOT_GIVEN, stop: List[str] | None | NotGiven = NOT_GIVEN, max_tokens: int | None | NotGiven = NOT_GIVEN, presence_penalty: float | None | NotGiven = NOT_GIVEN, frequency_penalty: float | None | NotGiven = NOT_GIVEN) List[str] | str | List[ChatCompletion] | ChatCompletion#

Asynchronous version of openai_translate().

Translates the given text using OpenAI.

Parameters:
  • text (Union[str, Iterable[str]]) – The text to translate. It can be a string or an iterable of strings.

  • override_previous_settings (bool) – Whether to override the previous settings that were used during the last call to an OpenAI translation function.

  • decorator (Callable or None) – The decorator to use when translating. Typically for exponential backoff retrying. If this is None, OpenAI will retry the request twice if it fails.

  • logging_directory (str or None) – The directory to log to. If None, no logging is done. This’ll append the text result and some function information to a file in the specified directory. File is created if it doesn’t exist.

  • response_type (Literal["text", "raw", "json", "raw_json"]) – The type of response to return. ‘text’ returns the translated text, ‘raw’ returns the raw response, a ChatCompletion object, ‘json’ returns a json-parseable string. ‘raw_json’ returns the raw response, a ChatCompletion object, but with the content as a json-parseable string.

  • semaphore (int) – The number of concurrent requests to make. Default is 5.

  • translation_delay (float or None) – If text is an iterable, the delay between each translation. Default is none. This is more important for asynchronous translations where a semaphore alone may not be sufficient.

  • translation_instructions (str or SystemTranslationMessage or None) – The translation instructions to use. If None, the default system message is used. If you plan on using the json response type, you must specify that you want a json output and it’s format in the instructions. The default system message will ask for a generic json if the response type is json.

  • model (str) – The model to use. (E.g. ‘gpt-4’, ‘gpt-3.5-turbo-0125’, ‘gpt-4o’, etc.)

  • temperature (float) – The temperature to use. The higher the temperature, the more creative the output. Lower temperatures are typically better for translation.

  • top_p (float) – The nucleus sampling probability. The higher the value, the more words are considered for the next token. Generally, alter this or temperature, not both.

  • stop (List[str] or None) – String sequences that will cause the model to stop translating if encountered, generally useless.

  • max_tokens (int or None) – The maximum number of tokens to output.

  • presence_penalty (float) – The presence penalty to use. This penalizes the model from repeating the same content in the output. Shouldn’t be messed with for translation.

  • frequency_penalty (float) – The frequency penalty to use. This penalizes the model from using the same words too frequently in the output. Shouldn’t be messed with for translation.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of ChatCompletion objects if the response type is ‘raw’ and input was an iterable, a ChatCompletion object otherwise.

Return type:

Union[List[str], str, List[ChatCompletion], ChatCompletion]

static set_credentials(api_type: Literal['deepl', 'gemini', 'openai', 'google translate', 'anthropic', 'azure'], credentials: str) None#

Sets the credentials for the specified API type.

Parameters:
  • api_type (literal["deepl", "gemini", "openai", "google translate", "anthropic", "azure"]) – The API type to set the credentials for. Supported types are ‘deepl’, ‘gemini’, ‘openai’, ‘google translate’, ‘anthropic’, and ‘azure’.

  • credentials (str) – The credentials to set. This is an API key for deepl, gemini, anthropic, azure, and openai. For google translate, this is a path to your JSON that has your service account key.

static test_credentials(api_type: Literal['deepl', 'gemini', 'openai', 'google translate', 'anthropic', 'azure']) Tuple[bool, Exception | None]#

Tests the validity of the credentials for the specified API type.

Parameters:

api_type (str) – The API type to test the credentials for. (literal[“deepl”, “gemini”, “openai”, “google translate”, “anthropic”, “azure”])

Returns:

Whether the credentials are valid. (bool)

Return type:

bool

Returns:

The exception that was raised, if any. None otherwise. (Exception)

Return type:

Exception

static translate(text: str | Iterable[str], service: Literal['deepl', 'openai', 'gemini', 'google translate', 'anthropic', 'azure'] | None = 'deepl', **kwargs) List[str] | str | List[TextResult] | TextResult | List[ChatCompletion] | ChatCompletion | List[GenerateContentResponse] | GenerateContentResponse | List[Any] | Any | List[Message] | Message#

Translates the given text to the target language using the specified service.

Please see the documentation for the specific translation function for the service you want to use.

DeepL: deepl_translate() OpenAI: openai_translate() Gemini: gemini_translate() Google Translate: googletl_translate() Anthropic: anthropic_translate() Azure: azure_translate()

All functions can return a list of strings or a string, depending on the input. The response type can be specified to return the raw response instead: DeepL: TextResult OpenAI: ChatCompletion Gemini: GenerateContentResponse Google Translate: any Anthropic: AnthropicMessage or AnthropicToolsBetaMessage Azure: str

Parameters:
  • service (str) – The service to use for translation.

  • text (str or Iterable[str]) – The text to translate.

  • ~*~*kwargs – The keyword arguments to pass to the translation function.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of TextResult objects if the response type is ‘raw’ and input was an iterable, a TextResult object otherwise. A list of GenerateContentResponse objects if the response type is ‘raw’ and input was an iterable, a GenerateContentResponse object otherwise. A list of ChatCompletion objects if the response type is ‘raw’ and input was an iterable, a ChatCompletion object otherwise. A list of any objects if the response type is ‘raw’ and input was an iterable, an any object otherwise. A list of AnthropicMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

Return type:

str or List[str] or TextResult or List[TextResult] or GenerateContentResponse or List[GenerateContentResponse] or ChatCompletion or List[ChatCompletion] or Any or List[Any] or AnthropicMessage or List[AnthropicMessage] or AnthropicToolsBetaMessage or List[AnthropicToolsBetaMessage]

async static translate_async(text: str | Iterable[str], service: Literal['deepl', 'openai', 'gemini', 'google translate', 'anthropic', 'azure'] | None = 'deepl', **kwargs) List[str] | str | List[TextResult] | TextResult | List[ChatCompletion] | ChatCompletion | List[AsyncGenerateContentResponse] | AsyncGenerateContentResponse | List[Any] | Any | List[Message] | Message#

Asynchronous version of translate().

Translates the given text to the target language using the specified service. This function assumes that the API key has already been set. translate_async() will generally be faster for iterables. Order is preserved.

Please see the documentation for the specific translation function for the service you want to use.

All functions can return a list of strings or a string, depending on the input. The response type can be specified to return the raw response instead:

Parameters:
  • service (str) – The service to use for translation.

  • text (str or Iterable[str]) – The text to translate.

  • kwargs – The keyword arguments to pass to the translation function.

Returns:

The translation result. A list of strings if the input was an iterable, a string otherwise. A list of TextResult objects if the response type is ‘raw’ and input was an iterable, a TextResult object otherwise. A list of AsyncGenerateContentResponse objects if the response type is ‘raw’ and input was an iterable, an AsyncGenerateContentResponse object otherwise. A list of ChatCompletion objects if the response type is ‘raw’ and input was an iterable, a ChatCompletion object otherwise. A list of any objects if the response type is ‘raw’ and input was an iterable, an any object otherwise. A list of AnthropicMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

Return type:

Union[List[str], str, List[TextResult], TextResult, List[ChatCompletion], ChatCompletion, List[AsyncGenerateContentResponse], AsyncGenerateContentResponse, List[Any], Any, List[AnthropicMessage], AnthropicMessage, List[AnthropicToolsBetaMessage], AnthropicToolsBetaMessage]terable, an AnthropicMessage object otherwise. A list of AnthropicToolsBetaMessage objects if the response type is ‘raw’ and input was an iterable, an AnthropicToolsBetaMessage object otherwise.

class easytl.Formality(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

Options for formality parameter.

DEFAULT = 'default'#

Translate using the default formality.

LESS = 'less'#

Translate using informal language.

MORE = 'more'#

Translate using formal language.

PREFER_LESS = 'prefer_less'#

Translate using informal language if the target language supports formality, otherwise use default formality.

PREFER_MORE = 'prefer_more'#

Translate using formal language if the target language supports formality, otherwise use default formality.

class easytl.GenerateContentResponse(done: bool, iterator: None | Iterable[GenerateContentResponse] | AsyncIterable[GenerateContentResponse], result: GenerateContentResponse, chunks: Iterable[GenerateContentResponse] | None = None)#

Bases: BaseGenerateContentResponse

Instances of this class manage the response of the generate_content method.

These are returned by GenerativeModel.generate_content and ChatSession.send_message. This object is based on the low level glm.GenerateContentResponse class which just has prompt_feedback and candidates attributes. This class adds several quick accessors for common use cases.

The same object type is returned for both stream=True/False.

### Streaming

When you pass stream=True to GenerativeModel.generate_content or ChatSession.send_message, iterate over this object to receive chunks of the response:

``` response = model.generate_content(…, stream=True): for chunk in response:

print(chunk.text)

```

GenerateContentResponse.prompt_feedback is available immediately but GenerateContentResponse.candidates, and all the attributes derived from them (.text, .parts), are only available after the iteration is complete.

classmethod from_iterator(iterator: Iterable[GenerateContentResponse])#
classmethod from_response(response: GenerateContentResponse)#
resolve()#
class easytl.GenerationConfig(candidate_count: int | None = None, stop_sequences: Iterable[str] | None = None, max_output_tokens: int | None = None, temperature: float | None = None, top_p: float | None = None, top_k: int | None = None, response_mime_type: str | None = None, response_schema: Schema | Mapping[str, Any] | None = None)#

Bases: object

A simple dataclass used to configure the generation parameters of GenerativeModel.generate_content.

Attributes:
candidate_count:

Number of generated responses to return.

stop_sequences:

The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop at the first appearance of a stop sequence. The stop sequence will not be included as part of the response.

max_output_tokens:

The maximum number of tokens to include in a candidate.

If unset, this will default to output_token_limit specified in the model’s specification.

temperature:

Controls the randomness of the output. Note: The default value varies by model, see the Model.temperature attribute of the Model returned the genai.get_model function.

Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will produce responses that are more varied and creative, while a value closer to 0.0 will typically result in more straightforward responses from the model.

top_p:

Optional. The maximum cumulative probability of tokens to consider when sampling.

The model uses combined Top-k and nucleus sampling.

Tokens are sorted based on their assigned probabilities so that only the most likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while Nucleus sampling limits number of tokens based on the cumulative probability.

Note: The default value varies by model, see the Model.top_p attribute of the Model returned the genai.get_model function.

top_k (int):

Optional. The maximum number of tokens to consider when sampling.

The model uses combined Top-k and nucleus sampling.

Top-k sampling considers the set of top_k most probable tokens. Defaults to 40.

Note: The default value varies by model, see the Model.top_k attribute of the Model returned the genai.get_model function.

response_mime_type:

Optional. Output response mimetype of the generated candidate text.

Supported mimetype:

text/plain: (default) Text output. application/json: JSON response in the candidates.

response_schema:

Optional. Specifies the format of the JSON requested if response_mime_type is application/json.

candidate_count: int | None = None#
max_output_tokens: int | None = None#
response_mime_type: str | None = None#
response_schema: Schema | Mapping[str, Any] | None = None#
stop_sequences: Iterable[str] | None = None#
temperature: float | None = None#
top_k: int | None = None#
top_p: float | None = None#
class easytl.GlossaryInfo(glossary_id: str, name: str, ready: bool, source_lang: str, target_lang: str, creation_time: datetime, entry_count: int)#

Bases: object

Information about a glossary, excluding the entry list.

Parameters:
  • glossary_id – Unique ID assigned to the glossary.

  • name – User-defined name assigned to the glossary.

  • ready – True iff the glossary may be used for translations.

  • source_lang – Source language code of the glossary.

  • target_lang – Target language code of the glossary.

  • creation_time – Timestamp when the glossary was created.

  • entry_count – The number of entries contained in the glossary.

property creation_time: datetime#
property entry_count: int#
static from_json(json) GlossaryInfo#

Create GlossaryInfo from the given API JSON object.

property glossary_id: str#
property name: str#
property ready: bool#
property source_lang: str#
property target_lang: str#
exception easytl.GoogleAPIError#

Bases: Exception

Base class for all exceptions raised by Google API Clients.

exception easytl.GoogleAuthError(*args, **kwargs)#

Bases: Exception

Base class for all google.auth errors.

property retryable#
easytl.GoogleDefaultCredentialsError#

alias of DefaultCredentialsError

class easytl.Language(code: str, name: str, supports_formality: bool | None = None)#

Bases: object

Information about a language supported by DeepL translator.

Parameters:
  • code – Language code according to ISO 639-1, for example “EN”. Some target languages also include the regional variant according to ISO 3166-1, for example “EN-US”.

  • name – Name of the language in English.

  • supports_formality – (Optional) Specifies whether the formality option is available for this language; target languages only.

BULGARIAN = 'bg'#
CHINESE = 'zh'#
CZECH = 'cs'#
DANISH = 'da'#
DUTCH = 'nl'#
ENGLISH = 'en'#
ENGLISH_AMERICAN = 'en-US'#
ENGLISH_BRITISH = 'en-GB'#
ESTONIAN = 'et'#
FINNISH = 'fi'#
FRENCH = 'fr'#
GERMAN = 'de'#
GREEK = 'el'#
HUNGARIAN = 'hu'#
INDONESIAN = 'id'#
ITALIAN = 'it'#
JAPANESE = 'ja'#
KOREAN = 'ko'#
LATVIAN = 'lv'#
LITHUANIAN = 'lt'#
NORWEGIAN = 'nb'#
POLISH = 'pl'#
PORTUGUESE = 'pt'#
PORTUGUESE_BRAZILIAN = 'pt-BR'#
PORTUGUESE_EUROPEAN = 'pt-PT'#
ROMANIAN = 'ro'#
RUSSIAN = 'ru'#
SLOVAK = 'sk'#
SLOVENIAN = 'sl'#
SPANISH = 'es'#
SWEDISH = 'sv'#
TURKISH = 'tr'#
UKRAINIAN = 'uk'#
static remove_regional_variant(language: str | Language) str#

Removes the regional variant from a language, e.g. EN-US gives EN

class easytl.Message(content: str)#

Bases: object

Message is a class that is used to send translation batches to the OpenAI API.

property content#
property role#
to_dict()#
class easytl.ModelTranslationMessage(content: str)#

Bases: Message

ModelTranslationMessage is a class that is used to send the model/user message to the OpenAI API.

property role#
class easytl.NotGiven#

Bases: object

A sentinel singleton class used to distinguish omitted keyword arguments from those passed in with the value None (which may have different behavior).

Used until PEP 0661 is accepted

For example:

def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response:
    ...

get(timeout=1) # 1s timeout
get(timeout=None) # No timeout
get() # Default timeout behavior, which may not be statically known at the method definition.
easytl.OpenAIAPIConnectionError#

alias of APIConnectionError

easytl.OpenAIAPIError#

alias of APIError

easytl.OpenAIAPIResponseValidationError#

alias of APIResponseValidationError

easytl.OpenAIAPIStatusError#

alias of APIStatusError

easytl.OpenAIAPITimeoutError#

alias of APITimeoutError

easytl.OpenAIAuthenticationError#

alias of AuthenticationError

easytl.OpenAIBadRequestError#

alias of BadRequestError

easytl.OpenAIConflictError#

alias of ConflictError

exception easytl.OpenAIError#

Bases: Exception

easytl.OpenAIInternalServerError#

alias of InternalServerError

easytl.OpenAINotFoundError#

alias of NotFoundError

easytl.OpenAIPermissionDeniedError#

alias of PermissionDeniedError

easytl.OpenAIRateLimitError#

alias of RateLimitError

easytl.OpenAIUnprocessableEntityError#

alias of UnprocessableEntityError

exception easytl.RequestException(*args, **kwargs)#

Bases: OSError

There was an ambiguous exception that occurred while handling your request.

Initialize RequestException with request and response objects.

class easytl.SplitSentences(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

Options for split_sentences parameter.

Sets whether the translation engine should first split the input into sentences. This is enabled by default. Possible values are: - OFF: no splitting at all, whole input is treated as one sentence. Use

this option if the input text is already split into sentences, to prevent the engine from splitting the sentence unintentionally.

  • ALL: (default) splits on punctuation and on newlines.

  • NO_NEWLINES: splits on punctuation only, ignoring newlines.

ALL = '1'#
DEFAULT = '1'#
NO_NEWLINES = 'nonewlines'#
OFF = '0'#
class easytl.SystemTranslationMessage(content: str)#

Bases: Message

SystemTranslationMessage is a class that is used to send the system message to the OpenAI API.

property role#
class easytl.TextResult(text: str, detected_source_lang: str)#

Bases: object

Holds the result of a text translation request.