129 lines
4.7 KiB
Python
129 lines
4.7 KiB
Python
import json
|
||
import os
|
||
import re
|
||
import requests
|
||
|
||
from .config import AGENTS, log
|
||
from .text import clean_for_speech, find_sentence_end
|
||
from .tts import speak, play_error_sound
|
||
|
||
# Ключ голосовой сессии — Cosmo работает как полноценный агент
|
||
VOICE_SESSION_KEY = os.getenv("VOICE_SESSION_KEY", "agent:main:voice:home")
|
||
|
||
# "stream" — режем по предложениям (быстро, но рваная интонация)
|
||
# "full" — собираем весь ответ, потом TTS (естественно, но пауза перед началом)
|
||
TTS_MODE = os.getenv("TTS_MODE", "full")
|
||
|
||
RESET_PATTERNS = re.compile(
|
||
r"(начни|начать|создай|открой|давай).{0,10}(новую|новый|чистую|чистый).{0,10}(сессию|сессия|диалог|разговор|чат)"
|
||
r"|"
|
||
r"(сбрось|очисти|обнови).{0,10}(сессию|диалог|разговор|чат|историю|контекст)",
|
||
re.IGNORECASE,
|
||
)
|
||
|
||
|
||
def is_reset_command(text: str) -> bool:
|
||
return bool(RESET_PATTERNS.search(text))
|
||
|
||
|
||
def ask_agent_stream(text: str, conv=None, agent_id: str = "cosmo") -> str:
|
||
"""
|
||
Отправляет запрос к OpenClaw gateway как полноценный агент.
|
||
История хранится на стороне gateway (session_key).
|
||
conv параметр сохранён для обратной совместимости, не используется.
|
||
"""
|
||
cfg = AGENTS.get(agent_id, AGENTS["cosmo"])
|
||
gateway_url = cfg["gateway_url"]
|
||
session = cfg["session"]
|
||
agent = cfg["agent"]
|
||
|
||
session_key = cfg.get("session_key", VOICE_SESSION_KEY)
|
||
|
||
try:
|
||
resp = session.post(
|
||
f"{gateway_url}/v1/chat/completions",
|
||
headers={
|
||
"x-ocplatform-model": cfg["voice_model"],
|
||
"x-openclaw-session-key": session_key,
|
||
},
|
||
json={
|
||
"model": agent,
|
||
"stream": True,
|
||
"messages": [{"role": "user", "content": text}],
|
||
"max_tokens": 150,
|
||
},
|
||
stream=True,
|
||
timeout=60,
|
||
)
|
||
resp.raise_for_status()
|
||
except requests.ConnectionError:
|
||
log.exception("Gateway недоступен")
|
||
msg = "Не могу связаться с сервером, попробуй ещё раз."
|
||
print(f"⚠️ {msg}")
|
||
play_error_sound()
|
||
speak(msg, agent_id)
|
||
return msg
|
||
except requests.Timeout:
|
||
log.exception("Gateway таймаут")
|
||
msg = "Сервер не ответил вовремя, попробуй ещё раз."
|
||
print(f"⚠️ {msg}")
|
||
play_error_sound()
|
||
speak(msg, agent_id)
|
||
return msg
|
||
except requests.HTTPError:
|
||
log.exception(f"Gateway HTTP ошибка {resp.status_code}")
|
||
msg = "Ошибка сервера, попробуй ещё раз."
|
||
print(f"⚠️ Gateway {resp.status_code}: {resp.text}")
|
||
play_error_sound()
|
||
speak(msg, agent_id)
|
||
return msg
|
||
|
||
full_text = ""
|
||
buffer = ""
|
||
|
||
try:
|
||
for line in resp.iter_lines():
|
||
if not line or line == b"data: [DONE]":
|
||
continue
|
||
if line.startswith(b"data: "):
|
||
try:
|
||
chunk = json.loads(line[6:])
|
||
delta = chunk["choices"][0]["delta"].get("content", "")
|
||
if not delta:
|
||
continue
|
||
|
||
full_text += delta
|
||
buffer += delta
|
||
|
||
if TTS_MODE == "stream":
|
||
last_punct = find_sentence_end(buffer, min_len=120)
|
||
if last_punct > -1:
|
||
sentence = clean_for_speech(buffer[:last_punct + 1])
|
||
if sentence.strip():
|
||
speak(sentence, agent_id)
|
||
buffer = buffer[last_punct + 1:].lstrip()
|
||
|
||
except (json.JSONDecodeError, KeyError, IndexError):
|
||
continue
|
||
except Exception as e:
|
||
log.exception("Ошибка при чтении стрима")
|
||
print(f"⚠️ Стрим прервался: {e}")
|
||
|
||
if not full_text:
|
||
msg = "Не получил ответ, попробуй ещё раз."
|
||
speak(msg, agent_id)
|
||
return msg
|
||
|
||
result = clean_for_speech(full_text)
|
||
|
||
if TTS_MODE == "full":
|
||
if result.strip():
|
||
speak(result, agent_id)
|
||
else:
|
||
if buffer.strip():
|
||
tail = clean_for_speech(buffer)
|
||
if tail:
|
||
speak(tail, agent_id)
|
||
|
||
return result
|