Spaces:
Sleeping

datbkpro commited on
Commit
6aef77a
·
verified ·
1 Parent(s): 1e3a9b7

Update services/sambanova_voice_service.py

Browse files
Files changed (1) hide show
  1. services/sambanova_voice_service.py +17 -96
services/sambanova_voice_service.py CHANGED
@@ -12,8 +12,8 @@ from fastrtc import (
12
  get_stt_model,
13
  )
14
 
15
- class SambanovaVoiceService:
16
- """Dịch vụ Voice AI với Sambanova API - Fixed State elem_id error"""
17
 
18
  def __init__(self):
19
  # Khởi tạo client Sambanova
@@ -21,98 +21,19 @@ class SambanovaVoiceService:
21
  api_key=os.environ.get("SAMBANOVA_API_KEY"),
22
  base_url="https://api.sambanova.ai/v1",
23
  )
24
-
25
- # STT model
26
- self.model = get_stt_model()
27
-
28
- # RTC configuration - DISABLE TURN
29
- self.rtc_configuration = None
30
-
31
- print("✅ Sambanova Voice Service initialized")
32
 
33
- def create_stream(self):
34
- """Tạo FastRTC stream với components đơn giản"""
35
- response_handler = self._create_response_handler()
36
-
37
- # Tạo components không dùng elem_id cho State
38
- chatbot_input = gr.Chatbot(
39
- type="messages",
40
- value=[],
41
- label="💬 Voice Conversation",
42
- height=300
43
- )
44
-
45
- state_input = gr.State(value=[])
46
-
47
- chatbot_output = gr.Chatbot(type="messages", value=[])
48
- state_output = gr.State(value=[])
49
-
50
- return Stream(
51
- ReplyOnStopWords(
52
- response_handler,
53
- stop_words=["computer", "hey", "hello", "xin chào", "llama"],
54
- input_sample_rate=16000,
55
- ),
56
- mode="send",
57
- modality="audio",
58
- additional_inputs=[chatbot_input, state_input],
59
- additional_outputs=[chatbot_output, state_output],
60
- additional_outputs_handler=lambda *args: (args[2], args[3]),
61
- concurrency_limit=2,
62
- time_limit=90,
63
- rtc_configuration=self.rtc_configuration,
64
- )
65
-
66
- def _create_response_handler(self):
67
- """Tạo response handler cho voice streaming"""
68
-
69
- def response(
70
- audio: tuple[int, np.ndarray],
71
- gradio_chatbot: list[dict] | None = None,
72
- conversation_state: list[dict] | None = None,
73
- ):
74
- gradio_chatbot = gradio_chatbot or []
75
- conversation_state = conversation_state or []
76
-
77
- try:
78
- # Speech to Text
79
- text = self.model.stt(audio)
80
- print("🎤 STT Result:", text)
81
-
82
- if not text.strip():
83
- yield AdditionalOutputs(gradio_chatbot, conversation_state)
84
- return
85
-
86
- # Thêm user message
87
- user_msg = {"role": "user", "content": f"🎤: {text}"}
88
- gradio_chatbot.append(user_msg)
89
- conversation_state.append({"role": "user", "content": text})
90
-
91
- yield AdditionalOutputs(gradio_chatbot, conversation_state)
92
-
93
- # Gọi Sambanova API
94
- print("🤖 Calling Sambanova API...")
95
- request = self.client.chat.completions.create(
96
- model="Meta-Llama-3.2-3B-Instruct",
97
- messages=conversation_state,
98
- temperature=0.1,
99
- top_p=0.1,
100
- )
101
- response_content = {
102
- "role": "assistant",
103
- "content": request.choices[0].message.content
104
- }
105
-
106
- conversation_state.append(response_content)
107
- gradio_chatbot.append(response_content)
108
-
109
- yield AdditionalOutputs(gradio_chatbot, conversation_state)
110
-
111
- except Exception as e:
112
- print(f"❌ Error in response handler: {e}")
113
- error_msg = {"role": "assistant", "content": f"❌ Lỗi: {str(e)}"}
114
- gradio_chatbot.append(error_msg)
115
- conversation_state.append(error_msg)
116
- yield AdditionalOutputs(gradio_chatbot, conversation_state)
117
-
118
- return response
 
12
  get_stt_model,
13
  )
14
 
15
+ class SambanovaService:
16
+ """Dịch vụ Sambanova AI - Text Only"""
17
 
18
  def __init__(self):
19
  # Khởi tạo client Sambanova
 
21
  api_key=os.environ.get("SAMBANOVA_API_KEY"),
22
  base_url="https://api.sambanova.ai/v1",
23
  )
24
+ print("✅ Sambanova Service initialized (Text Mode)")
 
 
 
 
 
 
 
25
 
26
+ def generate_response(self, messages):
27
+ """Generate response từ Sambanova API"""
28
+ try:
29
+ response = self.client.chat.completions.create(
30
+ model="Meta-Llama-3.2-3B-Instruct",
31
+ messages=messages,
32
+ temperature=0.1,
33
+ top_p=0.1,
34
+ max_tokens=1024,
35
+ )
36
+ return response.choices[0].message.content
37
+ except Exception as e:
38
+ print(f"❌ Sambanova API Error: {e}")
39
+ return f"Xin lỗi, có lỗi xảy ra: {str(e)}"