[docs]classElevenLabsModel(str,Enum):"""Models available for Eleven Labs Text2Speech."""MULTI_LINGUAL="eleven_multilingual_v1"MONO_LINGUAL="eleven_monolingual_v1"
[docs]classElevenLabsText2SpeechTool(BaseTool):"""Tool that queries the Eleven Labs Text2Speech API. In order to set this up, follow instructions at: https://docs.elevenlabs.io/welcome/introduction """model:Union[ElevenLabsModel,str]=ElevenLabsModel.MULTI_LINGUALname:str="eleven_labs_text2speech"description:str=("A wrapper around Eleven Labs Text2Speech. ""Useful for when you need to convert text to speech. ""It supports multiple languages, including English, German, Polish, ""Spanish, Italian, French, Portuguese, and Hindi. ")@root_validator(pre=True)defvalidate_environment(cls,values:Dict)->Dict:"""Validate that api key exists in environment."""_=get_from_dict_or_env(values,"eleven_api_key","ELEVEN_API_KEY")returnvaluesdef_run(self,query:str,run_manager:Optional[CallbackManagerForToolRun]=None)->str:"""Use the tool."""elevenlabs=_import_elevenlabs()try:speech=elevenlabs.generate(text=query,model=self.model)withtempfile.NamedTemporaryFile(mode="bx",suffix=".wav",delete=False)asf:f.write(speech)returnf.nameexceptExceptionase:raiseRuntimeError(f"Error while running ElevenLabsText2SpeechTool: {e}")
[docs]defplay(self,speech_file:str)->None:"""Play the text as speech."""elevenlabs=_import_elevenlabs()withopen(speech_file,mode="rb")asf:speech=f.read()elevenlabs.play(speech)
[docs]defstream_speech(self,query:str)->None:"""Stream the text as speech as it is generated. Play the text in your speakers."""elevenlabs=_import_elevenlabs()speech_stream=elevenlabs.generate(text=query,model=self.model,stream=True)elevenlabs.stream(speech_stream)