ElevenLabs API 交互以实现文本转语音功能。 首先,您需要设置一个 ElevenLabs 帐户。您可以按照此处的说明操作。复制
向 AI 提问
pip install -qU elevenlabs langchain-community
复制
向 AI 提问
import os
os.environ["ELEVENLABS_API_KEY"] = ""
用法
复制
向 AI 提问
from langchain_community.tools import ElevenLabsText2SpeechTool
text_to_speak = "Hello world! I am the real slim shady"
tts = ElevenLabsText2SpeechTool()
tts.name
复制
向 AI 提问
'eleven_labs_text2speech'
复制
向 AI 提问
speech_file = tts.run(text_to_speak)
tts.play(speech_file)
复制
向 AI 提问
tts.stream_speech(text_to_speak)
在 Agent 中使用
复制
向 AI 提问
from langchain.agents import AgentType, initialize_agent, load_tools
from langchain_openai import OpenAI
复制
向 AI 提问
llm = OpenAI(temperature=0)
tools = load_tools(["eleven_labs_text2speech"])
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
)
复制
向 AI 提问
audio_file = agent.run("Tell me a joke and read it out for me.")
复制
向 AI 提问
> Entering new AgentExecutor chain...
Action:
\`\`\`
{
"action": "eleven_labs_text2speech",
"action_input": {
"query": "Why did the chicken cross the playground? To get to the other slide!"
}
}
\`\`\`
Observation: /tmp/tmpsfg783f1.wav
Thought: I have the audio file ready to be sent to the human
Action:
\`\`\`
{
"action": "Final Answer",
"action_input": "/tmp/tmpsfg783f1.wav"
}
\`\`\`
> Finished chain.
复制
向 AI 提问
tts.play(audio_file)
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。