# 配置
BASE_URL = "https://api.deepseek.com"
API_KEY = ""
from openai import OpenAI
import config
# 创建客户端
client = OpenAI(api_key=config.API_KEY, base_url=config.BASE_URL)
def send_text_message(message_text):
try:
response = client.chat.completions.create(
model="deepseek-chat", # 固定模型名
messages=[
{"role": "user", "content": message_text}
],
# 可选参数
temperature=0.7,
max_tokens=1024,
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"调用 DeepSeek API 出错: {str(e)}"
import pyttsx3
import threading
from robot import send_text_message
def speak_async(text):
"""在子线程中异步朗读语音"""
def run():
engine = pyttsx3.init()
# 可选:设置语速
engine.setProperty('rate', 180)
# 可选:设置音量
engine.setProperty('volume', 0.9)
# 可选:设置中文语音
voices = engine.getProperty('voices')
for voice in voices:
if 'Chinese' in voice.name or '普通话' in voice.id or 'Hui' in voice.name:
engine.setProperty('voice', voice.id)
break
engine.say(text)
engine.runAndWait() # 在子线程中运行,不会阻塞主线程
engine.stop()
# 启动子线程播放语音
thread = threading.Thread(target=run, daemon=True)
thread.start()
def ask(your_name, ai_name):
question = input(f'{your_name} (输入0结束聊天):')
if question == '0':
return False
# 异步朗读用户输入
speak_async(question)
# 调用 AI 获取回复
result = send_text_message(question)
print(f'{ai_name}:{result}')
# 异步朗读 AI 回复
speak_async(result)
return True
def main():
print('欢迎来到聊天室,请问你的名字', end=': ')
speak_async('欢迎来到聊天室,请问你的名字。')
your_name = input()
print('你好,我是你的聊天对象,请为我取名字', end=': ')
speak_async('你好,我是你的聊天对象,请为我取名字。')
ai_name = input()
while True:
if not ask(your_name, ai_name):
break
if __name__ == '__main__':
main()