diff --git a/libs/community/langchain_community/tools/azure_ai_services/text_translate.py b/libs/community/langchain_community/tools/azure_ai_services/text_translate.py new file mode 100644 index 0000000000000..ae6211ba55b4a --- /dev/null +++ b/libs/community/langchain_community/tools/azure_ai_services/text_translate.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +logger = logging.getLogger(__name__) + + +class AzureAITextTranslateTool(BaseTool): + """ + A tool that interacts with the Azure Translator API using the SDK. + + Attributes: + text_translation_key (str): + The API key for the Azure Translator service. + text_translation_endpoint (str): + The endpoint for the Azure Translator service. + region (str): The Azure region where the Translator service is hosted. + translate_client (TextTranslationClient): + The Azure Translator client initialized with the credentials. + default_language (str): + The default language for translation (default is 'en'). + + This tool queries the Azure Translator API to translate text between languages. + Input must be text (str), and the 'to_language' + parameter must be a two-letter language code (e.g., 'es', 'it', 'de'). + """ + + text_translation_key: Optional[str] = None + text_translation_endpoint: Optional[str] = None + region: Optional[str] = None + + translate_client: Any = None + default_language: str = "en" + + name: str = "azure_translator_tool" + description: str = ( + "A wrapper around Azure Translator API. Useful for translating text between " + "languages. Input must be text (str), and the 'to_language'" + " parameter must be a two-letter language code (str), e.g., 'es', 'it', 'de'." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """ + Validate that the required environment variables are set, and set up + the client. + """ + + try: + from azure.ai.translation.text import TextTranslationClient + from azure.core.credentials import AzureKeyCredential + except ImportError: + raise ImportError( + "Azure Translator API packages are not installed. " + "Please install 'azure-ai-translation-text' and 'azure-core'." + ) + + text_translation_key = get_from_dict_or_env( + values, "text_translation_key", "AZURE_TRANSLATE_API_KEY" + ) + text_translation_endpoint = get_from_dict_or_env( + values, "text_translation_endpoint", "AZURE_TRANSLATE_ENDPOINT" + ) + region = get_from_dict_or_env(values, "region", "REGION") + + values["translate_client"] = TextTranslationClient( + endpoint=text_translation_endpoint, + credential=AzureKeyCredential(text_translation_key), + region=region, + ) + + return values + + def _translate_text(self, text: str, to_language: str = "en") -> str: + """ + Perform text translation using the Azure Translator API. + """ + if not text: + raise ValueError("Input text for translation is empty.") + + body = [{"Text": text}] + try: + response = self.translate_client.translate( + body=body, to_language=[to_language] + ) + return response[0].translations[0].text + except Exception as e: + logger.error("Translation failed: %s", e) + raise RuntimeError(f"Translation failed: {e}") + + from azure.ai.translation.text import TextTranslationClient + + self.translate_client: TextTranslationClient + + body = [{"Text": text}] + try: + response = self.translate_client.translate( + body=body, to_language=[to_language] + ) + return response[0].translations[0].text + except Exception: + raise + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + to_language: str = "en", + ) -> str: + """ + Run the tool to perform translation. + + Args: + query (str): The text to be translated. + run_manager (Optional[CallbackManagerForToolRun]): + A callback manager for tracking the tool run. + to_language (str): The target language for translation. + + Returns: + str: The translated text. + """ + # Ensure only the text (not the full query dictionary) + # is passed to the translation function + text_to_translate = query + return self._translate_text(text_to_translate, to_language) diff --git a/libs/community/pyproject.toml b/libs/community/pyproject.toml index 6406350abf2bd..769df661402be 100644 --- a/libs/community/pyproject.toml +++ b/libs/community/pyproject.toml @@ -165,4 +165,4 @@ develop = true [tool.poetry.group.typing.dependencies.langchain] path = "../langchain" -develop = true +develop = true \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index e63de41890dee..2d90d5eaa533b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -87,4 +87,4 @@ extend-exclude = [ # These files were failing the listed rules at the time ruff was adopted for notebooks. # Don't require them to change at once, though we should look into them eventually. "cookbook/gymnasium_agent_simulation.ipynb" = ["F821"] -"docs/docs/integrations/document_loaders/tensorflow_datasets.ipynb" = ["F821"] +"docs/docs/integrations/document_loaders/tensorflow_datasets.ipynb" = ["F821"] \ No newline at end of file diff --git a/test_azure_translate_tool.py b/test_azure_translate_tool.py new file mode 100644 index 0000000000000..3502e7e539950 --- /dev/null +++ b/test_azure_translate_tool.py @@ -0,0 +1,70 @@ +import unittest +from unittest.mock import patch, MagicMock +from libs.community.langchain_community.tools.azure_ai_services.text_translate import ( + AzureAITextTranslateTool, +) + + +class TestAzureTranslateTool(unittest.TestCase): + @patch( + "azure.ai.translation.text.TextTranslationClient" + ) # Mock the translation client + def setUp(self, mock_translation_client): + # Set up a mock translation client + self.mock_translation_client = mock_translation_client + self.mock_translation_instance = mock_translation_client.return_value + + # Create an instance of the AzureTranslateTool + self.tool = AzureAITextTranslateTool() + + # Mock environment variables + self.tool.text_translation_key = "fake_api_key" + self.tool.text_translation_endpoint = "https://fake.endpoint.com" + self.tool.region = "fake_region" + + def test_translate_success(self): + # Mock the translation API response + mock_response = MagicMock() + mock_response.translations = [MagicMock(text="Hola")] + self.mock_translation_instance.translate.return_value = [mock_response] + + # Call the translate function + result = self.tool._translate_text("Hello", to_language="es") + + # Assert the result is as expected + self.assertEqual(result, "Hola") + self.mock_translation_instance.translate.assert_called_once_with( + body=[{"Text": "Hello"}], to_language=["es"] + ) + + def test_empty_text(self): + # Test that an empty input raises a ValueError + with self.assertRaises(ValueError) as context: + self.tool._translate_text("", to_language="es") + + self.assertEqual(str(context.exception), "Input text for translation is empty.") + + def test_api_failure(self): + # Simulate an API failure + self.mock_translation_instance.translate.side_effect = Exception("API failure") + + # Test that an exception is raised and handled properly + with self.assertRaises(RuntimeError) as context: + self.tool._translate_text("Hello", to_language="es") + + self.assertIn("Translation failed", str(context.exception)) + + @patch("azure.ai.translation.text.TextTranslationClient") + def test_validate_environment(self, mock_translation_client): + # Test that the environment is validated and the client is initialized + self.tool.validate_environment() + + # Ensure the translation client is initialized properly + mock_translation_client.assert_called_once_with( + endpoint=self.tool.text_translation_endpoint, credential=unittest.mock.ANY + ) + + +# Run the unit tests +if __name__ == "__main__": + unittest.main() diff --git a/translate_test.ipynb b/translate_test.ipynb new file mode 100644 index 0000000000000..1a70f3e6139af --- /dev/null +++ b/translate_test.ipynb @@ -0,0 +1,775 @@ +{ + "cells": [ + { + "metadata": {}, + "cell_type": "markdown", + "source": [ + "\n", + "# # AzureTranslateTool with AgentExecutor\n", + "# " + ], + "id": "68856c663f10f863" + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "# This notebook demonstrates how to use the `AzureTranslateTool` in conjunction with an AgentExecutor. The agent will handle translation requests by utilizing the Azure OpenAI model and the `AzureTranslateTool`.", + "id": "23cc6f4912d58722" + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": [ + "\n", + "# ## Step 1: Import Required Libraries and Load Environment Variables\n", + "# We begin by importing the necessary libraries and loading the environment variables that include the Azure OpenAI and LangSmith API keys.\n" + ], + "id": "9fb605e9b94dc85d" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:15.693866Z", + "start_time": "2024-10-18T22:17:13.429824Z" + } + }, + "cell_type": "code", + "source": [ + "# Import necessary libraries\n", + "from libs.community.langchain_community.tools.azure_ai_services.text_translate import AzureAITextTranslateTool\n", + "from langchain_openai import AzureChatOpenAI\n", + "from langchain.agents import AgentExecutor, create_structured_chat_agent\n", + "from langchain import hub\n", + "import os\n", + "from dotenv import load_dotenv" + ], + "id": "6ae483a2b854e093", + "outputs": [], + "execution_count": 1 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:15.700593Z", + "start_time": "2024-10-18T22:17:15.694873Z" + } + }, + "cell_type": "code", + "source": [ + "# Load environment variables from .env\n", + "load_dotenv()" + ], + "id": "62379bb5905fbcec", + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "execution_count": 2 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:17.081117Z", + "start_time": "2024-10-18T22:17:15.700593Z" + } + }, + "cell_type": "code", + "source": [ + "# Load the prompt from LangSmith\n", + "LANGSMITH_KEY = os.getenv('LANGSMITH_KEY')\n", + "prompt = hub.pull(\"hwchase17/structured-chat-agent\", api_key=LANGSMITH_KEY)" + ], + "id": "6ad93fbe3f5fbee7", + "outputs": [], + "execution_count": 3 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:17.137832Z", + "start_time": "2024-10-18T22:17:17.082126Z" + } + }, + "cell_type": "code", + "source": [ + "# Instantiate the AzureTranslateTool\n", + "tools = [AzureAITextTranslateTool()]" + ], + "id": "2fb7ad6a5802d30e", + "outputs": [], + "execution_count": 4 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:17.671453Z", + "start_time": "2024-10-18T22:17:17.138837Z" + } + }, + "cell_type": "code", + "source": [ + "# Initialize the Azure OpenAI model\n", + "model = AzureChatOpenAI(\n", + " openai_api_version=os.getenv('OPENAI_API_VERSION'), \n", + " azure_deployment=os.getenv('COMPLETIONS_MODEL'),\n", + " azure_endpoint=os.getenv('AZURE_ENDPOINT'),\n", + " api_key=os.getenv('AZURE_API_KEY'),\n", + " temperature=0.5,\n", + " max_tokens=200,\n", + " timeout=60,\n", + " max_retries=10,\n", + ")" + ], + "id": "75b8572d53cc9eac", + "outputs": [], + "execution_count": 5 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:17.683846Z", + "start_time": "2024-10-18T22:17:17.672453Z" + } + }, + "cell_type": "code", + "source": [ + "# Create the agent using the model, tools, and prompt\n", + "agent = create_structured_chat_agent(model, tools, prompt)\n", + "# Set up the AgentExecutor with verbose output\n", + "agent_executor = AgentExecutor(\n", + " agent=agent, tools=tools, verbose=True, handle_parsing_errors=True\n", + ")" + ], + "id": "fabe673727ec707b", + "outputs": [], + "execution_count": 6 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 1 - Simple Translation", + "id": "83526707746bed32" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:21.972266Z", + "start_time": "2024-10-18T22:17:17.684851Z" + } + }, + "cell_type": "code", + "source": [ + "\n", + "# Input text to translate\n", + "input_text = \"Hello, how are you?\"# Invoke the agent with the translation request\n", + "try:\n", + " response = agent_executor.invoke({\"input\": f\"Can you translate the following text to te reo maori: {input_text}\"})\n", + " print(\"Translation result:\", response)\n", + "except Exception as e:\n", + " print(f\"Error during translation: {e}\")\n" + ], + "id": "94364527d63b0018", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Hello, how are you?\",\n", + " \"to_language\": \"mi\"\n", + " }\n", + "}\u001B[0m\u001B[36;1m\u001B[1;3mTēnā koe e pēhea ana koe?\u001B[0m\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"Tēnā koe e pēhea ana koe?\"\n", + "}\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Translation result: {'input': 'Can you translate the following text to te reo maori: Hello, how are you?', 'output': 'Tēnā koe e pēhea ana koe?'}\n" + ] + } + ], + "execution_count": 7 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 2 - Language Detection", + "id": "de061d907f8bbcbc" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:22.916405Z", + "start_time": "2024-10-18T22:17:21.973263Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Detect the language of \"Bonjour tout le monde\"\n", + "query_language_detection = {'input': 'Can you detect what language this phrase is in: Bonjour tout le monde'}\n", + "\n", + "# Invoke the tool to detect language\n", + "try:\n", + " response_language_detection = agent_executor.invoke(query_language_detection)\n", + " print(\"Language detection result:\", response_language_detection)\n", + "except Exception as e:\n", + " print(f\"Error during language detection: {e}\")\n" + ], + "id": "f3f873abc2fd8643", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"The phrase 'Bonjour tout le monde' is in French.\"\n", + "}\n", + "```\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Language detection result: {'input': 'Can you detect what language this phrase is in: Bonjour tout le monde', 'output': \"The phrase 'Bonjour tout le monde' is in French.\"}\n" + ] + } + ], + "execution_count": 8 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 3 Translate Complex Sentences", + "id": "727ee92dd8f7cdbb" + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "", + "id": "97ffedd4c5c7ab58" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:26.912227Z", + "start_time": "2024-10-18T22:17:22.917412Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Translate a more complex sentence to French\n", + "query_complex_sentence = {'input': 'Can you translate this technical sentence to French: \"Artificial intelligence will revolutionize healthcare in the next decade.\"'}\n", + "\n", + "# Invoke the tool to translate the complex sentence\n", + "try:\n", + " response_complex_sentence = agent_executor.invoke(query_complex_sentence)\n", + " print(\"Complex translation result:\", response_complex_sentence)\n", + "except Exception as e:\n", + " print(f\"Error during translation: {e}\")\n" + ], + "id": "3334795db21b2dff", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Artificial intelligence will revolutionize healthcare in the next decade.\",\n", + " \"to_language\": \"fr\"\n", + " }\n", + "}\n", + "```\u001B[0m\u001B[36;1m\u001B[1;3mL’intelligence artificielle révolutionnera les soins de santé au cours de la prochaine décennie.\u001B[0m\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"L’intelligence artificielle révolutionnera les soins de santé au cours de la prochaine décennie.\"\n", + "}\n", + "```\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Complex translation result: {'input': 'Can you translate this technical sentence to French: \"Artificial intelligence will revolutionize healthcare in the next decade.\"', 'output': 'L’intelligence artificielle révolutionnera les soins de santé au cours de la prochaine décennie.'}\n" + ] + } + ], + "execution_count": 9 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 4 - Language guess + translate", + "id": "2b4e8b03e6e7b059" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:30.220619Z", + "start_time": "2024-10-18T22:17:26.913232Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Guess the language and translate to English\n", + "query_language_guess_and_translate = {'input': 'Can you guess what language this is and translate it to English: \"Hola, ¿cómo estás?\"'}\n", + "\n", + "# Invoke the tool to guess language and translate\n", + "try:\n", + " response_language_guess_and_translate = agent_executor.invoke(query_language_guess_and_translate)\n", + " print(\"Guess and Translate result:\", response_language_guess_and_translate)\n", + "except Exception as e:\n", + " print(f\"Error during language guess and translation: {e}\")\n" + ], + "id": "d3a6a9f6054503b2", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3mThought: The phrase \"Hola, ¿cómo estás?\" appears to be in Spanish. I will use the Azure Translator tool to confirm and translate it to English.\n", + "\n", + "Action:\n", + "```\n", + "{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Hola, ¿cómo estás?\",\n", + " \"to_language\": \"en\"\n", + " }\n", + "}\n", + "```\u001B[0m\u001B[36;1m\u001B[1;3mHello, how are you?\u001B[0m\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"The phrase 'Hola, ¿cómo estás?' is in Spanish and translates to 'Hello, how are you?' in English.\"\n", + "}\n", + "```\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Guess and Translate result: {'input': 'Can you guess what language this is and translate it to English: \"Hola, ¿cómo estás?\"', 'output': \"The phrase 'Hola, ¿cómo estás?' is in Spanish and translates to 'Hello, how are you?' in English.\"}\n" + ] + } + ], + "execution_count": 10 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 5 - Translate to Multiple Languages", + "id": "9f7262bced602aa" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:36.012369Z", + "start_time": "2024-10-18T22:17:30.220619Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Translate \"Good morning\" into Spanish, French, and Italian\n", + "query_multiple_translations = {'input': 'Can you translate \"Good morning\" into Spanish, French, and Italian?'}\n", + "\n", + "# Invoke the tool to translate into multiple languages\n", + "try:\n", + " response_multiple_translations = agent_executor.invoke(query_multiple_translations)\n", + " print(\"Multiple translations result:\", response_multiple_translations)\n", + "except Exception as e:\n", + " print(f\"Error during translation to multiple languages: {e}\")\n" + ], + "id": "c5e6193f42d3e8ab", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Good morning\",\n", + " \"to_language\": \"es\"\n", + " }\n", + "}\u001B[0m\u001B[36;1m\u001B[1;3mBuenos días\u001B[0m\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Good morning\",\n", + " \"to_language\": \"fr\"\n", + " }\n", + "}\n", + "```\u001B[0m\u001B[36;1m\u001B[1;3mBonjour\u001B[0m\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Good morning\",\n", + " \"to_language\": \"it\"\n", + " }\n", + "}\n", + "```\u001B[0m\u001B[36;1m\u001B[1;3mBuongiorno\u001B[0m\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"The translation of 'Good morning' is 'Buenos días' in Spanish, 'Bonjour' in French, and 'Buongiorno' in Italian.\"\n", + "}\n", + "```\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Multiple translations result: {'input': 'Can you translate \"Good morning\" into Spanish, French, and Italian?', 'output': \"The translation of 'Good morning' is 'Buenos días' in Spanish, 'Bonjour' in French, and 'Buongiorno' in Italian.\"}\n" + ] + } + ], + "execution_count": 11 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 6 - Asking for Idiomatic Expressions", + "id": "1c7cc951159f1b77" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:39.008149Z", + "start_time": "2024-10-18T22:17:36.012369Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Translate the idiom \"It's raining cats and dogs\" into Spanish\n", + "query_idiom_translation = {'input': 'Can you translate the idiom \"It\\'s raining cats and dogs\" into Spanish?'}\n", + "\n", + "# Invoke the tool to translate the idiom\n", + "try:\n", + " response_idiom_translation = agent_executor.invoke(query_idiom_translation)\n", + " print(\"Idiom translation result:\", response_idiom_translation)\n", + "except Exception as e:\n", + " print(f\"Error during idiom translation: {e}\")\n" + ], + "id": "fefb7a73f1d8786d", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"It's raining cats and dogs\",\n", + " \"to_language\": \"es\"\n", + " }\n", + "}\u001B[0m\u001B[36;1m\u001B[1;3mEstá lloviendo a cántaros.\u001B[0m\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"The idiom 'It's raining cats and dogs' translates to Spanish as 'Está lloviendo a cántaros.'\"\n", + "}\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Idiom translation result: {'input': 'Can you translate the idiom \"It\\'s raining cats and dogs\" into Spanish?', 'output': \"The idiom 'It's raining cats and dogs' translates to Spanish as 'Está lloviendo a cántaros.'\"}\n" + ] + } + ], + "execution_count": 12 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 7 - Asking to Translate Back and Forth", + "id": "24cb1f36c16fd165" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:17:44.097244Z", + "start_time": "2024-10-18T22:17:39.009136Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Translate a phrase to German and then back to English\n", + "query_back_and_forth = {'input': 'Can you translate \"The quick brown fox jumps over the lazy dog\" into German, and then back to English?'}\n", + "\n", + "# Invoke the tool to translate back and forth\n", + "try:\n", + " response_back_and_forth = agent_executor.invoke(query_back_and_forth)\n", + " print(\"Back-and-forth translation result:\", response_back_and_forth)\n", + "except Exception as e:\n", + " print(f\"Error during back-and-forth translation: {e}\")\n" + ], + "id": "94fe663bdc404c6c", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"The quick brown fox jumps over the lazy dog\",\n", + " \"to_language\": \"de\"\n", + " }\n", + "}\u001B[0m\u001B[36;1m\u001B[1;3mDer flinke braune Fuchs springt über den faulen Hund\u001B[0m\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Der flinke braune Fuchs springt über den faulen Hund\",\n", + " \"to_language\": \"en\"\n", + " }\n", + "}\u001B[0m\u001B[36;1m\u001B[1;3mThe nimble brown fox jumps over the lazy dog\u001B[0m\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"The translation of 'The quick brown fox jumps over the lazy dog' into German is 'Der flinke braune Fuchs springt über den faulen Hund'. When translated back to English, it becomes 'The nimble brown fox jumps over the lazy dog'.\"\n", + "}\n", + "```\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Back-and-forth translation result: {'input': 'Can you translate \"The quick brown fox jumps over the lazy dog\" into German, and then back to English?', 'output': \"The translation of 'The quick brown fox jumps over the lazy dog' into German is 'Der flinke braune Fuchs springt über den faulen Hund'. When translated back to English, it becomes 'The nimble brown fox jumps over the lazy dog'.\"}\n" + ] + } + ], + "execution_count": 13 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 8 - Translating Phrases with Special Characters or Emojis", + "id": "366463970b6b0ea5" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:18:22.753680Z", + "start_time": "2024-10-18T22:17:44.099250Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Translate a phrase with text and emojis into French\n", + "query_with_text_and_emojis = {'input': 'Can you translate this phrase into French: \"I\\'m happy 😊 because it\\'s sunny ☀️ today.\"'}\n", + "\n", + "# Invoke the tool to translate the phrase with text and emojis\n", + "try:\n", + " response_with_text_and_emojis = agent_executor.invoke(query_with_text_and_emojis)\n", + " print(\"Emoji translation result:\", response_with_text_and_emojis)\n", + "except Exception as e:\n", + " print(f\"Error during emoji translation: {e}\")\n", + "\n" + ], + "id": "fe20e25c2d230a6d", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"I'm happy 😊 because it's sunny ☀️ today.\",\n", + " \"to_language\": \"fr\"\n", + " }\n", + "}\u001B[0m\u001B[36;1m\u001B[1;3mJe suis content 😊 parce qu’il fait beau ☀️ aujourd’hui.\u001B[0m\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"Je suis content 😊 parce qu’il fait beau ☀️ aujourd’hui.\"\n", + "}\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Emoji translation result: {'input': 'Can you translate this phrase into French: \"I\\'m happy 😊 because it\\'s sunny ☀️ today.\"', 'output': 'Je suis content 😊 parce qu’il fait beau ☀️ aujourd’hui.'}\n" + ] + } + ], + "execution_count": 14 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 9 - Longer Paragraph Translation", + "id": "20bc1bbae49034a4" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:18:25.730741Z", + "start_time": "2024-10-18T22:18:22.753680Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Translate a longer paragraph into Spanish\n", + "query_paragraph_translation = {'input': 'Can you translate this paragraph to Spanish: \"Machine learning is a subset of artificial intelligence, and it allows computers to learn from data without being explicitly programmed.\"'}\n", + "\n", + "# Invoke the tool to translate a paragraph\n", + "try:\n", + " response_paragraph_translation = agent_executor.invoke(query_paragraph_translation)\n", + " print(\"Paragraph translation result:\", response_paragraph_translation)\n", + "except Exception as e:\n", + " print(f\"Error during paragraph translation: {e}\")\n" + ], + "id": "5735995f84383ac8", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Machine learning is a subset of artificial intelligence, and it allows computers to learn from data without being explicitly programmed.\",\n", + " \"to_language\": \"es\"\n", + " }\n", + "}\u001B[0m\u001B[36;1m\u001B[1;3mEl aprendizaje automático es un subconjunto de la inteligencia artificial y permite a los ordenadores aprender de los datos sin necesidad de programarlos explícitamente.\u001B[0m\u001B[32;1m\u001B[1;3m{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"El aprendizaje automático es un subconjunto de la inteligencia artificial y permite a los ordenadores aprender de los datos sin necesidad de programarlos explícitamente.\"\n", + "}\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Paragraph translation result: {'input': 'Can you translate this paragraph to Spanish: \"Machine learning is a subset of artificial intelligence, and it allows computers to learn from data without being explicitly programmed.\"', 'output': 'El aprendizaje automático es un subconjunto de la inteligencia artificial y permite a los ordenadores aprender de los datos sin necesidad de programarlos explícitamente.'}\n" + ] + } + ], + "execution_count": 15 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "Example 10 - Asking for a Reverse Translation", + "id": "929bf72aee7b1d83" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-10-18T22:18:32.983994Z", + "start_time": "2024-10-18T22:18:25.731739Z" + } + }, + "cell_type": "code", + "source": [ + "# Example: Reverse translate a complex sentence through multiple languages (English -> German -> Spanish -> English)\n", + "query_reverse_translation_complex = {\n", + " 'input': 'Translate \"The quick brown fox jumps over the lazy dog\" into German, then into Spanish, and finally back to English. Let\\'s see if the meaning remains the same.'\n", + "}\n", + "\n", + "# Invoke the tool for complex reverse translation\n", + "try:\n", + " response_reverse_translation_complex = agent_executor.invoke(query_reverse_translation_complex)\n", + " print(\"Complex reverse translation result:\", response_reverse_translation_complex)\n", + "except Exception as e:\n", + " print(f\"Error during reverse translation: {e}\")\n", + "\n" + ], + "id": "8ace6212a41fcd59", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n", + "\u001B[32;1m\u001B[1;3mThought: I will first translate the sentence into German, then into Spanish, and finally back to English.\n", + "\n", + "Action:\n", + "```\n", + "{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"The quick brown fox jumps over the lazy dog\",\n", + " \"to_language\": \"de\"\n", + " }\n", + "}\n", + "```\u001B[0m\u001B[36;1m\u001B[1;3mDer flinke braune Fuchs springt über den faulen Hund\u001B[0m\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"Der flinke braune Fuchs springt über den faulen Hund\",\n", + " \"to_language\": \"es\"\n", + " }\n", + "}\n", + "```\u001B[0m\u001B[36;1m\u001B[1;3mEl ágil zorro marrón salta sobre el perro perezoso\u001B[0m\u001B[32;1m\u001B[1;3mAction:\n", + "```\n", + "{\n", + " \"action\": \"azure_translator_tool\",\n", + " \"action_input\": {\n", + " \"query\": \"El ágil zorro marrón salta sobre el perro perezoso\",\n", + " \"to_language\": \"en\"\n", + " }\n", + "}\n", + "```\u001B[0m\u001B[36;1m\u001B[1;3mThe agile brown fox jumps on the lazy dog\u001B[0m\u001B[32;1m\u001B[1;3mThe meaning of the sentence has slightly changed during the translations, particularly the preposition \"over\" has been altered to \"on.\"\n", + "\n", + "Action:\n", + "```\n", + "{\n", + " \"action\": \"Final Answer\",\n", + " \"action_input\": \"The agile brown fox jumps on the lazy dog\"\n", + "}\n", + "```\u001B[0m\n", + "\n", + "\u001B[1m> Finished chain.\u001B[0m\n", + "Complex reverse translation result: {'input': 'Translate \"The quick brown fox jumps over the lazy dog\" into German, then into Spanish, and finally back to English. Let\\'s see if the meaning remains the same.', 'output': 'The agile brown fox jumps on the lazy dog'}\n" + ] + } + ], + "execution_count": 16 + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}