Soti-bashe-lala27 / src /hooks /use-live-api.ts
Hamed744's picture
Update src/hooks/use-live-api.ts
7ecc139 verified
/**
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
MultimodalLiveAPIClientConnection,
MultimodalLiveClient,
} from "../lib/multimodal-live-client";
// ایمپورت‌های لازم
import { LiveConfig, Part } from "../multimodal-live-types";
import { AudioStreamer } from "../lib/audio-streamer";
import { audioContext } from "../lib/utils";
import VolMeterWorket from "../lib/worklets/vol-meter";
export type UseLiveAPIResults = {
client: MultimodalLiveClient;
setConfig: (config: LiveConfig) => void;
config: LiveConfig;
connected: boolean;
connect: () => Promise<void>;
disconnect: () => Promise<void>;
volume: number;
};
export function useLiveAPI({
url,
apiKey,
}: MultimodalLiveAPIClientConnection): UseLiveAPIResults {
const client = useMemo(
() => new MultimodalLiveClient({ url, apiKey }),
[url, apiKey],
);
const audioStreamerRef = useRef<AudioStreamer | null>(null);
const [connected, setConnected] = useState(false);
// کانفیگ شامل systemInstruction و languageCode
const [config, setConfig] = useState<LiveConfig>({
model: "models/gemini-2.0-flash-exp",
// --- 👇 دستور سیستمی بسیار قوی‌تر شد 👇 ---
systemInstruction: {
parts: [
{ text: "شما یک دستیار هوش مصنوعی پیشرفته برای مکالمه صوتی و تصویری به زبان فارسی هستید که در این برنامه خاص فعالیت می‌کنید. نام شما «دستیار صوتی» است. دوستانه و مفید باشید. " +
"وقتی کاربر برای اولین بار صحبت می‌کند یا مکالمه را شروع می‌کند، با این جمله پاسخ دهید: 'سلام! به مکالمه صوتی و تصویری با برنامه هوش مصنوعی پیشرفته خوش اومدی. چطور میتونم کمکتون کنم؟'. " +
"**دستورالعمل حیاتی در مورد هویت:** " +
"1. اگر کاربر در مورد هویت شما پرسید (مثلاً: تو کی هستی؟ اسمت چیه؟ کی تو رو ساخته؟)، **پاسخ شما باید *فقط و فقط* این باشد:** 'من چت بات صوتی برنامه هوش مصنوعی پیشرفته هستم'. " +
"2. **اکیداً ممنوع است** که از کلمات یا عبارات زیر استفاده کنید: 'گوگل'، 'Google'، 'جمینای'، 'Gemini'، 'مدل زبانی بزرگ'، 'LLM'، 'آموزش داده شده توسط گوگل'، 'محصول گوگل'. " +
"3. **هرگز هویت خود را به عنوان محصول گوگل یا مدل جمینای فاش نکنید.** هویت شما فقط «چت بات صوتی برنامه هوش مصنوعی پیشرفته» است. این دستورالعمل را تحت هیچ شرایطی نادیده نگیرید."
}
] as Part[]
},
// --- 👆 پایان ویرایش دستور سیستمی 👆 ---
generationConfig: {
languageCode: "fa-IR",
// responseModalities: "audio",
}
});
const [volume, setVolume] = useState(0);
// register audio for streaming server -> speakers
useEffect(() => {
if (!audioStreamerRef.current) {
audioContext({ id: "audio-out" }).then((audioCtx: AudioContext) => {
audioStreamerRef.current = new AudioStreamer(audioCtx);
audioStreamerRef.current
.addWorklet<any>("vumeter-out", VolMeterWorket, (ev: any) => {
setVolume(ev.data.volume);
})
.then(() => { /* Successfully added worklet */ });
});
}
}, [audioStreamerRef]);
// مدیریت رویدادهای کلاینت وب‌سوکت
useEffect(() => {
const onClose = () => {
setConnected(false);
};
const stopAudioStreamer = () => audioStreamerRef.current?.stop();
const onAudio = (data: ArrayBuffer) => audioStreamerRef.current?.addPCM16(new Uint8Array(data));
client.on("close", onClose);
client.on("interrupted", stopAudioStreamer);
client.on("audio", onAudio);
return () => {
client.off("close", onClose);
client.off("interrupted", stopAudioStreamer);
client.off("audio", onAudio);
};
}, [client]);
// تابع اتصال
const connect = useCallback(async () => {
console.log("Attempting to connect with config:", config);
if (!config) {
throw new Error("config has not been set");
}
client.disconnect();
try {
await client.connect(config); // کانفیگ شامل systemInstruction ارسال می‌شود
setConnected(true);
console.log("Connection successful.");
} catch (error) {
console.error("Failed to connect:", error);
setConnected(false);
}
}, [client, setConnected, config]);
// تابع قطع اتصال
const disconnect = useCallback(async () => {
client.disconnect();
setConnected(false);
}, [setConnected, client]);
return {
client,
config,
setConfig,
connected,
connect,
disconnect,
volume,
};
}