[docs]classAzureAiServicesTextToSpeechTool(BaseTool):# type: ignore[override]"""Tool that queries the Azure AI Services Text to Speech API. In order to set this up, follow instructions at: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/get-started-text-to-speech?pivots=programming-language-python """name:str="azure_ai_services_text_to_speech"description:str=("A wrapper around Azure AI Services Text to Speech API. ""Useful for when you need to convert text to speech. ")return_direct:bool=Trueazure_ai_services_key:str=""#: :meta private:azure_ai_services_region:str=""#: :meta private:speech_language:str="en-US"#: :meta private:speech_config:Any#: :meta private:@model_validator(mode="before")@classmethoddefvalidate_environment(cls,values:Dict)->Any:"""Validate that api key and endpoint exists in environment."""azure_ai_services_key=get_from_dict_or_env(values,"azure_ai_services_key","AZURE_AI_SERVICES_KEY")azure_ai_services_region=get_from_dict_or_env(values,"azure_ai_services_region","AZURE_AI_SERVICES_REGION")try:importazure.cognitiveservices.speechasspeechsdkvalues["speech_config"]=speechsdk.SpeechConfig(subscription=azure_ai_services_key,region=azure_ai_services_region)exceptImportError:raiseImportError("azure-cognitiveservices-speech is not installed. ""Run `pip install azure-cognitiveservices-speech` to install.")returnvaluesdef_text_to_speech(self,text:str,speech_language:str)->str:try:importazure.cognitiveservices.speechasspeechsdkexceptImportError:passself.speech_config.speech_synthesis_language=speech_languagespeech_synthesizer=speechsdk.SpeechSynthesizer(speech_config=self.speech_config,audio_config=None)result=speech_synthesizer.speak_text(text)ifresult.reason==speechsdk.ResultReason.SynthesizingAudioCompleted:stream=speechsdk.AudioDataStream(result)withtempfile.NamedTemporaryFile(mode="wb",suffix=".wav",delete=False)asf:stream.save_to_wav_file(f.name)returnf.nameelifresult.reason==speechsdk.ResultReason.Canceled:cancellation_details=result.cancellation_detailslogger.debug(f"Speech synthesis canceled: {cancellation_details.reason}")ifcancellation_details.reason==speechsdk.CancellationReason.Error:raiseRuntimeError(f"Speech synthesis error: {cancellation_details.error_details}")return"Speech synthesis canceled."else:returnf"Speech synthesis failed: {result.reason}"def_run(self,query:str,run_manager:Optional[CallbackManagerForToolRun]=None,)->str:"""Use the tool."""try:speech_file=self._text_to_speech(query,self.speech_language)returnspeech_fileexceptExceptionase:raiseRuntimeError(f"Error while running AzureAiServicesTextToSpeechTool: {e}")