Spaces:
Configuration error
Configuration error
Commit ·
4e6f302
1
Parent(s): a3e05d0
Deploy files from GitHub repository
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- space/README.md-1
- space/space/space/Dockerfile+17-29
- space/space/space/space/space/space/space/README.md-18
- space/space/space/space/space/space/space/space/space/README.md+108-18
- space/space/space/space/space/space/space/space/space/data/prompt_template/customer_service.txt+10-10
- space/space/space/space/space/space/space/space/space/main.py+11-2
- space/space/space/space/space/space/space/space/space/space/space/README.md-2
- space/space/space/space/space/space/space/space/space/space/space/space/space/README.md+1-1
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/README.md+8-3
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/data/prompt_template/customer_service.txtAdded+12
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/data/prompt_template/query_maker.txtAdded+35
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/main.pyAdded+32
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/__chat__.py-2
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/__init__.py+1-1
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/pipeline/language_model.py+70-70
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/pipeline/preprocessing.py+70-70
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/base_retriever.py+4-4
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/document_loader.py+3-3
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/document_processor.py+3-3
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/langchain_retriever.py+11-11
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/web_search/duckduckgo_search.py+19-19
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rtc/rtc_call.py+15-15
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/stt/whisper_stt.py+10-10
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/tts/audio_edge_tts.py+3-3
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/__init__.py+2-2
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/__init__.pyAdded
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/agents.pyAdded+16
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/customer_service_agent.pyAdded+33
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/gpt_customer_service_agent.pyAdded+13
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/query_maker_agent.pyAdded+13
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/chat_template/__init__.pyAdded+29
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/chat_template/customer_service.txtAdded+12
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/chat_template/query_maker.txtAdded+35
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/chat_template/query_maker_temp.txtAdded+30
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/inference/__init__.pyAdded
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/pipeline/language_model.pyAdded+947
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/__init__.pyAdded
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/langchain_retriever.py+25-7
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/web_search/__init__.pyAdded
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rtc/rtc_call_gpt.pyAdded+364
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/tests/qwen_llm_test.py+9-9
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/__chat__.py+4-3
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/__test__.py-5
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/app.logAdded
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/__init__.py+61-21
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/inference/inferencer.py+51-9
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/pipeline/qwen_llm.py+29-8
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/prompt_tuner/chat_template.py+6-4
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/web_search/duckduckgo_search.pyAdded+142
- space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rtc/__init__.py+3-1
69 unmodified lines7071727374757669 unmodified lines### Chatbot Interface```bashcd apppython main.py --mode chatbot --port 7861```69 unmodified lines70717273747569 unmodified lines### Chatbot Interface```bashpython main.py --mode chatbot --port 7861```
123456789101112131 unmodified line1516171819202122232425262728293031323334353637383940414243444546474849# Gunakan image dasar Python versi 3.13FROM python:3.13# Tambahkan user non-root untuk keamananRUN useradd -m -u 1001 appuser# Set working directoryWORKDIR /rag_be# Set cache directories ke writable locationENV HF_HOME=/tmp/.cache/huggingfaceENV TRANSFORMERS_CACHE=/tmp/.cache/transformersENV TORCH_HOME=/tmp/.cache/torch1 unmodified lineENV TMPDIR=/tmpENV WHISPER_CACHE_DIR=/tmp/.cache/whisper# Copy requirements dan install dependenciesCOPY requirements.txt ./RUN pip install --no-cache-dir --upgrade -r requirements.txt# Copy aplikasi dengan ownership ke appuserCOPY --chown=appuser:appuser . /rag_be# Buat file .env dengan variabel environment menggunakan Hugging Face secretsRUN --mount=type=secret,id=OPENAI_API_KEY,mode=0444,required=false \--mount=type=secret,id=HF_TOKEN,mode=0444,required=false \--mount=type=secret,id=ELEVENLABS_API_KEY,mode=0444,required=false \echo "OPENAI_API_KEY=$(cat /run/secrets/OPENAI_API_KEY 2>/dev/null || echo '')" >> .env && \echo "HF_TOKEN=$(cat /run/secrets/HF_TOKEN 2>/dev/null || echo '')" >> .env && \echo "ELEVENLABS_API_KEY=$(cat /run/secrets/ELEVENLABS_API_KEY 2>/dev/null || echo '')" >> .envRUN ls -l /rag_be/app && whoami && id# Buat directories yang diperlukan dengan permissions yang tepatRUN mkdir -p /tmp/.cache /tmp/.cache/whisper /tmp/.cache/huggingface /rag_be/vectorstore /tmp/.cache/transformers /tmp/.cache/torch \/rag_be/app/vectorstore /rag_be/documents && \chmod -R 777 /tmp/.cache /rag_be/app /rag_be/app/vectorstore /rag_be/vectorstore /rag_be/documents && \chown -R appuser:appuser /tmp/.cache /rag_be/app /rag_be/app/vectorstore /rag_be/vectorstore /rag_be/documents /rag_be/.envRUN apt-get update && apt-get install -y ffmpeg# Beralih ke user non-rootUSER appuser# Expose port untuk Hugging Face SpacesEXPOSE 7860# Jalankan aplikasiCMD ["python", "app/__test__.py"]123456789101 unmodified line1213141516171819202122232425262728293031323334353637FROM python:3.13RUN useradd -m -u 1001 appuserWORKDIR /rag_beENV HF_HOME=/tmp/.cache/huggingfaceENV TRANSFORMERS_CACHE=/tmp/.cache/transformersENV TORCH_HOME=/tmp/.cache/torch1 unmodified lineENV TMPDIR=/tmpENV WHISPER_CACHE_DIR=/tmp/.cache/whisperCOPY requirements.txt ./RUN pip install --no-cache-dir --upgrade -r requirements.txtCOPY --chown=appuser:appuser . /rag_beRUN mkdir -p /tmp/.cache \/tmp/.cache/whisper \/tmp/.cache/huggingface \/tmp/.cache/transformers \/tmp/.cache/torch \/rag_be/vectorstore \/rag_be/app/vectorstore \/rag_be/documents && \chmod -R 777 /tmp/.cache /rag_be/app /rag_be/vectorstore /rag_be/documentsRUN apt-get update && apt-get install -y ffmpeg && apt-get cleanUSER appuserEXPOSE 8000CMD ["python", "main.py --mode rtc-ui --port 7860"]
103 unmodified lines104105106107108109110111112113114115116117118119120121122123124103 unmodified linesOnce the server is running, you can access the API documentation at:- `http://localhost:{port}/docs` (if using FastAPI)- `http://localhost:{port}` (for Gradio interface)## 🏗️ Project Structure```cs-ai-sakura-dev/├── app/│ └── main.py # Chatbot application├── main.py # Main application entry point├── requirements.txt # Python dependencies├── .env # Environment variables (create this)├── Dockerfile # Docker configuration└── README.md # Project documentation```---**Happy coding! 🌸**103 unmodified lines104105106103 unmodified linesOnce the server is running, you can access the API documentation at:- `http://localhost:{port}/docs` (if using FastAPI)- `http://localhost:{port}` (for Gradio interface)
12345678910111213141516171819202122232425262728293031323334---title: Cs Ai Sakura Devemoji: 🏢colorFrom: indigocolorTo: indigosdk: dockerpinned: false---**Install The Requirements**1.Create a virtual environment and install the dependencies```python3 -m venv envsource env/bin/activatepip install -r requirements.txt```2. Set your OPENAI_API_KEY in .env file3. **TO LAUNCH THE GRADIO UI** Run the command below :```python main.py --mode rtc-ui --port {your_port}```4. **TO LAUNCH THE API ENDPOINT (SERVER)** Run the command below :```python main.py --mode rtc-server --port {your_port}```5. **TO LAUNCH THE CHATBOT UI** Run the command below :```python main.py --mode chatbot --port {your_port}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124# CS AI Sakura Dev 🏢A comprehensive AI-powered application with multiple modes including RTC (Real-Time Communication), GPT integration, and chatbot functionality.## 🚀 Features- **RTC Mode**: Real-time communication interface- **GPT Integration**: Enhanced AI capabilities with OpenAI GPT models- **Chatbot Interface**: Interactive chat functionality- **Gradio UI**: User-friendly web interface- **API Server**: RESTful API endpoints- **Docker Support**: Containerized deployment## 📋 Prerequisites- Python 3.8 or higher- OpenAI API Key- Docker (optional)## ⚙️ Installation### 1. Clone the Repository```bashgit clone <repository-url>cd cs-ai-sakura-dev```### 2. Create Virtual Environment```bashpython3 -m venv envsource env/bin/activate # On Windows: env\Scripts\activate```### 3. Install Dependencies```bashpip install -r requirements.txt```### 4. Environment ConfigurationCreate a `.env` file in the root directory and add your OpenAI API key:```bashOPENAI_API_KEY=your_openai_api_key_here```## 🖥️ Usage### Gradio Web Interface#### Non-GPT Based UI```bashpython main.py --mode rtc-ui --port 8080```#### GPT-Powered UI```bashpython main.py --mode rtc-gpt-ui --port 8080```### API Server#### Non-GPT Based Server```bashpython main.py --mode rtc-server --port 8080```#### GPT-Powered Server```bashpython main.py --mode rtc-gpt-server --port 8080```### Chatbot Interface```bashcd apppython main.py --mode chatbot --port 8080```## 🐳 Docker DeploymentThe application supports Docker deployment. Build and run the container:```bashdocker build -t cs-ai-sakura-dev .docker run -p 8080:8080 cs-ai-sakura-dev```## 📚 Available Modes| Mode | Description | Command ||------|-------------|---------|| `rtc-ui` | Real-time communication web interface | `python main.py --mode rtc-ui --port {port}` || `rtc-gpt-ui` | GPT-powered real-time communication UI | `python main.py --mode rtc-gpt-ui --port {port}` || `rtc-server` | Real-time communication API server | `python main.py --mode rtc-server --port {port}` || `rtc-gpt-server` | GPT-powered API server | `python main.py --mode rtc-gpt-server --port {port}` || `chatbot` | Interactive chatbot interface | `cd app && python main.py --mode chatbot --port {port}` |## 🔧 Configuration### Environment Variables- `OPENAI_API_KEY`: Your OpenAI API key (required for GPT modes)- `PORT`: Application port (default: 8080)## 📖 API DocumentationOnce the server is running, you can access the API documentation at:- `http://localhost:{port}/docs` (if using FastAPI)- `http://localhost:{port}` (for Gradio interface)## 🏗️ Project Structure```cs-ai-sakura-dev/├── app/│ └── main.py # Chatbot application├── main.py # Main application entry point├── requirements.txt # Python dependencies├── .env # Environment variables (create this)├── Dockerfile # Docker configuration└── README.md # Project documentation```---**Happy coding! 🌸**
123456789101112You are a friendly and professional Customer Service for Human Resource Information System (HRIS) field,representative, fluent in Indonesian. Your job is to assist customers with accurate information based on your company's basic knowledge. Follow these guidelines:- Always greet customers in a friendly and professional manner.- Your answers are contextual and objective.- Provide clear, easy-to-understand, and structured answers based on the context provided by the user.- If information is not available, offer alternative assistance or direct them to the appropriate channel.- Use polite language and empathize with the customer's needs.- Conclude by offering further assistance.- You are highly skilled in the area relevant to the given context.Please use the given context to answer accurately.123456789101112Anda adalah seorang Customer Service yang ramah dan profesional di bidang Human Resource Information System (HRIS),fasih berbahasa Indonesia. Tugas Anda adalah membantu pelanggan dengan informasi yang akurat berdasarkan pengetahuan dasar perusahaan Anda. Ikuti panduan berikut:- Selalu menyapa pelanggan dengan ramah dan profesional.- Jawaban Anda kontekstual dan objektif.- Berikan jawaban yang jelas, mudah dipahami, dan terstruktur berdasarkan konteks yang diberikan oleh pengguna.- Jika informasi tidak tersedia, tawarkan bantuan alternatif atau arahkan mereka ke saluran yang tepat.- Gunakan bahasa yang sopan dan berempati terhadap kebutuhan pelanggan.- Akhiri dengan menawarkan bantuan lebih lanjut.- Anda sangat terampil di bidang yang relevan dengan konteks yang diberikan.Harap gunakan konteks yang diberikan untuk menjawab dengan akurat.
1234567891016 unmodified lines272829303132import argparsefrom src.provider import AppProviderapp = AppProvider()chatbot_ui = app.provide_chatbot().provide_chatbot_ui()rtc = app.provide_rtc()rtc_handler = rtc.provide_rtc_handler()parser = argparse.ArgumentParser()parser.add_argument("--mode", choices=[16 unmodified lineselif(args.mode == "rtc-ui"):print("launching RTC UI Mode ... ")rtc_handler.launch_ui(port = int(args.port))else:print("ERROR : INVALID ARGUMENT | PLEASE CHOOSE ONE BETWEEN chatbot/rtc-server/rtc-ui mode ")123456789101112131416 unmodified lines3132333435363738394041import argparsefrom src.provider import AppProviderfrom src.config import OPENAI_API_KEYfrom openai import OpenAIopenai_client = OpenAI(api_key = OPENAI_API_KEY)app = AppProvider(openai_client)chatbot_ui = app.provide_chatbot().provide_chatbot_ui()rtc = app.provide_rtc()rtc_handler = rtc.provide_rtc_handler()rtc_gpt_handler = rtc.provide_rtc_gpt_handler()parser = argparse.ArgumentParser()parser.add_argument("--mode", choices=[16 unmodified lineselif(args.mode == "rtc-ui"):print("launching RTC UI Mode ... ")rtc_handler.launch_ui(port = int(args.port))elif(args.mode == "rtc-gpt-ui"):print("RTC GPT UI mode ...")rtc_gpt_handler.launch_ui(port = int(args.port))elif(args.mode == "rtc-gpt-server"):rtc_gpt_handler.start_server(port = int(args.port))else:print("ERROR : INVALID ARGUMENT | PLEASE CHOOSE ONE BETWEEN chatbot / rtc-server/ rtc-ui / rtc-gpt-server / rtc-gpt-ui mode ")
24 unmodified lines25262728293031323334353624 unmodified lines4. **TO LAUNCH THE API ENDPOINT (SERVER)** Run the command below :```cd apppython main.py --mode rtc-server --port {your_port}```5. **TO LAUNCH THE CHATBOT UI** Run the command below :```cd apppython main.py --mode chatbot --port {your_port}```24 unmodified lines2526272829303132333424 unmodified lines4. **TO LAUNCH THE API ENDPOINT (SERVER)** Run the command below :```python main.py --mode rtc-server --port {your_port}```5. **TO LAUNCH THE CHATBOT UI** Run the command below :```python main.py --mode chatbot --port {your_port}```
28 unmodified lines2930313233343528 unmodified linespython main.py --mode rtc-server --port {your_port}```54. **TO LAUNCH THE CHATBOT UI** Run the command below :```cd apppython main.py --mode chatbot --port {your_port}28 unmodified lines2930313233343528 unmodified linespython main.py --mode rtc-server --port {your_port}```5. **TO LAUNCH THE CHATBOT UI** Run the command below :```cd apppython main.py --mode chatbot --port {your_port}
19 unmodified lines20212223242526272829303119 unmodified lines3. **TO LAUNCH THE GRADIO UI** Run the command below :```cd apppython __test__.py```4. **TO LAUNCH THE API ENDPOINT (SERVER)** Run the command below :```cd apppython __server__.py```19 unmodified lines202122232425262728293031323334353619 unmodified lines3. **TO LAUNCH THE GRADIO UI** Run the command below :```python main.py --mode rtc-ui --port {your_port}```4. **TO LAUNCH THE API ENDPOINT (SERVER)** Run the command below :```cd apppython main.py --mode rtc-server --port {your_port}```54. **TO LAUNCH THE CHATBOT UI** Run the command below :```cd apppython main.py --mode chatbot --port {your_port}```
123456789101112You are a friendly and professional Customer Service for Human Resource Information System (HRIS) field,representative, fluent in Indonesian. Your job is to assist customers with accurate information based on your company's basic knowledge. Follow these guidelines:
- Always greet customers in a friendly and professional manner.- Your answers are contextual and objective.- Provide clear, easy-to-understand, and structured answers based on the context provided by the user.- If information is not available, offer alternative assistance or direct them to the appropriate channel.- Use polite language and empathize with the customer's needs.- Conclude by offering further assistance.- You are highly skilled in the area relevant to the given context.
Please use the given context to answer accurately.1234567891011121314151617181920212223242526272829303132333435Anda adalah agen AI yang tepat dan objektif, Anda bertugas mengubah pertanyaan atau pernyataan pengguna menjadi query yang eksplisit dan efisien untuk keperluan pencarian dokumen dalam sistem RAG (Retrieval-Augmented Generation).
Ikuti langkah-langkah berikut:
1. Ekstrak bagian-bagian penting dari input pengguna: - **Intent**: Tujuan utama atau jenis permintaan (misalnya: apa itu, cara, syarat, apakah bisa, berapa). - **Entity/Noun Phrase**: Objek utama yang dibahas (misalnya: BPJS, tokenizer truncation, RWKV, gaji). - **Context**: Informasi pendukung yang menyempitkan fokus (misalnya: kecelakaan kerja, gaji 1 juta per bulan, perusahaan mitra BPJS). - **Question**: Pertanyaan spesifik yang ingin dijawab (misalnya: bagaimana prosesnya, apa manfaatnya, berapa jumlahnya).
2. Setelah semua elemen diidentifikasi, bentuk **Query RAG** dengan struktur: [INTENT] + [ENTITY] + [CONTEXT] + [QUESTION]3. Gunakan bahasa natural yang ringkas, namun informatif dan eksplisit.4. Generate hanya hasil akhirnya saja berupa satu buah kalimat
Contoh 0 :User Input:> Apa itu BPJSOutput : Pengertian BPJS
Contoh 1 :User Input:> Di mana lokasi PT Sakura System Solution ?
Output: Lokasi PT Sakura System Solution
Contoh 2:User Input:> Saya mengalami kecelakaan di kantor dan ingin tahu apakah bisa klaim BPJS karena perusahaan saya adalah mitra.
Output: apakah bisa klaim BPJS kecelakaan kerja di kantor jika perusahaan mitra dan apakah saya memenuhi syarat
**Tugas Anda sekarang:**Lakukan proses di atas untuk setiap input pengguna yang diberikan. Hasilkan query RAG akhir yang siap digunakan dalam pencarian dokumen.1234567891011121314151617181920212223242526272829303132import argparsefrom src.provider import AppProvider
app = AppProvider()chatbot_ui = app.provide_chatbot().provide_chatbot_ui()rtc = app.provide_rtc()rtc_handler = rtc.provide_rtc_handler()
parser = argparse.ArgumentParser()parser.add_argument("--mode", choices=[ "rtc-server", "rtc-ui", "rtc-gpt-server", "rtc-gpt-ui", "chatbot", ], required=True)
parser.add_argument("--port", default=7861, required=True)args = parser.parse_args()
if(args.mode == "chatbot"): print("Launching Chabot UI :))))))") chatbot_ui.launch(port = int(args.port))elif(args.mode == "rtc-server"): print("launching RTC Server Mode ... ") rtc_handler.start_server(port = int(args.port))elif(args.mode == "rtc-ui"): print("launching RTC UI Mode ... ") rtc_handler.launch_ui(port = int(args.port))else: print("ERROR : INVALID ARGUMENT | PLEASE CHOOSE ONE BETWEEN chatbot/rtc-server/rtc-ui mode ")
5 unmodified lines6789101112135 unmodified linesimport asynciodef run_test():try:# await test_document_retriever()# await test_language_model()test_inference()except Exception as e:print(e)5 unmodified lines678910115 unmodified linesimport asynciodef run_test():try:test_inference()except Exception as e:print(e)
28 unmodified lines2930313233343528 unmodified linesconfig = LMConfig(model_name = "Qwen/Qwen2.5-1.5B-Instruct",temperature=0.3,max_length=512,generation_timeout=100,28 unmodified lines2930313233343528 unmodified linesconfig = LMConfig(model_name = "meta-llama/Llama-3.1-8B",temperature=0.3,max_length=512,generation_timeout=100,
25 unmodified lines262728293031323334353637383940414222 unmodified lines65666768697071727374756 unmodified lines828384858687884 unmodified lines939495969798995 unmodified lines10510610710810911011138 unmodified lines15015115215315415515653 unmodified lines21021121221321421521611 unmodified lines2282292302312322332346 unmodified lines2412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772784 unmodified lines2832842852862872882892902912922932942952962 unmodified lines29930030130230330430530630730830931031131231331431531631731831932032132232332432532632720 unmodified lines3483493503513523533543 unmodified lines3583593603613623633643653663673683693703718 unmodified lines38038138238338438538638738838939010 unmodified lines40140240340440540640740840941041141241341441541641741841942042142242342442521 unmodified lines44744844945045145245345445545623 unmodified lines4804814824834844854865 unmodified lines49249349449549649749826 unmodified lines5255265275285295305315325335345355365375383 unmodified lines54254354454554654754830 unmodified lines5795805815825835845853 unmodified lines58959059159259359459543 unmodified lines63964064164264364464564664764824 unmodified lines67367467567667767867968068168268368468568631 unmodified lines7187197207217227237247257267277287297307318 unmodified lines7407417427437447457465 unmodified lines75275375475575675775875976076176276376476576676776876977077177223 unmodified lines7967977987998008018025 unmodified lines80880981081181281381419 unmodified lines83483583683783883984021 unmodified lines86286386486586686786825 unmodified lines8948958968978988999001 unmodified line90290390490590690790890991091110 unmodified lines92292392492592692792892993093125 unmodified linesquantization_config: any = Nonepad_token_id: Optional[int] = Noneeos_token_id: Optional[int] = None# RAG-specific configsmax_context_length: int = 1500context_separator: str = "\n---\n"instruction_template: str = "system" # "system", "instruction", "custom"# Async-specific configsmax_workers: int = 2generation_timeout: float = 30repetition_penalty: float = 1.0# Streaming-specific configsstream_timeout: float = 100 # timeout untuk stream chunkskip_prompt: bool = True # skip prompt dari streaming outputclass LM:"""22 unmodified linesself.is_loaded = Falseself.executor = ThreadPoolExecutor(max_workers=self.config.max_workers)self._lock = asyncio.Lock()# Setup logginglogging.basicConfig(level=logging.INFO)self.logger = logging.getLogger(__name__)# RAG prompt templatesself.prompt_template = prompt_templateasync def load_model(self) -> None:6 unmodified linestry:self.logger.info(f"Loading model: {self.config.model_name}")# Load tokenizer dalam thread poolself.tokenizer = await asyncio.get_event_loop().run_in_executor(self.executor,lambda: AutoTokenizer.from_pretrained(4 unmodified lines))# Load model dalam thread poolself.model = await asyncio.get_event_loop().run_in_executor(self.executor,lambda: AutoModelForCausalLM.from_pretrained(5 unmodified lines))# Setup generation configself.generation_config = GenerationConfig(max_length=self.config.max_length,temperature=self.config.temperature,38 unmodified linesreturn f"Template '{template_type}' tidak tersedia. Available: {self.get_available_templates()}"template_data = copy.deepcopy(self.prompt_template)# template_key = "user_template" if "user_template" in template_data else "template"return template_data["content"].format(context=sample_context,53 unmodified linesif len(context) <= max_length:return context# Truncate dan tambahkan indicatortruncated = context[:max_length - 50]return truncated + "\n\n[... Context dipotong karena terlalu panjang ...]"11 unmodified linesdef _format_sync():# Handle RetrievalResult secara eksplisitif isinstance(contexts, RetrievalResult):docs = contexts.documentsif max_contexts:6 unmodified linesmetadata=contexts.metadata)else:# contexts diasumsikan sebagai list biasa (list[str] atau list[Document])processed_contexts = contexts[:max_contexts] if max_contexts and len(contexts) > max_contexts else contexts# Format context menjadi stringformatted_context = self._format_context(processed_contexts, context_numbering)# Truncate jika panjang melebihi batasformatted_context = self._truncate_context(formatted_context,self.config.max_context_length)# Tambah metadata jika diizinkan dan konteks adalah RetrievalResultif include_metadata and isinstance(processed_contexts, RetrievalResult):metadata_info = []for i, doc in enumerate(processed_contexts.documents, 1):if hasattr(doc, "metadata") and doc.metadata:metadata_info.append(f"Dokumen {i}: {doc.metadata}")# if metadata_info:# formatted_context += f"\n\n[Metadata]\n" + "\n".join(metadata_info)return formatted_context# Jalankan _format_sync di thread poolformatted_context = await asyncio.get_event_loop().run_in_executor(self.executor, _format_sync)self.logger.info(f"Formatted Context {formatted_context}")# Tentukan template yang akan dipakaiif(template_type == ""):self.config.instruction_template = "system"# Gunakan custom template jika disediakanif custom_template:return custom_template.format(context=formatted_context,4 unmodified linestemplate_data = copy.deepcopy(self.prompt_template)print("template = ", template_type, "rag template = ", template_data)# template_key = "user_template" if "user_template" in template_data else "template"formatted_template = []for cht in template_data:# Create a copy of the content to avoid modifying the originalcontent = cht["content"]# Format both placeholders at once to avoid KeyErrorif "{context}" in content or "{question}" in content:try:content = content.format(2 unmodified lines)except KeyError as e:self.logger.error(f"Missing placeholder in template: {e}")# Fallback: format only available placeholdersif "{context}" in content:content = content.replace("{context}", formatted_context)if "{question}" in content:content = content.replace("{question}", question)# Create new dict with formatted contentformatted_chat = {"role": cht["role"],"content": content}# Copy other fields if they existif "description" in cht:formatted_chat["description"] = cht["description"]formatted_template.append(formatted_chat)# self.logger.info(f"Formatted Template {formatted_template}")# print("Forrmatted Template", formatted_template)return formatted_templateelse:# Fallback default templatereturn [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": question}20 unmodified lines"""await self._check_model_loaded()# Setup streamerstreamer = TextIteratorStreamer(self.tokenizer,timeout=self.config.stream_timeout,3 unmodified linesdef _generate_sync():try:# Tokenize inputinputs = self.tokenizer.apply_chat_template(prompt,add_generation_prompt=True,return_tensors="pt")# Override generation config jika diperlukangen_config = self.generation_configif any([max_new_tokens, temperature, top_p]):gen_config = GenerationConfig(8 unmodified lines**kwargs)# Move to GPUself.model.to("cuda")input_ids = inputs.to("cuda")# Generate dalam thread terpisahgeneration_kwargs = {"input_ids": input_ids,"generation_config": gen_config,10 unmodified linesself.logger.error(f"Error during stream generation setup: {e}")raise# Setup generation threadgeneration_thread = await asyncio.get_event_loop().run_in_executor(self.executor, _generate_sync)err = Nonetry:# Stream tokensfor token in streamer:if token: # Skip empty tokensyield token# Wait for generation thread to finisherr = await asyncio.get_event_loop().run_in_executor(self.executor, generation_thread.join)except Exception as e:self.logger.error(f"Error during streaming: {e}, {err}")# Make sure thread is cleaned upif generation_thread.is_alive():generation_thread.join(timeout=1.0)raise21 unmodified lines"""await self._check_model_loaded()# Format promptprompt = await self.format_rag_prompt(question, contexts, template_type)# Generate dengan temperature yang lebih rendah untuk RAG (lebih faktual)temp = temperature if temperature is not None else 0.3async for chunk in self.generate_stream(23 unmodified linesdef _format_chat():try:# Format messages untuk chatformatted_prompt = self.tokenizer.apply_chat_template(messages,tokenize=False,5 unmodified linesself.logger.error(f"Error during chat formatting: {e}")raise# Format chat template dalam thread poolformatted_prompt = await asyncio.get_event_loop().run_in_executor(self.executor, _format_chat)26 unmodified lines"""await self._check_model_loaded()# Ambil last user message sebagai questionuser_messages = [msg for msg in messages if msg.get("role") == "user"]if not user_messages:raise ValueError("No user message found in conversation")last_question = user_messages[-1]["content"]# Generate RAG response secara streamingasync for chunk in self.rag_generate_stream(question=last_question,contexts=contexts,3 unmodified lines):yield chunk# Utility method untuk collect full response dari streamasync def collect_stream(self, stream_generator: AsyncGenerator[str, None]) -> str:"""Collect semua chunks dari stream generator menjadi full text30 unmodified lines"""await self._check_model_loaded()# Create tasks untuk concurrent generationtasks = []for template_type in template_types:task = asyncio.create_task(3 unmodified lines)tasks.append((template_type, task))# Wait for all tasksresults = {}for template_type, task in tasks:try:43 unmodified lines"""await self._check_model_loaded()# Format promptprompt = await self.format_rag_prompt(question, contexts, template_type)# Generate dengan temperature yang lebih rendah untuk RAG (lebih faktual)temp = temperature if temperature is not None else 0.3return await self.generate(24 unmodified lines"""await self._check_model_loaded()# Ambil last user message sebagai questionuser_messages = [msg for msg in messages if msg.get("role") == "user"]if not user_messages:raise ValueError("No user message found in conversation")last_question = user_messages[-1]["content"]# Generate RAG responsereturn await self.rag_generate(question=last_question,contexts=contexts,31 unmodified linesdef _generate_sync():try:# Tokenize inputinputs = self.tokenizer.apply_chat_template(prompt,add_generation_prompt=True,return_tensors="pt")# Override generation config jika diperlukangen_config = self.generation_configif any([max_new_tokens, temperature, top_p]):gen_config = GenerationConfig(8 unmodified lines**kwargs)# Generatewith torch.no_grad():self.model.to("cuda")5 unmodified lines**kwargs)# Decode outputgenerated_text = self.tokenizer.decode(outputs[0][prompt_length:],skip_special_tokens=True)print("Generated Text", generated_text)# Remove input prompt dari outputreturn generated_textexcept Exception as e:self.logger.error(f"Error during generation: {e}")raise# Run generation in thread pool dengan timeouttry:result = await asyncio.wait_for(asyncio.get_event_loop().run_in_executor(self.executor, _generate_sync),23 unmodified linesdef _format_chat():try:# Format messages untuk chatformatted_prompt = self.tokenizer.apply_chat_template(messages,chat_template="rag",5 unmodified linesself.logger.error(f"Error during chat formatting: {e}")raise# Format chat template dalam thread poolformatted_prompt = await asyncio.get_event_loop().run_in_executor(self.executor, _format_chat)19 unmodified lineselse:self.logger.warning(f"Unknown config parameter: {key}")# Update generation config jika model sudah loadedif self.is_loaded:self.generation_config = GenerationConfig(max_length=self.config.max_length,21 unmodified lines}if self.is_loaded:# Get model info dalam thread pooldef _get_info():return {"vocab_size": self.tokenizer.vocab_size,25 unmodified lines"""await self._check_model_loaded()# Create tasks untuk concurrent generationtasks = [asyncio.create_task(self.generate(prompt, max_new_tokens=max_new_tokens, **kwargs)1 unmodified linefor prompt in prompts]# Wait for all tasksresults = await asyncio.gather(*tasks, return_exceptions=True)# Process resultsprocessed_results = []for i, result in enumerate(results):if isinstance(result, Exception):10 unmodified lines"""self.logger.info("Closing LM...")# Shutdown executorself.executor.shutdown(wait=True)# Clear GPU memoryif hasattr(self, 'model') and self.model is not None:del self.modelif hasattr(self, 'tokenizer') and self.tokenizer is not None:25 unmodified lines262728293031323334353637383940414222 unmodified lines65666768697071727374756 unmodified lines828384858687884 unmodified lines939495969798995 unmodified lines10510610710810911011138 unmodified lines15015115215315415515653 unmodified lines21021121221321421521611 unmodified lines2282292302312322332346 unmodified lines2412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772784 unmodified lines2832842852862872882892902912922932942952962 unmodified lines29930030130230330430530630730830931031131231331431531631731831932032132232332432532632720 unmodified lines3483493503513523533543 unmodified lines3583593603613623633643653663673683693703718 unmodified lines38038138238338438538638738838939010 unmodified lines40140240340440540640740840941041141241341441541641741841942042142242342442521 unmodified lines44744844945045145245345445545623 unmodified lines4804814824834844854865 unmodified lines49249349449549649749826 unmodified lines5255265275285295305315325335345355365375383 unmodified lines54254354454554654754830 unmodified lines5795805815825835845853 unmodified lines58959059159259359459543 unmodified lines63964064164264364464564664764824 unmodified lines67367467567667767867968068168268368468568631 unmodified lines7187197207217227237247257267277287297307318 unmodified lines7407417427437447457465 unmodified lines75275375475575675775875976076176276376476576676776876977077177223 unmodified lines7967977987998008018025 unmodified lines80880981081181281381419 unmodified lines83483583683783883984021 unmodified lines86286386486586686786825 unmodified lines8948958968978988999001 unmodified line90290390490590690790890991091110 unmodified lines92292392492592692792892993093125 unmodified linesquantization_config: any = Nonepad_token_id: Optional[int] = Noneeos_token_id: Optional[int] = Nonemax_context_length: int = 1500context_separator: str = "\n---\n"instruction_template: str = "system"max_workers: int = 2generation_timeout: float = 30repetition_penalty: float = 1.0stream_timeout: float = 100skip_prompt: bool = Trueclass LM:"""22 unmodified linesself.is_loaded = Falseself.executor = ThreadPoolExecutor(max_workers=self.config.max_workers)self._lock = asyncio.Lock()logging.basicConfig(level=logging.INFO)self.logger = logging.getLogger(__name__)self.prompt_template = prompt_templateasync def load_model(self) -> None:6 unmodified linestry:self.logger.info(f"Loading model: {self.config.model_name}")self.tokenizer = await asyncio.get_event_loop().run_in_executor(self.executor,lambda: AutoTokenizer.from_pretrained(4 unmodified lines))self.model = await asyncio.get_event_loop().run_in_executor(self.executor,lambda: AutoModelForCausalLM.from_pretrained(5 unmodified lines))self.generation_config = GenerationConfig(max_length=self.config.max_length,temperature=self.config.temperature,38 unmodified linesreturn f"Template '{template_type}' tidak tersedia. Available: {self.get_available_templates()}"template_data = copy.deepcopy(self.prompt_template)return template_data["content"].format(context=sample_context,53 unmodified linesif len(context) <= max_length:return contexttruncated = context[:max_length - 50]return truncated + "\n\n[... Context dipotong karena terlalu panjang ...]"11 unmodified linesdef _format_sync():if isinstance(contexts, RetrievalResult):docs = contexts.documentsif max_contexts:6 unmodified linesmetadata=contexts.metadata)else:processed_contexts = contexts[:max_contexts] if max_contexts and len(contexts) > max_contexts else contextsformatted_context = self._format_context(processed_contexts, context_numbering)formatted_context = self._truncate_context(formatted_context,self.config.max_context_length)if include_metadata and isinstance(processed_contexts, RetrievalResult):metadata_info = []for i, doc in enumerate(processed_contexts.documents, 1):if hasattr(doc, "metadata") and doc.metadata:metadata_info.append(f"Dokumen {i}: {doc.metadata}")return formatted_contextformatted_context = await asyncio.get_event_loop().run_in_executor(self.executor, _format_sync)self.logger.info(f"Formatted Context {formatted_context}")if(template_type == ""):self.config.instruction_template = "system"if custom_template:return custom_template.format(context=formatted_context,4 unmodified linestemplate_data = copy.deepcopy(self.prompt_template)print("template = ", template_type, "rag template = ", template_data)formatted_template = []for cht in template_data:content = cht["content"]if "{context}" in content or "{question}" in content:try:content = content.format(2 unmodified lines)except KeyError as e:self.logger.error(f"Missing placeholder in template: {e}")if "{context}" in content:content = content.replace("{context}", formatted_context)if "{question}" in content:content = content.replace("{question}", question)formatted_chat = {"role": cht["role"],"content": content}if "description" in cht:formatted_chat["description"] = cht["description"]formatted_template.append(formatted_chat)return formatted_templateelse:return [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": question}20 unmodified lines"""await self._check_model_loaded()streamer = TextIteratorStreamer(self.tokenizer,timeout=self.config.stream_timeout,3 unmodified linesdef _generate_sync():try:inputs = self.tokenizer.apply_chat_template(prompt,add_generation_prompt=True,return_tensors="pt")gen_config = self.generation_configif any([max_new_tokens, temperature, top_p]):gen_config = GenerationConfig(8 unmodified lines**kwargs)self.model.to("cuda")input_ids = inputs.to("cuda")generation_kwargs = {"input_ids": input_ids,"generation_config": gen_config,10 unmodified linesself.logger.error(f"Error during stream generation setup: {e}")raisegeneration_thread = await asyncio.get_event_loop().run_in_executor(self.executor, _generate_sync)err = Nonetry:for token in streamer:if token:yield tokenerr = await asyncio.get_event_loop().run_in_executor(self.executor, generation_thread.join)except Exception as e:self.logger.error(f"Error during streaming: {e}, {err}")if generation_thread.is_alive():generation_thread.join(timeout=1.0)raise21 unmodified lines"""await self._check_model_loaded()prompt = await self.format_rag_prompt(question, contexts, template_type)temp = temperature if temperature is not None else 0.3async for chunk in self.generate_stream(23 unmodified linesdef _format_chat():try:formatted_prompt = self.tokenizer.apply_chat_template(messages,tokenize=False,5 unmodified linesself.logger.error(f"Error during chat formatting: {e}")raiseformatted_prompt = await asyncio.get_event_loop().run_in_executor(self.executor, _format_chat)26 unmodified lines"""await self._check_model_loaded()user_messages = [msg for msg in messages if msg.get("role") == "user"]if not user_messages:raise ValueError("No user message found in conversation")last_question = user_messages[-1]["content"]async for chunk in self.rag_generate_stream(question=last_question,contexts=contexts,3 unmodified lines):yield chunkasync def collect_stream(self, stream_generator: AsyncGenerator[str, None]) -> str:"""Collect semua chunks dari stream generator menjadi full text30 unmodified lines"""await self._check_model_loaded()tasks = []for template_type in template_types:task = asyncio.create_task(3 unmodified lines)tasks.append((template_type, task))results = {}for template_type, task in tasks:try:43 unmodified lines"""await self._check_model_loaded()prompt = await self.format_rag_prompt(question, contexts, template_type)temp = temperature if temperature is not None else 0.3return await self.generate(24 unmodified lines"""await self._check_model_loaded()user_messages = [msg for msg in messages if msg.get("role") == "user"]if not user_messages:raise ValueError("No user message found in conversation")last_question = user_messages[-1]["content"]return await self.rag_generate(question=last_question,contexts=contexts,31 unmodified linesdef _generate_sync():try:inputs = self.tokenizer.apply_chat_template(prompt,add_generation_prompt=True,return_tensors="pt")gen_config = self.generation_configif any([max_new_tokens, temperature, top_p]):gen_config = GenerationConfig(8 unmodified lines**kwargs)with torch.no_grad():self.model.to("cuda")5 unmodified lines**kwargs)generated_text = self.tokenizer.decode(outputs[0][prompt_length:],skip_special_tokens=True)print("Generated Text", generated_text)return generated_textexcept Exception as e:self.logger.error(f"Error during generation: {e}")raisetry:result = await asyncio.wait_for(asyncio.get_event_loop().run_in_executor(self.executor, _generate_sync),23 unmodified linesdef _format_chat():try:formatted_prompt = self.tokenizer.apply_chat_template(messages,chat_template="rag",5 unmodified linesself.logger.error(f"Error during chat formatting: {e}")raiseformatted_prompt = await asyncio.get_event_loop().run_in_executor(self.executor, _format_chat)19 unmodified lineselse:self.logger.warning(f"Unknown config parameter: {key}")if self.is_loaded:self.generation_config = GenerationConfig(max_length=self.config.max_length,21 unmodified lines}if self.is_loaded:def _get_info():return {"vocab_size": self.tokenizer.vocab_size,25 unmodified lines"""await self._check_model_loaded()tasks = [asyncio.create_task(self.generate(prompt, max_new_tokens=max_new_tokens, **kwargs)1 unmodified linefor prompt in prompts]results = await asyncio.gather(*tasks, return_exceptions=True)processed_results = []for i, result in enumerate(results):if isinstance(result, Exception):10 unmodified lines"""self.logger.info("Closing LM...")self.executor.shutdown(wait=True)if hasattr(self, 'model') and self.model is not None:del self.modelif hasattr(self, 'tokenizer') and self.tokenizer is not None:
5 unmodified lines67891011122 unmodified lines15161718192021222324252627282930313233343536373839404142434445464748495010 unmodified lines616263646566676869707172737475767720 unmodified lines98991001011021031041051061071081091101111121131141158 unmodified lines12412512612712812913023 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761 unmodified line17817918018118218318418518618718818913 unmodified lines20320420520620720820919 unmodified lines22923023123223323423523623723823924024118 unmodified lines2602612622632642652662672682692702712722732742752762772782792802812822836 unmodified lines2902912922932942952964 unmodified lines30130230330430530630712 unmodified lines3203213223233243253267 unmodified lines33433533633733833934042 unmodified lines3833843853863873883892 unmodified lines3923933943953963973987 unmodified lines4064074084094104114124134142 unmodified lines4174184194204214224234244254264274284294308 unmodified lines4394404414424434444451 unmodified line4474484494504514524531 unmodified line4554564574584594604611 unmodified line46346446546646746846910 unmodified lines48048148248348448548613 unmodified lines50050150250350450550650750850951011 unmodified lines52252352452552652752852953053153253353453553653719 unmodified lines55755855956056156256325 unmodified lines58959059159259359459510 unmodified lines60660760860961061161224 unmodified lines6376386396406416426436446456466476485 unmodified lines65465565665765865966038 unmodified lines69970070170270370470570670733 unmodified lines7417427437447457467477487497507517522 unmodified lines7557567577587597607617627637647657667677687697707717727737747755 unmodified linesfrom datetime import datetimeimport hashlib# Import types yang sudah adafrom typing import List, Dict, Any, Optional, Unionfrom dataclasses import dataclassfrom enum import Enum2 unmodified lines@dataclassclass PreprocessingConfig:"""Konfigurasi untuk preprocessing"""# Text cleaning optionsremove_extra_whitespace: bool = Trueremove_special_chars: bool = Falsenormalize_unicode: bool = Trueremove_urls: bool = Falseremove_emails: bool = False# Chunking optionsenable_chunking: bool = False # Apakah perlu chunking lagichunk_size: int = 500chunk_overlap: int = 50chunk_method: str = "sentence" # "sentence", "paragraph", "fixed"# Content filteringmin_content_length: int = 20max_content_length: int = 3000filter_empty_content: bool = Truefilter_duplicate_content: bool = True# Metadata optionsextract_metadata: bool = Trueinclude_retrieval_info: bool = Trueinclude_document_info: bool = Trueinclude_timestamps: bool = True# Scoring optionsuse_retrieval_scores: bool = True # Use scores dari retrieval systemnormalize_scores: bool = True # Normalize scores ke range 0-1min_score_threshold: float = 0.0 # Filter berdasarkan minimum scorescore_boost_factor: float = 1.0 # Boost factor untuk scoresclass RetrievalPreprocessor:"""10 unmodified lines"""self.config = config or PreprocessingConfig()# Setup logginglogging.basicConfig(level=logging.INFO)self.logger = logging.getLogger(__name__)# Regex patterns untuk cleaningself.url_pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')self.email_pattern = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b')self.special_chars_pattern = re.compile(r'[^\w\s\.\,\!\?\;\:\-\(\)\[\]\{\}\"\'\/]')self.whitespace_pattern = re.compile(r'\s+')# Cache untuk duplicate detectionself._seen_content_hashes = set()def process_retrieval_result(self, retrieval_result: RetrievalResult) -> List[RetrievalResult]:20 unmodified linesf"Processing {len(retrieval_result.documents)} documents from retrieval result for query: '{retrieval_result.query}'")# Clear cache untuk setiap batch baruself._seen_content_hashes.clear()contexts = []# Process setiap documentfor i, doc in enumerate(retrieval_result.documents):try:# Get corresponding scorescore = retrieval_result.scores[i] if i < len(retrieval_result.scores) else 0.0# Process single documentprocessed_contexts = self._process_single_document(document=doc,retrieval_score=score,8 unmodified linesself.logger.error(f"Error processing document {i}: {e}")continue# Post-processingcontexts = self._post_process_contexts(contexts)self.logger.info(f"Successfully processed {len(contexts)} contexts from retrieval result")23 unmodified linesself.logger.warning(f"Empty content in document {document_index}")return []# Clean contentcleaned_content = self._clean_text(document.page_content)if not cleaned_content:return []# Filter by lengthif len(cleaned_content) < self.config.min_content_length:self.logger.debug(f"Content too short in document {document_index}: {len(cleaned_content)} chars")return []if len(cleaned_content) > self.config.max_content_length:# Truncate contentcleaned_content = self._truncate_content(cleaned_content)self.logger.debug(f"Content truncated in document {document_index}")# Check for duplicatesif self.config.filter_duplicate_content:content_hash = hashlib.md5(cleaned_content.encode()).hexdigest()if content_hash in self._seen_content_hashes:1 unmodified linereturn []self._seen_content_hashes.add(content_hash)# Filter by score thresholdif self.config.use_retrieval_scores and retrieval_score < self.config.min_score_threshold:self.logger.debug(f"Score too low in document {document_index}: {retrieval_score}")return []# Chunking (if enabled)if self.config.enable_chunking:chunks = self._chunk_content(cleaned_content)contexts = []13 unmodified linesreturn contextselse:# Single context per documentcontext = self._create_retrieved_context(content=cleaned_content,document=document,19 unmodified lines"""Create RetrievalResult object"""# Process scorefinal_score = self._process_score(retrieval_score, document_index, total_documents)# Extract sourcesource = self._extract_source(document)# Build metadatametadata = self._build_metadata(document=document,retrieval_result=retrieval_result,18 unmodified linescleaned = text# Normalize unicodeif self.config.normalize_unicode:import unicodedatacleaned = unicodedata.normalize('NFKC', cleaned)# Remove URLsif self.config.remove_urls:cleaned = self.url_pattern.sub('', cleaned)# Remove emailsif self.config.remove_emails:cleaned = self.email_pattern.sub('', cleaned)# Remove special charactersif self.config.remove_special_chars:cleaned = self.special_chars_pattern.sub(' ', cleaned)# Remove extra whitespaceif self.config.remove_extra_whitespace:cleaned = self.whitespace_pattern.sub(' ', cleaned)6 unmodified linesif len(content) <= max_length:return content# Try to cut at sentence boundarytruncated = content[:max_length - 20]last_sentence_end = max(truncated.rfind('.'),4 unmodified linesif last_sentence_end > len(truncated) * 0.7:return truncated[:last_sentence_end + 1]else:# Cut at word boundarylast_space = truncated.rfind(' ')if last_space > len(truncated) * 0.8:return truncated[:last_space] + "..."12 unmodified lineselif self.config.chunk_method == "fixed":return self._chunk_by_fixed_size(content)else:return [content] # No chunkingdef _chunk_by_sentence(self, text: str) -> List[str]:"""Chunk by sentences"""7 unmodified linesif len(current_chunk) + len(sentence) > self.config.chunk_size and current_chunk:chunks.append(current_chunk.strip())# Handle overlapif self.config.chunk_overlap > 0:overlap_text = current_chunk[-self.config.chunk_overlap:]current_chunk = overlap_text + " " + sentence42 unmodified linesend = start + self.config.chunk_sizechunk = text[start:end]# Try to break at word boundaryif end < len(text):last_space = chunk.rfind(' ')if last_space > len(chunk) * 0.8:2 unmodified lineschunks.append(chunk.strip())# Move with overlapstart = end - self.config.chunk_overlapif start <= 0:start = end7 unmodified linesscore = retrieval_score * self.config.score_boost_factor# Normalize to 0-1 range jika diperlukanif self.config.normalize_scores:# Assume retrieval scores are already normalized, but ensure they are in rangescore = max(0.0, min(1.0, score))return round(score, 4)2 unmodified lines"""Extract source dari document metadata"""metadata = document.metadata or {}# Try different metadata keys for sourcesource_keys = ['source', 'file_name', 'filename', 'title', 'file_path', 'path']for key in source_keys:if key in metadata and metadata[key]:return str(metadata[key])# Fallback to generic sourcereturn "unknown_source"def _build_metadata(self,8 unmodified linesmetadata = {}if self.config.extract_metadata:# Include original document metadataif document.metadata and self.config.include_document_info:metadata.update({"original_metadata": document.metadata,1 unmodified line"total_documents": total_documents})# Include chunking infoif chunk_index is not None:metadata.update({"chunk_index": chunk_index,1 unmodified line"is_chunked": total_chunks > 1})# Include retrieval infoif self.config.include_retrieval_info:metadata.update({"retrieval_query": retrieval_result.query,1 unmodified line"retrieval_metadata": retrieval_result.metadata})# Include processing infoif self.config.include_timestamps:metadata.update({"processed_at": datetime.now().isoformat(),10 unmodified lines}})# Content statisticsword_count = len(content.split())sentence_count = len(re.split(r'[.!?]+', content))13 unmodified linesif not contexts:return contexts# Sort by score (descending)if self.config.use_retrieval_scores:contexts.sort(key=lambda x: x.score or 0.0, reverse=True)# Additional filtering jika diperlukanfiltered_contexts = []for ctx in contexts:if self.config.filter_empty_content and not ctx.content.strip():11 unmodified linestotal_words = sum(len(ctx.content.split()) for ctx in contexts)total_chars = sum(len(ctx.content) for ctx in contexts)# Score distributionscores = [ctx.score for ctx in contexts if ctx.score is not None]# Source distributionsources = {}for ctx in contexts:if ctx.source:sources[ctx.source] = sources.get(ctx.source, 0) + 1# Chunking statschunked_contexts = sum(1 for ctx in contextsif ctx.metadata and ctx.metadata.get("is_chunked", False))19 unmodified linesstats["source_distribution"] = sourcesstats["unique_sources"] = len(sources)# Content length distributionlengths = [len(ctx.content) for ctx in contexts]stats["content_length_stats"] = {"min_length": min(lengths),25 unmodified linestry:contexts = self.process_retrieval_result(result)# Add batch info to metadatafor ctx in contexts:if ctx.metadata:ctx.metadata["batch_index"] = i10 unmodified linesself.logger.error(f"Error processing retrieval result {i}: {e}")continue# Final post-processing untuk batchall_contexts = self._post_process_contexts(all_contexts)self.logger.info(f"Batch processing completed: {len(all_contexts)} total contexts")24 unmodified linesfor ctx in contexts:content_words = set(ctx.content.lower().split())# Simple relevance calculation: overlap of wordsoverlap = len(query_words.intersection(content_words))relevance_score = overlap / len(query_words) if query_words else 0.0if relevance_score >= min_relevance_score:# Update metadata dengan relevance infoif ctx.metadata:ctx.metadata["query_relevance_score"] = round(relevance_score, 3)ctx.metadata["matched_query_words"] = list(query_words.intersection(content_words))5 unmodified linesfiltered_contexts.append(ctx)# Sort by relevance scorefiltered_contexts.sort(key=lambda x: x.metadata.get("query_relevance_score", 0.0),reverse=True38 unmodified linesif sim_score >= similarity_threshold:is_duplicate = True# Keep the one with higher scoreif (ctx.score or 0.0) > (existing_ctx.score or 0.0):# Replace existing with currentidx = deduplicated.index(existing_ctx)deduplicated[idx] = ctx33 unmodified linesif not proc_result.chunks:continue# Convert Document chunks to RetrievalResultfor j, chunk in enumerate(proc_result.chunks):# Extract source dari document metadatasource = self._extract_source(chunk)# Build metadata from ProcessingResultmetadata = {"document_metadata": proc_result.document_metadata.__dict__,"chunk_index": j,2 unmodified lines"processed_at": datetime.now().isoformat()}# Include original chunk metadataif chunk.metadata:metadata["original_chunk_metadata"] = chunk.metadata# Clean contentcleaned_content = self._clean_text(chunk.page_content)if not cleaned_content or len(cleaned_content) < self.config.min_content_length:continue# Create RetrievalResultcontext = RetrievalResult(content=cleaned_content,source=source,score=1.0, # Default score for processing resultsmetadata=metadata)5 unmodified lines67891011122 unmodified lines15161718192021222324252627282930313233343536373839404142434445464748495010 unmodified lines616263646566676869707172737475767720 unmodified lines98991001011021031041051061071081091101111121131141158 unmodified lines12412512612712812913023 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761 unmodified line17817918018118218318418518618718818913 unmodified lines20320420520620720820919 unmodified lines22923023123223323423523623723823924024118 unmodified lines2602612622632642652662672682692702712722732742752762772782792802812822836 unmodified lines2902912922932942952964 unmodified lines30130230330430530630712 unmodified lines3203213223233243253267 unmodified lines33433533633733833934042 unmodified lines3833843853863873883892 unmodified lines3923933943953963973987 unmodified lines4064074084094104114124134142 unmodified lines4174184194204214224234244254264274284294308 unmodified lines4394404414424434444451 unmodified line4474484494504514524531 unmodified line4554564574584594604611 unmodified line46346446546646746846910 unmodified lines48048148248348448548613 unmodified lines50050150250350450550650750850951011 unmodified lines52252352452552652752852953053153253353453553653719 unmodified lines55755855956056156256325 unmodified lines58959059159259359459510 unmodified lines60660760860961061161224 unmodified lines6376386396406416426436446456466476485 unmodified lines65465565665765865966038 unmodified lines69970070170270370470570670733 unmodified lines7417427437447457467477487497507517522 unmodified lines7557567577587597607617627637647657667677687697707717727737747755 unmodified linesfrom datetime import datetimeimport hashlibfrom typing import List, Dict, Any, Optional, Unionfrom dataclasses import dataclassfrom enum import Enum2 unmodified lines@dataclassclass PreprocessingConfig:"""Konfigurasi untuk preprocessing"""remove_extra_whitespace: bool = Trueremove_special_chars: bool = Falsenormalize_unicode: bool = Trueremove_urls: bool = Falseremove_emails: bool = Falseenable_chunking: bool = Falsechunk_size: int = 500chunk_overlap: int = 50chunk_method: str = "sentence"min_content_length: int = 20max_content_length: int = 3000filter_empty_content: bool = Truefilter_duplicate_content: bool = Trueextract_metadata: bool = Trueinclude_retrieval_info: bool = Trueinclude_document_info: bool = Trueinclude_timestamps: bool = Trueuse_retrieval_scores: bool = Truenormalize_scores: bool = Truemin_score_threshold: float = 0.0score_boost_factor: float = 1.0class RetrievalPreprocessor:"""10 unmodified lines"""self.config = config or PreprocessingConfig()logging.basicConfig(level=logging.INFO)self.logger = logging.getLogger(__name__)self.url_pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')self.email_pattern = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b')self.special_chars_pattern = re.compile(r'[^\w\s\.\,\!\?\;\:\-\(\)\[\]\{\}\"\'\/]')self.whitespace_pattern = re.compile(r'\s+')self._seen_content_hashes = set()def process_retrieval_result(self, retrieval_result: RetrievalResult) -> List[RetrievalResult]:20 unmodified linesf"Processing {len(retrieval_result.documents)} documents from retrieval result for query: '{retrieval_result.query}'")self._seen_content_hashes.clear()contexts = []for i, doc in enumerate(retrieval_result.documents):try:score = retrieval_result.scores[i] if i < len(retrieval_result.scores) else 0.0processed_contexts = self._process_single_document(document=doc,retrieval_score=score,8 unmodified linesself.logger.error(f"Error processing document {i}: {e}")continuecontexts = self._post_process_contexts(contexts)self.logger.info(f"Successfully processed {len(contexts)} contexts from retrieval result")23 unmodified linesself.logger.warning(f"Empty content in document {document_index}")return []cleaned_content = self._clean_text(document.page_content)if not cleaned_content:return []if len(cleaned_content) < self.config.min_content_length:self.logger.debug(f"Content too short in document {document_index}: {len(cleaned_content)} chars")return []if len(cleaned_content) > self.config.max_content_length:cleaned_content = self._truncate_content(cleaned_content)self.logger.debug(f"Content truncated in document {document_index}")if self.config.filter_duplicate_content:content_hash = hashlib.md5(cleaned_content.encode()).hexdigest()if content_hash in self._seen_content_hashes:1 unmodified linereturn []self._seen_content_hashes.add(content_hash)if self.config.use_retrieval_scores and retrieval_score < self.config.min_score_threshold:self.logger.debug(f"Score too low in document {document_index}: {retrieval_score}")return []if self.config.enable_chunking:chunks = self._chunk_content(cleaned_content)contexts = []13 unmodified linesreturn contextselse:context = self._create_retrieved_context(content=cleaned_content,document=document,19 unmodified lines"""Create RetrievalResult object"""final_score = self._process_score(retrieval_score, document_index, total_documents)source = self._extract_source(document)metadata = self._build_metadata(document=document,retrieval_result=retrieval_result,18 unmodified linescleaned = textif self.config.normalize_unicode:import unicodedatacleaned = unicodedata.normalize('NFKC', cleaned)if self.config.remove_urls:cleaned = self.url_pattern.sub('', cleaned)if self.config.remove_emails:cleaned = self.email_pattern.sub('', cleaned)if self.config.remove_special_chars:cleaned = self.special_chars_pattern.sub(' ', cleaned)if self.config.remove_extra_whitespace:cleaned = self.whitespace_pattern.sub(' ', cleaned)6 unmodified linesif len(content) <= max_length:return contenttruncated = content[:max_length - 20]last_sentence_end = max(truncated.rfind('.'),4 unmodified linesif last_sentence_end > len(truncated) * 0.7:return truncated[:last_sentence_end + 1]else:last_space = truncated.rfind(' ')if last_space > len(truncated) * 0.8:return truncated[:last_space] + "..."12 unmodified lineselif self.config.chunk_method == "fixed":return self._chunk_by_fixed_size(content)else:return [content]def _chunk_by_sentence(self, text: str) -> List[str]:"""Chunk by sentences"""7 unmodified linesif len(current_chunk) + len(sentence) > self.config.chunk_size and current_chunk:chunks.append(current_chunk.strip())if self.config.chunk_overlap > 0:overlap_text = current_chunk[-self.config.chunk_overlap:]current_chunk = overlap_text + " " + sentence42 unmodified linesend = start + self.config.chunk_sizechunk = text[start:end]if end < len(text):last_space = chunk.rfind(' ')if last_space > len(chunk) * 0.8:2 unmodified lineschunks.append(chunk.strip())start = end - self.config.chunk_overlapif start <= 0:start = end7 unmodified linesscore = retrieval_score * self.config.score_boost_factorif self.config.normalize_scores:score = max(0.0, min(1.0, score))return round(score, 4)2 unmodified lines"""Extract source dari document metadata"""metadata = document.metadata or {}source_keys = ['source', 'file_name', 'filename', 'title', 'file_path', 'path']for key in source_keys:if key in metadata and metadata[key]:return str(metadata[key])return "unknown_source"def _build_metadata(self,8 unmodified linesmetadata = {}if self.config.extract_metadata:if document.metadata and self.config.include_document_info:metadata.update({"original_metadata": document.metadata,1 unmodified line"total_documents": total_documents})if chunk_index is not None:metadata.update({"chunk_index": chunk_index,1 unmodified line"is_chunked": total_chunks > 1})if self.config.include_retrieval_info:metadata.update({"retrieval_query": retrieval_result.query,1 unmodified line"retrieval_metadata": retrieval_result.metadata})if self.config.include_timestamps:metadata.update({"processed_at": datetime.now().isoformat(),10 unmodified lines}})word_count = len(content.split())sentence_count = len(re.split(r'[.!?]+', content))13 unmodified linesif not contexts:return contextsif self.config.use_retrieval_scores:contexts.sort(key=lambda x: x.score or 0.0, reverse=True)filtered_contexts = []for ctx in contexts:if self.config.filter_empty_content and not ctx.content.strip():11 unmodified linestotal_words = sum(len(ctx.content.split()) for ctx in contexts)total_chars = sum(len(ctx.content) for ctx in contexts)scores = [ctx.score for ctx in contexts if ctx.score is not None]sources = {}for ctx in contexts:if ctx.source:sources[ctx.source] = sources.get(ctx.source, 0) + 1chunked_contexts = sum(1 for ctx in contextsif ctx.metadata and ctx.metadata.get("is_chunked", False))19 unmodified linesstats["source_distribution"] = sourcesstats["unique_sources"] = len(sources)lengths = [len(ctx.content) for ctx in contexts]stats["content_length_stats"] = {"min_length": min(lengths),25 unmodified linestry:contexts = self.process_retrieval_result(result)for ctx in contexts:if ctx.metadata:ctx.metadata["batch_index"] = i10 unmodified linesself.logger.error(f"Error processing retrieval result {i}: {e}")continueall_contexts = self._post_process_contexts(all_contexts)self.logger.info(f"Batch processing completed: {len(all_contexts)} total contexts")24 unmodified linesfor ctx in contexts:content_words = set(ctx.content.lower().split())overlap = len(query_words.intersection(content_words))relevance_score = overlap / len(query_words) if query_words else 0.0if relevance_score >= min_relevance_score:if ctx.metadata:ctx.metadata["query_relevance_score"] = round(relevance_score, 3)ctx.metadata["matched_query_words"] = list(query_words.intersection(content_words))5 unmodified linesfiltered_contexts.append(ctx)filtered_contexts.sort(key=lambda x: x.metadata.get("query_relevance_score", 0.0),reverse=True38 unmodified linesif sim_score >= similarity_threshold:is_duplicate = Trueif (ctx.score or 0.0) > (existing_ctx.score or 0.0):idx = deduplicated.index(existing_ctx)deduplicated[idx] = ctx33 unmodified linesif not proc_result.chunks:continuefor j, chunk in enumerate(proc_result.chunks):source = self._extract_source(chunk)metadata = {"document_metadata": proc_result.document_metadata.__dict__,"chunk_index": j,2 unmodified lines"processed_at": datetime.now().isoformat()}if chunk.metadata:metadata["original_chunk_metadata"] = chunk.metadatacleaned_content = self._clean_text(chunk.page_content)if not cleaned_content or len(cleaned_content) < self.config.min_content_length:continuecontext = RetrievalResult(content=cleaned_content,source=source,score=1.0,metadata=metadata)
46 unmodified lines4748495051525314 unmodified lines686970717273747576771 unmodified line7980818283848546 unmodified lines"""Delete documents by IDs"""pass# ===== DOCUMENT LOADERS =====class MultiFormatDocumentLoader(BaseDocumentLoader):"""Document loader supporting multiple formats"""14 unmodified linesif not file_path.exists():raise FileNotFoundError(f"File not found: {file_path}")# Determine document typedoc_type = self._get_document_type(file_path)# Load documentloader_func = self.loaders.get(doc_type)if not loader_func:raise ValueError(f"Unsupported file type: {doc_type}")1 unmodified linelogger.info(f"Loading {doc_type} document: {file_path}")documents = await loader_func(str(file_path))# Add metadata to documentsfor doc in documents:doc.metadata.update({"file_path": str(file_path),46 unmodified lines4748495051525314 unmodified lines686970717273747576771 unmodified line7980818283848546 unmodified lines"""Delete documents by IDs"""passclass MultiFormatDocumentLoader(BaseDocumentLoader):"""Document loader supporting multiple formats"""14 unmodified linesif not file_path.exists():raise FileNotFoundError(f"File not found: {file_path}")doc_type = self._get_document_type(file_path)loader_func = self.loaders.get(doc_type)if not loader_func:raise ValueError(f"Unsupported file type: {doc_type}")1 unmodified linelogger.info(f"Loading {doc_type} document: {file_path}")documents = await loader_func(str(file_path))for doc in documents:doc.metadata.update({"file_path": str(file_path),
55 unmodified lines565758596061626364651 unmodified line6768697071727355 unmodified linesif not file_path.exists():raise FileNotFoundError(f"File not found: {file_path}")# Determine document typedoc_type = self._get_document_type(file_path)# Load documentloader_func = self.loaders.get(doc_type)if not loader_func:raise ValueError(f"Unsupported file type: {doc_type}")1 unmodified linelogger.info(f"Loading {doc_type} document: {file_path}")documents = await loader_func(str(file_path))# Add metadata to documentsfor doc in documents:doc.metadata.update({"file_path": str(file_path),55 unmodified lines565758596061626364651 unmodified line6768697071727355 unmodified linesif not file_path.exists():raise FileNotFoundError(f"File not found: {file_path}")doc_type = self._get_document_type(file_path)loader_func = self.loaders.get(doc_type)if not loader_func:raise ValueError(f"Unsupported file type: {doc_type}")1 unmodified linelogger.info(f"Loading {doc_type} document: {file_path}")documents = await loader_func(str(file_path))for doc in documents:doc.metadata.update({"file_path": str(file_path),
17 unmodified lines181920212223249 unmodified lines34353637383940414243444517 unmodified linesself.chunk_size = chunk_sizeself.chunk_overlap = chunk_overlap# Default separators for better chunkingif separators is None:separators = ["\n\n", "\n", " ", ""]9 unmodified linestry:logger.info(f"Processing {len(documents)} documents")# Split documents into chunkschunks = await asyncio.get_event_loop().run_in_executor(None, self.text_splitter.split_documents, documents)# Add chunk metadatafor i, chunk in enumerate(chunks):chunk.metadata.update({"chunk_id": i,17 unmodified lines181920212223249 unmodified lines34353637383940414243444517 unmodified linesself.chunk_size = chunk_sizeself.chunk_overlap = chunk_overlapif separators is None:separators = ["\n\n", "\n", " ", ""]9 unmodified linestry:logger.info(f"Processing {len(documents)} documents")chunks = await asyncio.get_event_loop().run_in_executor(None, self.text_splitter.split_documents, documents)for i, chunk in enumerate(chunks):chunk.metadata.update({"chunk_id": i,
123456789101112131470 unmodified lines858687888990919269 unmodified lines1621631641651661671681691701711721731743 unmodified lines178179180181182183184185186187188189from rag.retriever.base_retriever import BaseRetriever# Embeddingsfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_openai import OpenAIEmbeddings# Vector storesfrom langchain_community.vectorstores import Chroma, FAISS, Pineconefrom langchain.retrievers import EnsembleRetriever# Retriever basefrom langchain_core.vectorstores import VectorStoreRetrieverfrom langchain_community.retrievers import BM25Retrieverfrom langchain.retrievers import ContextualCompressionRetriever70 unmodified linessearch_kwargs={"k": 10})if self.use_hybrid_search:self.bm25_retriever = None # initialized later after adding docsreturn vector_retriever # temporary fallbackelse:return vector_retrieverexcept Exception as e:69 unmodified linesreturn Falseasync def _update_bm25_retriever(self, documents: List[Document]):try:# Create BM25 retriever from documentsself.bm25_retriever = BM25Retriever.from_documents(documents)self.bm25_retriever.k = 10 # Set number of documents to retrieve# For hybrid search, you have several options:# Option 1: Use only BM25 retriever (simplest fix)self.retriever = self.bm25_retrievervector_retriever = VectorStoreRetriever(3 unmodified linesself.retriever = EnsembleRetriever(retrievers=[vector_retriever, self.bm25_retriever],weights=[0.5, 0.5] # Equal weight to both retrievers)except Exception as e:logger.error(f"Error updating BM25 retriever: {str(e)}")# Fallback to vector retriever onlyself.retriever = VectorStoreRetriever(vectorstore=self.vectorstore,search_kwargs={"k": 10}123456789101112131470 unmodified lines858687888990919269 unmodified lines1621631641651661671681691701711721731743 unmodified lines178179180181182183184185186187188189from rag.retriever.base_retriever import BaseRetrieverfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_openai import OpenAIEmbeddingsfrom langchain_community.vectorstores import Chroma, FAISS, Pineconefrom langchain.retrievers import EnsembleRetrieverfrom langchain_core.vectorstores import VectorStoreRetrieverfrom langchain_community.retrievers import BM25Retrieverfrom langchain.retrievers import ContextualCompressionRetriever70 unmodified linessearch_kwargs={"k": 10})if self.use_hybrid_search:self.bm25_retriever = Nonereturn vector_retrieverelse:return vector_retrieverexcept Exception as e:69 unmodified linesreturn Falseasync def _update_bm25_retriever(self, documents: List[Document]):try:self.bm25_retriever = BM25Retriever.from_documents(documents)self.bm25_retriever.k = 10self.retriever = self.bm25_retrievervector_retriever = VectorStoreRetriever(3 unmodified linesself.retriever = EnsembleRetriever(retrievers=[vector_retriever, self.bm25_retriever],weights=[0.5, 0.5])except Exception as e:logger.error(f"Error updating BM25 retriever: {str(e)}")self.retriever = VectorStoreRetriever(vectorstore=self.vectorstore,search_kwargs={"k": 10}
6 unmodified lines789101112132 unmodified lines161718192021221 unmodified line242526272829303132333416 unmodified lines5152535455565758596061624 unmodified lines67686970717273747576777879808182838485861 unmodified line888990919293943 unmodified lines98991001011021031043 unmodified lines1081091101111121131141151161171183 unmodified lines1221231241251261271286 unmodified linesclass DuckDuckGoSearch:def __init__(self, html_loader: AsyncChromiumLoader = None, html_parser = None):# Initialize dengan default values jika tidak diberikanself.html_loader = html_loader or AsyncChromiumLoader([])self.html_parser = html_parser or BeautifulSoupTransformer()self.logger = logging.getLogger("ddgs_logger")2 unmodified lines"""Get page content from URLs - returns list of documents"""try:self.html_loader.urls = urlshtml = await self.html_loader.aload() # This returns a LISTself.logger.info(f"search engine aload result: {len(html)} documents loaded")docs_transformed = self.html_parser.transform_documents(1 unmodified linetags_to_extract=["p"],remove_unwanted_tags=["a"])return docs_transformed # Returns LIST of documentsexcept Exception as e:self.logger.error(f"Error loading pages: {e}", exc_info=True)return [] # Return empty list on errordef truncate(self, text: str, max_words: int = 400) -> str:"""Truncate text to specified number of words"""16 unmodified linestry:self.logger.info(f"Searching for: {query} (max_results: {max_results})")# Step 1: Get search results from DDGS (regular iterator)results = DDGS().text(query, max_results=max_results)urls = []# Step 2: Extract URLs using regular for loop (NOT async for)for result in results: # ← FIXED: Regular for loopurl = result.get('href')if url:urls.append(url)4 unmodified linesself.logger.warning("No URLs found from search results")return# Step 3: Get page content (await the coroutine first)docs = await self.get_page(urls) # ← FIXED: Await first, get list# Step 4: Process documents using regular for loop (NOT async for)for doc in docs: # ← FIXED: Regular for loop on listtry:if hasattr(doc, 'page_content') and doc.page_content:# Clean up textpage_text = re.sub(r"\n\n+", "\n", doc.page_content)page_text = page_text.strip()if page_text: # Only yield if there's actual contenttext = self.truncate(page_text)yield text # Yield makes this an async generatorexcept Exception as e:self.logger.error(f"Error processing document: {e}")1 unmodified lineexcept Exception as e:self.logger.error(f"Error in search method: {e}", exc_info=True)# Don't re-raise, just log and return (generator will be empty)async def search_with_metadata(self, query: str, max_results: int = 5) -> AsyncGenerator[dict, None]:"""3 unmodified linesresults = DDGS().text(query, max_results=max_results)urls_and_titles = []# Collect URLs and titlesfor result in results:url = result.get('href')title = result.get('title', 'No title')3 unmodified linesif not urls_and_titles:return# Get page contenturls = [item['url'] for item in urls_and_titles]docs = await self.get_page(urls)# Process and yield with metadatafor i, doc in enumerate(docs):try:if hasattr(doc, 'page_content') and doc.page_content:3 unmodified linesif page_text:text = self.truncate(page_text)# Get metadata if availablemetadata = {}if i < len(urls_and_titles):metadata = urls_and_titles[i]6 unmodified lines789101112132 unmodified lines161718192021221 unmodified line242526272829303132333416 unmodified lines5152535455565758596061624 unmodified lines67686970717273747576777879808182838485861 unmodified line888990919293943 unmodified lines98991001011021031043 unmodified lines1081091101111121131141151161171183 unmodified lines1221231241251261271286 unmodified linesclass DuckDuckGoSearch:def __init__(self, html_loader: AsyncChromiumLoader = None, html_parser = None):self.html_loader = html_loader or AsyncChromiumLoader([])self.html_parser = html_parser or BeautifulSoupTransformer()self.logger = logging.getLogger("ddgs_logger")2 unmodified lines"""Get page content from URLs - returns list of documents"""try:self.html_loader.urls = urlshtml = await self.html_loader.aload()self.logger.info(f"search engine aload result: {len(html)} documents loaded")docs_transformed = self.html_parser.transform_documents(1 unmodified linetags_to_extract=["p"],remove_unwanted_tags=["a"])return docs_transformedexcept Exception as e:self.logger.error(f"Error loading pages: {e}", exc_info=True)return []def truncate(self, text: str, max_words: int = 400) -> str:"""Truncate text to specified number of words"""16 unmodified linestry:self.logger.info(f"Searching for: {query} (max_results: {max_results})")results = DDGS().text(query, max_results=max_results)urls = []for result in results:url = result.get('href')if url:urls.append(url)4 unmodified linesself.logger.warning("No URLs found from search results")returndocs = await self.get_page(urls)for doc in docs:try:if hasattr(doc, 'page_content') and doc.page_content:page_text = re.sub(r"\n\n+", "\n", doc.page_content)page_text = page_text.strip()if page_text:text = self.truncate(page_text)yield textexcept Exception as e:self.logger.error(f"Error processing document: {e}")1 unmodified lineexcept Exception as e:self.logger.error(f"Error in search method: {e}", exc_info=True)async def search_with_metadata(self, query: str, max_results: int = 5) -> AsyncGenerator[dict, None]:"""3 unmodified linesresults = DDGS().text(query, max_results=max_results)urls_and_titles = []for result in results:url = result.get('href')title = result.get('title', 'No title')3 unmodified linesif not urls_and_titles:returnurls = [item['url'] for item in urls_and_titles]docs = await self.get_page(urls)for i, doc in enumerate(docs):try:if hasattr(doc, 'page_content') and doc.page_content:3 unmodified linesif page_text:text = self.truncate(page_text)metadata = {}if i < len(urls_and_titles):metadata = urls_and_titles[i]
30 unmodified lines3132333435363763 unmodified lines1011021031041051061075 unmodified lines1131141151161171181191 unmodified line12112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615711 unmodified lines16917017117217317417530 unmodified linesfrom rag import cs_agent# Load .envload_dotenv()logging.basicConfig(level=logging.INFO)63 unmodified linesllm_time = time.time()self.full_response = ""# Single async function to handle both text streaming and audio generationasync def stream_text_to_audio():chunk_size = 1024no_buffer = 05 unmodified lineschunk = stream_data["data"]["chunk"]self.full_response += chunktext_buffer += chunk# Generate audio immediately for each text chunkif re.search(r'[.,?;!]', chunk):try:audio_buffer_gen = await self.edge_tts.generate_audio_buffer(text_buffer)1 unmodified lineaudio_buffer.seek(0)# Convert MP3 to PCMaudio_segment = AudioSegment.from_file(audio_buffer, format="mp3")samples = np.array(audio_segment.get_array_of_samples()).astype(np.float32) / (2 ** 15)# Handle stereo to monoif audio_segment.channels == 2:samples = samples.reshape((-1, 2)).mean(axis=1)# # Resample to 24kHz# resampled = librosa.resample(samples, orig_sr=audio_segment.frame_rate, target_sr=24000)import torchimport torchaudio# Check if CUDA is availabledevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")# Convert numpy array to torch tensor and move to GPUaudio_tensor = torch.from_numpy(samples).unsqueeze(0).to(device) # Add batch dimension and move to GPU# Create resampler and move to GPUresampler = torchaudio.transforms.Resample(orig_freq=audio_segment.frame_rate,new_freq=24000).to(device)# Apply resampling on GPUresampled_tensor = resampler(audio_tensor)# Convert back to numpy (move to CPU first)resampled = resampled_tensor.squeeze(0).cpu().numpy()# Yield audio chunksfor i in range(0, len(resampled), chunk_size):yield (24000, resampled[i:i + chunk_size])no_buffer = 011 unmodified linesprint(f"\nTotal time: {total_time:.2f}s")break# Run the single async functionloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)30 unmodified lines3132333435363763 unmodified lines1011021031041051061075 unmodified lines1131141151161171181191 unmodified line12112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615711 unmodified lines16917017117217317417530 unmodified linesfrom rag import cs_agentload_dotenv()logging.basicConfig(level=logging.INFO)63 unmodified linesllm_time = time.time()self.full_response = ""async def stream_text_to_audio():chunk_size = 1024no_buffer = 05 unmodified lineschunk = stream_data["data"]["chunk"]self.full_response += chunktext_buffer += chunkif re.search(r'[.,?;!]', chunk):try:audio_buffer_gen = await self.edge_tts.generate_audio_buffer(text_buffer)1 unmodified lineaudio_buffer.seek(0)audio_segment = AudioSegment.from_file(audio_buffer, format="mp3")samples = np.array(audio_segment.get_array_of_samples()).astype(np.float32) / (2 ** 15)if audio_segment.channels == 2:samples = samples.reshape((-1, 2)).mean(axis=1)import torchimport torchaudiodevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")audio_tensor = torch.from_numpy(samples).unsqueeze(0).to(device)resampler = torchaudio.transforms.Resample(orig_freq=audio_segment.frame_rate,new_freq=24000).to(device)resampled_tensor = resampler(audio_tensor)resampled = resampled_tensor.squeeze(0).cpu().numpy()for i in range(0, len(resampled), chunk_size):yield (24000, resampled[i:i + chunk_size])no_buffer = 011 unmodified linesprint(f"\nTotal time: {total_time:.2f}s")breakloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)
14 unmodified lines15161718192021222324252627282930313233343536373839404110 unmodified lines525354555657585960616263646566676869707172737414 unmodified linesmodel_size: Model size (tiny, base, small, medium, large)device: Device to use ("auto", "cuda", "cpu")"""# Set up cache directorycache_dir = os.environ.get('WHISPER_CACHE_DIR', '/tmp/.cache/whisper')os.makedirs(cache_dir, exist_ok=True)# Determine deviceif device == "auto":self.device = "cuda" if torch.cuda.is_available() else "cpu"else:self.device = device# Validate CUDA availability if requestedif self.device == "cuda" and not torch.cuda.is_available():print("Warning: CUDA requested but not available. Falling back to CPU.")self.device = "cpu"# Load model with device specificationprint(f"Loading Whisper model '{model_size}' on device: {self.device}")self.model = whisper.load_model(model_size, device=self.device, download_root=cache_dir)self.language = "id" # ISO-639-1 code for Bahasa Indonesia# Print GPU info if using CUDAif self.device == "cuda":gpu_name = torch.cuda.get_device_name(0)gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**310 unmodified linesReturns:Transcribed text"""# Save audio to temporary filewith tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:tmp.write(audio.read())tmp.flush()tmp_path = tmp.nametry:# Transcribe with GPU acceleration if availableresult = self.model.transcribe(tmp_path,language=language,# Optional: Add fp16 for faster inference on supported GPUsfp16=self.device == "cuda")return result.get("text", "")finally:# Clean up temporary fileos.remove(tmp_path)def get_device_info(self) -> dict:14 unmodified lines15161718192021222324252627282930313233343536373839404110 unmodified lines525354555657585960616263646566676869707172737414 unmodified linesmodel_size: Model size (tiny, base, small, medium, large)device: Device to use ("auto", "cuda", "cpu")"""cache_dir = os.environ.get('WHISPER_CACHE_DIR', '/tmp/.cache/whisper')os.makedirs(cache_dir, exist_ok=True)if device == "auto":self.device = "cuda" if torch.cuda.is_available() else "cpu"else:self.device = deviceif self.device == "cuda" and not torch.cuda.is_available():print("Warning: CUDA requested but not available. Falling back to CPU.")self.device = "cpu"print(f"Loading Whisper model '{model_size}' on device: {self.device}")self.model = whisper.load_model(model_size, device=self.device, download_root=cache_dir)self.language = "id"if self.device == "cuda":gpu_name = torch.cuda.get_device_name(0)gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**310 unmodified linesReturns:Transcribed text"""with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:tmp.write(audio.read())tmp.flush()tmp_path = tmp.nametry:result = self.model.transcribe(tmp_path,language=language,fp16=self.device == "cuda")return result.get("text", "")finally:os.remove(tmp_path)def get_device_info(self) -> dict:
28 unmodified lines2930313233343516 unmodified lines5253545556575826 unmodified lines8586878889909128 unmodified linespitch=self.pitch_str)# Stream audio chunksasync for chunk in communicate.stream():if chunk["type"] == "audio":yield chunk["data"]16 unmodified linespitch=self.pitch_str)# Collect all audio chunks into a bufferaudio_buffer = io.BytesIO()async for chunk in communicate.stream():if chunk["type"] == "audio":26 unmodified linesasync for chunk in communicate.stream():if chunk["type"] == "audio":# Call callback with audio chunkcallback_func(chunk["data"], None)except Exception as e:28 unmodified lines2930313233343516 unmodified lines5253545556575826 unmodified lines8586878889909128 unmodified linespitch=self.pitch_str)async for chunk in communicate.stream():if chunk["type"] == "audio":yield chunk["data"]16 unmodified linespitch=self.pitch_str)audio_buffer = io.BytesIO()async for chunk in communicate.stream():if chunk["type"] == "audio":26 unmodified linesasync for chunk in communicate.stream():if chunk["type"] == "audio":callback_func(chunk["data"], None)except Exception as e:
48 unmodified lines495051525354555657585948 unmodified lines)document_retriever = LangChainRetriever(embedding_model="sentence-transformers/all-MiniLM-L6-v2",vectorstore_type="chroma",vectorstore_path="vectorstore/",use_hybrid_search=True,chunk_size=1000,chunk_overlap=200)48 unmodified lines495051525354555657585948 unmodified lines)document_retriever = LangChainRetriever(embedding_model="BAAI/bge-large-en",vectorstore_type="chroma",vectorstore_path="vectorstore/",use_hybrid_search=True,chunk_size=3000,chunk_overlap=200)
12345678910111213141516from rag.pipeline.language_model import LMfrom rag.inference.inferencer import Inferencerfrom abc import ABC, abstractmethodclass Agent(ABC): def __init__(self, inferencer:Inferencer, prompt_template = [ { "role" : "system", "content":"You are an agent that doing some specic task" } ]): self.inferencer = inferencer self.inferencer.model.prompt_template = prompt_template self.prompt = prompt_template @abstractmethod async def get_result(self): pass123456789101112131415161718192021222324252627282930313233from rag.agents.agents import Agentfrom rag.inference.inferencer import Inferencer
class CSAgent(Agent): def __init__(self, inferencer : Inferencer , prompt_template): super().__init__(inferencer, prompt_template) self.inferencer = inferencer self.prompt_template = prompt_template self.file_paths = [ "../documents/bpjs.pdf", # "../documents/pph21.pdf", # "../documents/lembur.pdf", # "../documents/uu13.pdf", "../documents/file.pdf", ] async def load_documents(self): for file_path in self.file_paths: await self.add_doc(file_path) async def add_doc(self, file_path): result = await self.inferencer.retriever.add_document_from_file(file_path) if result.success: print(f"Successfully processed: {result.document_metadata.file_name}") print(f"Chunks created: {result.document_metadata.chunk_count}") else: print(f"Failed to process: {result.error_message}")
async def get_result(self, question): self.inferencer.model.prompt_template = self.prompt_template async for item in self.inferencer.infer_stream(query = question, enable_reranking=False, k=3): yield item12345678910111213from rag.agents.agents import Agentfrom rag.pipeline.language_model import LMfrom rag.inference.inferencer import Inferencer
class GPTCSAgent(Agent): def __init__(self, inferencer : Inferencer , prompt_template): super().__init__(inferencer, prompt_template) self.inferencer = inferencer self.prompt_template = prompt_template async def get_result(self, question : str): self.inferencer.model.prompt_template = self.prompt_template print("Question received :", question) return await self.inferencer.infer(query = question)12345678910111213from rag.agents.agents import Agentfrom rag.pipeline.language_model import LMfrom rag.inference.inferencer import Inferencer
class QueryMakerAgent(Agent): def __init__(self, inferencer : Inferencer , prompt_template): super().__init__(inferencer, prompt_template) self.inferencer = inferencer self.prompt_template = prompt_template async def get_result(self, question : str): self.inferencer.model.prompt_template = self.prompt_template print("Question received :", question) return await self.inferencer.infer(query = question)1234567891011121314151617181920212223242526272829def read_template_txt(file_path): """Baca file txt biasa""" with open(f"rag/chat_template/{file_path}.txt", 'r', encoding='utf-8') as f: return f.read()def get_chat_template(file_name): sys_prompt = read_template_txt(file_name) return [ { "role" : "system", "content" : f""" {sys_prompt} """ }, { "role" : "user", "content" : """ Please answer properly: {question}
From given context : {context}
""" } ] 123456789101112You are a friendly and professional Customer Service for Human Resource Information System (HRIS) field,representative, fluent in Indonesian. Your job is to assist customers with accurate information based on your company's basic knowledge. Follow these guidelines:
- Always greet customers in a friendly and professional manner.- Your answers are contextual and objective.- Provide clear, easy-to-understand, and structured answers based on the context provided by the user.- If information is not available, offer alternative assistance or direct them to the appropriate channel.- Use polite language and empathize with the customer's needs.- Conclude by offering further assistance.- You are highly skilled in the area relevant to the given context.
Please use the given context to answer accurately.1234567891011121314151617181920212223242526272829303132333435Anda adalah agen AI yang tepat dan objektif, Anda bertugas mengubah pertanyaan atau pernyataan pengguna menjadi query yang eksplisit dan efisien untuk keperluan pencarian dokumen dalam sistem RAG (Retrieval-Augmented Generation).
Ikuti langkah-langkah berikut:
1. Ekstrak bagian-bagian penting dari input pengguna: - **Intent**: Tujuan utama atau jenis permintaan (misalnya: apa itu, cara, syarat, apakah bisa, berapa). - **Entity/Noun Phrase**: Objek utama yang dibahas (misalnya: BPJS, tokenizer truncation, RWKV, gaji). - **Context**: Informasi pendukung yang menyempitkan fokus (misalnya: kecelakaan kerja, gaji 1 juta per bulan, perusahaan mitra BPJS). - **Question**: Pertanyaan spesifik yang ingin dijawab (misalnya: bagaimana prosesnya, apa manfaatnya, berapa jumlahnya).
2. Setelah semua elemen diidentifikasi, bentuk **Query RAG** dengan struktur: [INTENT] + [ENTITY] + [CONTEXT] + [QUESTION]3. Gunakan bahasa natural yang ringkas, namun informatif dan eksplisit.4. Generate hanya hasil akhirnya saja berupa satu buah kalimat
Contoh 0 :User Input:> Apa itu BPJSOutput : Pengertian BPJS
Contoh 1 :User Input:> Di mana lokasi PT Sakura System Solution ?
Output: Lokasi PT Sakura System Solution
Contoh 2:User Input:> Saya mengalami kecelakaan di kantor dan ingin tahu apakah bisa klaim BPJS karena perusahaan saya adalah mitra.
Output: apakah bisa klaim BPJS kecelakaan kerja di kantor jika perusahaan mitra dan apakah saya memenuhi syarat
**Tugas Anda sekarang:**Lakukan proses di atas untuk setiap input pengguna yang diberikan. Hasilkan query RAG akhir yang siap digunakan dalam pencarian dokumen.123456789101112131415161718192021222324252627282930Anda adalah agen AI yang tepat dan objektif, Anda bertugas mengubah pertanyaan atau pernyataan pengguna menjadi query yang eksplisit dan efisien untuk keperluan pencarian dokumen dalam sistem RAG (Retrieval-Augmented Generation).
Ikuti langkah-langkah berikut:
1. Ekstrak bagian-bagian penting dari input pengguna: - **Intent**: Tujuan utama atau jenis permintaan (misalnya: apa itu, cara, syarat, apakah bisa, berapa). - **Entity/Noun Phrase**: Objek utama yang dibahas (misalnya: BPJS, tokenizer truncation, RWKV, gaji). - **Context**: Informasi pendukung yang menyempitkan fokus (misalnya: kecelakaan kerja, gaji 1 juta per bulan, perusahaan mitra BPJS). - **Question**: Pertanyaan spesifik yang ingin dijawab (misalnya: bagaimana prosesnya, apa manfaatnya, berapa jumlahnya).
2. Setelah semua elemen diidentifikasi, bentuk **Query RAG** dengan struktur: [INTENT] + [ENTITY] + [CONTEXT] + [QUESTION]3. Gunakan bahasa natural yang ringkas, namun informatif dan eksplisit.4. Generate hanya hasil akhirnya saja berupa satu buah kalimat
Contoh 1 :User Input:> Di mana lokasi PT Sakura System Solution ?
Output: Lokasi PT Sakura System Solution
Contoh 2:User Input:> Saya mengalami kecelakaan di kantor dan ingin tahu apakah bisa klaim BPJS karena perusahaan saya adalah mitra.
Output: apakah bisa klaim BPJS kecelakaan kerja di kantor jika perusahaan mitra dan apakah saya memenuhi syarat
**Tugas Anda sekarang:**Lakukan proses di atas untuk setiap input pengguna yang diberikan. Hasilkan query RAG akhir yang siap digunakan dalam pencarian dokumen.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947import torchimport asynciofrom transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig, TextIteratorStreamer, BitsAndBytesConfigimport torchfrom typing import Optional, Dict, Any, List, Union, Callable, Awaitable, AsyncGeneratorimport loggingfrom dataclasses import dataclassfrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutorfrom functools import partialfrom threading import Threadfrom rag.retriever.retriever_types import RetrievalResultfrom langchain_core.documents import Documentimport copy
@dataclassclass LMConfig: model_name: str = "Qwen/Qwen2.5-1.5B-Instruct" device: str = "cuda" torch_dtype: torch.dtype = torch.float16 max_length: int = 2048 temperature: float = 0.7 top_p: float = 0.8 top_k: int = 50 do_sample: bool = True quantization_config: any = None pad_token_id: Optional[int] = None eos_token_id: Optional[int] = None # RAG-specific configs max_context_length: int = 1500 context_separator: str = "\n---\n" instruction_template: str = "system" # "system", "instruction", "custom" # Async-specific configs max_workers: int = 2 generation_timeout: float = 30 repetition_penalty: float = 1.0 # Streaming-specific configs stream_timeout: float = 100 # timeout untuk stream chunk skip_prompt: bool = True # skip prompt dari streaming output
class LM: """ Async LLM Qwen 0.5B dengan interface yang mudah digunakan Termasuk prompt formatting khusus untuk RAG (Retrieval-Augmented Generation) Dan support untuk text streaming """ def __init__(self, config: Optional[LMConfig] = None, prompt_template = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "{question}"} ] ): """ Inisialisasi LM Args: config: Konfigurasi model (optional, akan menggunakan default jika None) """ if(config is None): self.config = LMConfig() else: self.config = config self.tokenizer : AutoTokenizer = None self.model = None self.generation_config = None self.is_loaded = False self.executor = ThreadPoolExecutor(max_workers=self.config.max_workers) self._lock = asyncio.Lock() # Setup logging logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger(__name__) # RAG prompt templates self.prompt_template = prompt_template async def load_model(self) -> None: """Load model dan tokenizer secara async""" async with self._lock: if self.is_loaded: self.logger.info("Model already loaded") return try: self.logger.info(f"Loading model: {self.config.model_name}") # Load tokenizer dalam thread pool self.tokenizer = await asyncio.get_event_loop().run_in_executor( self.executor, lambda: AutoTokenizer.from_pretrained( self.config.model_name, trust_remote_code=True, torch_dtype="auto", device_map="auto", ) ) # Load model dalam thread pool self.model = await asyncio.get_event_loop().run_in_executor( self.executor, lambda: AutoModelForCausalLM.from_pretrained( self.config.model_name, quantization_config=self.config.quantization_config, torch_dtype=self.config.torch_dtype, device_map=self.config.device, trust_remote_code=True ) ) # Setup generation config self.generation_config = GenerationConfig( max_length=self.config.max_length, temperature=self.config.temperature, top_p=self.config.top_p, top_k=self.config.top_k, do_sample=self.config.do_sample, pad_token_id=self.config.pad_token_id or self.tokenizer.eos_token_id, eos_token_id=self.config.eos_token_id or self.tokenizer.eos_token_id, repetition_penalty = self.config.repetition_penalty, ) self.is_loaded = True self.logger.info("Model loaded successfully!") except Exception as e: self.logger.error(f"Error loading model: {e}") raise def get_available_templates(self) -> List[str]: """ Dapatkan list template yang tersedia Returns: List of available template names """ return list(self.prompt_template) def preview_template(self, template_type: str, sample_question: str = "Apa itu AI?", sample_context: str = "Artificial Intelligence adalah teknologi...") -> str: """ Preview template dengan sample data Args: template_type: Template type to preview sample_question: Sample question sample_context: Sample context Returns: Preview of formatted template """ if template_type not in self.prompt_template: return f"Template '{template_type}' tidak tersedia. Available: {self.get_available_templates()}" template_data = copy.deepcopy(self.prompt_template) # template_key = "user_template" if "user_template" in template_data else "template" return template_data["content"].format( context=sample_context, question=sample_question ) def _format_context(self, contexts: Union[List[str], RetrievalResult], numbering: bool = True) -> str: """ Format retrieved contexts menjadi string yang coherent Args: contexts: List of contexts (string atau RetrievalResult objects) numbering: Whether to add document numbering Returns: Formatted context string """ if not contexts: return "" formatted_contexts = [] self.logger.info(f"Context : {contexts}") self.logger.info(f"Is RetrievalResult Contexts = {isinstance(contexts, RetrievalResult)}") if isinstance(contexts, RetrievalResult): for i, ctx in enumerate(contexts.documents, 1): if numbering: header = f"[Dokumen {i}" if contexts.scores[i - 1]: header += f" (Skor: {contexts.scores[i - 1]:.3f})" header += "]" else: header = "[Dokumen" header += "]" formatted_contexts.append(f"{header}\n{ctx.page_content}") else: for i, ctx in enumerate(contexts, 1): if isinstance(ctx, str): header = f"[Dokumen {i}]" if numbering else "[Dokumen]" formatted_contexts.append(f"{header}\n{ctx}") else: header = f"[Dokumen {i}]" if numbering else "[Dokumen]" formatted_contexts.append(f"{header}\n{str(ctx)}") return self.config.context_separator.join(formatted_contexts) def _truncate_context(self, context: str, max_length: int) -> str: """ Truncate context jika terlalu panjang Args: context: Context string max_length: Maximum length in characters Returns: Truncated context """ if len(context) <= max_length: return context # Truncate dan tambahkan indicator truncated = context[:max_length - 50] return truncated + "\n\n[... Context dipotong karena terlalu panjang ...]"
async def format_rag_prompt(self, question: str, contexts: Union[List[str], RetrievalResult], template_type: Optional[str] = None, custom_template: Optional[str] = None, include_metadata: bool = True, context_numbering: bool = True, max_contexts: Optional[int] = None) -> str: """ Format prompt untuk RAG dengan berbagai template options (async) """ def _format_sync(): # Handle RetrievalResult secara eksplisit if isinstance(contexts, RetrievalResult): docs = contexts.documents if max_contexts: docs = docs[:max_contexts] processed_contexts = RetrievalResult( documents=docs, scores=contexts.scores[:len(docs)] if contexts.scores else [], query=contexts.query, retrieval_time=contexts.retrieval_time, metadata=contexts.metadata ) else: # contexts diasumsikan sebagai list biasa (list[str] atau list[Document]) processed_contexts = contexts[:max_contexts] if max_contexts and len(contexts) > max_contexts else contexts
# Format context menjadi string formatted_context = self._format_context(processed_contexts, context_numbering)
# Truncate jika panjang melebihi batas formatted_context = self._truncate_context( formatted_context, self.config.max_context_length )
# Tambah metadata jika diizinkan dan konteks adalah RetrievalResult if include_metadata and isinstance(processed_contexts, RetrievalResult): metadata_info = [] for i, doc in enumerate(processed_contexts.documents, 1): if hasattr(doc, "metadata") and doc.metadata: metadata_info.append(f"Dokumen {i}: {doc.metadata}") # if metadata_info: # formatted_context += f"\n\n[Metadata]\n" + "\n".join(metadata_info)
return formatted_context
# Jalankan _format_sync di thread pool formatted_context = await asyncio.get_event_loop().run_in_executor( self.executor, _format_sync ) self.logger.info(f"Formatted Context {formatted_context}") # Tentukan template yang akan dipakai if(template_type == ""): self.config.instruction_template = "system" # Gunakan custom template jika disediakan if custom_template: return custom_template.format( context=formatted_context, question=question ) elif self.prompt_template: print("question", question) template_data = copy.deepcopy(self.prompt_template) print("template = ", template_type, "rag template = ", template_data) # template_key = "user_template" if "user_template" in template_data else "template"
formatted_template = [] for cht in template_data: # Create a copy of the content to avoid modifying the original content = cht["content"] # Format both placeholders at once to avoid KeyError if "{context}" in content or "{question}" in content: try: content = content.format( context=formatted_context, question=question ) except KeyError as e: self.logger.error(f"Missing placeholder in template: {e}") # Fallback: format only available placeholders if "{context}" in content: content = content.replace("{context}", formatted_context) if "{question}" in content: content = content.replace("{question}", question) # Create new dict with formatted content formatted_chat = { "role": cht["role"], "content": content } # Copy other fields if they exist if "description" in cht: formatted_chat["description"] = cht["description"] formatted_template.append(formatted_chat)
# self.logger.info(f"Formatted Template {formatted_template}") # print("Forrmatted Template", formatted_template) return formatted_template else: # Fallback default template return [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": question} ]
async def generate_stream(self, prompt: List[Dict], max_new_tokens: Optional[int] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, **kwargs) -> AsyncGenerator[str, None]: """ Generate text dari prompt secara streaming async Args: prompt: Input text prompt max_new_tokens: Maximum token baru yang akan di-generate temperature: Temperature untuk generation (override config) top_p: Top-p untuk generation (override config) **kwargs: Parameter tambahan untuk generation Yields: Generated text chunks """ await self._check_model_loaded() # Setup streamer streamer = TextIteratorStreamer( self.tokenizer, timeout=self.config.stream_timeout, skip_prompt=self.config.skip_prompt, skip_special_tokens=True ) def _generate_sync(): try: # Tokenize input inputs = self.tokenizer.apply_chat_template( prompt, add_generation_prompt=True, return_tensors="pt" ) # Override generation config jika diperlukan gen_config = self.generation_config if any([max_new_tokens, temperature, top_p]): gen_config = GenerationConfig( max_new_tokens=max_new_tokens or self.config.max_length, temperature=temperature or self.config.temperature, top_p=top_p or self.config.top_p, top_k=self.config.top_k, do_sample=self.config.do_sample, pad_token_id=self.config.pad_token_id or self.tokenizer.eos_token_id, eos_token_id=self.config.eos_token_id or self.tokenizer.eos_token_id, repetition_penalty=self.config.repetition_penalty, **kwargs ) # Move to GPU self.model.to("cuda") input_ids = inputs.to("cuda") # Generate dalam thread terpisah generation_kwargs = { "input_ids": input_ids, "generation_config": gen_config, "streamer": streamer, **kwargs } thread = Thread(target=self.model.generate, kwargs=generation_kwargs) thread.start() return thread except Exception as e: self.logger.error(f"Error during stream generation setup: {e}") raise # Setup generation thread generation_thread = await asyncio.get_event_loop().run_in_executor( self.executor, _generate_sync ) err = None try: # Stream tokens for token in streamer: if token: # Skip empty tokens yield token # Wait for generation thread to finish err = await asyncio.get_event_loop().run_in_executor( self.executor, generation_thread.join ) except Exception as e: self.logger.error(f"Error during streaming: {e}, {err}") # Make sure thread is cleaned up if generation_thread.is_alive(): generation_thread.join(timeout=1.0) raise
async def rag_generate_stream(self, question: str, contexts: Union[List[str], RetrievalResult], template_type: Optional[str] = None, max_new_tokens: Optional[int] = None, temperature: Optional[float] = None, **kwargs) -> AsyncGenerator[str, None]: """ Generate jawaban untuk RAG secara streaming async Args: question: User question contexts: List of retrieved contexts template_type: Template type untuk formatting max_new_tokens: Maximum token baru yang akan di-generate temperature: Temperature untuk generation **kwargs: Parameter tambahan untuk generation Yields: Generated answer chunks """ await self._check_model_loaded() # Format prompt prompt = await self.format_rag_prompt(question, contexts, template_type) # Generate dengan temperature yang lebih rendah untuk RAG (lebih faktual) temp = temperature if temperature is not None else 0.3 async for chunk in self.generate_stream( prompt=prompt, max_new_tokens=max_new_tokens, temperature=temp, **kwargs ): yield chunk
async def chat_stream(self, messages: List[Dict[str, str]], max_new_tokens: Optional[int] = None, **kwargs) -> AsyncGenerator[str, None]: """ Chat dengan format conversation secara streaming async Args: messages: List of messages dengan format [{"role": "user", "content": "..."}] max_new_tokens: Maximum token baru yang akan di-generate **kwargs: Parameter tambahan untuk generation Yields: Response text chunks """ await self._check_model_loaded() def _format_chat(): try: # Format messages untuk chat formatted_prompt = self.tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) return formatted_prompt except Exception as e: self.logger.error(f"Error during chat formatting: {e}") raise # Format chat template dalam thread pool formatted_prompt = await asyncio.get_event_loop().run_in_executor( self.executor, _format_chat ) async for chunk in self.generate_stream( formatted_prompt, max_new_tokens=max_new_tokens, **kwargs ): yield chunk
async def rag_chat_stream(self, messages: List[Dict[str, str]], contexts: Union[List[str], RetrievalResult], template_type: Optional[str] = None, max_new_tokens: Optional[int] = None, **kwargs) -> AsyncGenerator[str, None]: """ RAG Chat dengan format conversation secara streaming async Args: messages: List of messages dengan format [{"role": "user", "content": "..."}] contexts: List of retrieved contexts template_type: Template type untuk formatting max_new_tokens: Maximum token baru yang akan di-generate **kwargs: Parameter tambahan untuk generation Yields: Response text chunks """ await self._check_model_loaded() # Ambil last user message sebagai question user_messages = [msg for msg in messages if msg.get("role") == "user"] if not user_messages: raise ValueError("No user message found in conversation") last_question = user_messages[-1]["content"] # Generate RAG response secara streaming async for chunk in self.rag_generate_stream( question=last_question, contexts=contexts, template_type=template_type, max_new_tokens=max_new_tokens, **kwargs ): yield chunk
# Utility method untuk collect full response dari stream async def collect_stream(self, stream_generator: AsyncGenerator[str, None]) -> str: """ Collect semua chunks dari stream generator menjadi full text Args: stream_generator: AsyncGenerator yang menghasilkan text chunks Returns: Complete generated text """ chunks = [] async for chunk in stream_generator: chunks.append(chunk) return "".join(chunks) async def multi_template_generate(self, question: str, contexts: Union[List[str], RetrievalResult], template_types: List[str], max_new_tokens: Optional[int] = None, **kwargs) -> Dict[str, str]: """ Generate jawaban menggunakan multiple templates secara concurrent Args: question: User question contexts: List of retrieved contexts template_types: List of template types to use max_new_tokens: Maximum token baru yang akan di-generate **kwargs: Parameter tambahan untuk generation Returns: Dictionary dengan template_type sebagai key dan response sebagai value """ await self._check_model_loaded() # Create tasks untuk concurrent generation tasks = [] for template_type in template_types: task = asyncio.create_task( self._generate_single_template( question, contexts, template_type, max_new_tokens, **kwargs ) ) tasks.append((template_type, task)) # Wait for all tasks results = {} for template_type, task in tasks: try: response = await task results[template_type] = response except Exception as e: self.logger.error(f"Error generating with template {template_type}: {e}") results[template_type] = f"Error: {str(e)}" return results async def _generate_single_template(self, question: str, contexts: Union[List[str], RetrievalResult], template_type: str, max_new_tokens: Optional[int] = None, **kwargs) -> str: """Helper method untuk single template generation""" return await self.rag_generate( question=question, contexts=contexts, template_type=template_type, max_new_tokens=max_new_tokens, **kwargs ) async def rag_generate(self, question: str, contexts: Union[List[str], RetrievalResult], template_type: Optional[str] = None, max_new_tokens: Optional[int] = None, temperature: Optional[float] = None, **kwargs) -> str: """ Generate jawaban untuk RAG secara async Args: question: User question contexts: List of retrieved contexts template_type: Template type untuk formatting max_new_tokens: Maximum token baru yang akan di-generate temperature: Temperature untuk generation **kwargs: Parameter tambahan untuk generation Returns: Generated answer """ await self._check_model_loaded() # Format prompt prompt = await self.format_rag_prompt(question, contexts, template_type) # Generate dengan temperature yang lebih rendah untuk RAG (lebih faktual) temp = temperature if temperature is not None else 0.3 return await self.generate( prompt=prompt, max_new_tokens=max_new_tokens, temperature=temp, **kwargs ) async def rag_chat(self, messages: List[Dict[str, str]], contexts: Union[List[str], RetrievalResult], template_type: Optional[str] = None, max_new_tokens: Optional[int] = None, **kwargs) -> str: """ RAG Chat dengan format conversation secara async Args: messages: List of messages dengan format [{"role": "user", "content": "..."}] contexts: List of retrieved contexts template_type: Template type untuk formatting max_new_tokens: Maximum token baru yang akan di-generate **kwargs: Parameter tambahan untuk generation Returns: Response text """ await self._check_model_loaded() # Ambil last user message sebagai question user_messages = [msg for msg in messages if msg.get("role") == "user"] if not user_messages: raise ValueError("No user message found in conversation") last_question = user_messages[-1]["content"] # Generate RAG response return await self.rag_generate( question=last_question, contexts=contexts, template_type=template_type, max_new_tokens=max_new_tokens, **kwargs ) async def _check_model_loaded(self) -> None: """Cek apakah model sudah di-load secara async""" if not self.is_loaded: raise RuntimeError("Model belum di-load. Panggil await load_model() terlebih dahulu.") async def generate(self, prompt: Union[List[Dict], str], max_new_tokens: Optional[int] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, **kwargs) -> str: """ Generate text dari prompt secara async Args: prompt: Input text prompt max_new_tokens: Maximum token baru yang akan di-generate temperature: Temperature untuk generation (override config) top_p: Top-p untuk generation (override config) **kwargs: Parameter tambahan untuk generation Returns: Generated text """ await self._check_model_loaded() def _generate_sync(): try: # Tokenize input inputs = self.tokenizer.apply_chat_template( prompt, add_generation_prompt=True, return_tensors="pt" ) # Override generation config jika diperlukan gen_config = self.generation_config if any([max_new_tokens, temperature, top_p]): gen_config = GenerationConfig( max_new_tokens=max_new_tokens or self.config.max_length, temperature=temperature or self.config.temperature, top_p=top_p or self.config.top_p, top_k=self.config.top_k, do_sample=self.config.do_sample, pad_token_id=self.config.pad_token_id or self.tokenizer.eos_token_id, eos_token_id=self.config.eos_token_id or self.tokenizer.eos_token_id, repetition_penalty = self.config.repetition_penalty, **kwargs ) # Generate with torch.no_grad(): self.model.to("cuda") input_ids = inputs.to("cuda") prompt_length = input_ids.shape[-1] outputs = self.model.generate( input_ids, generation_config=gen_config, **kwargs ) # Decode output generated_text = self.tokenizer.decode( outputs[0][prompt_length:], skip_special_tokens=True )
print("Generated Text", generated_text) # Remove input prompt dari output return generated_text except Exception as e: self.logger.error(f"Error during generation: {e}") raise # Run generation in thread pool dengan timeout try: result = await asyncio.wait_for( asyncio.get_event_loop().run_in_executor(self.executor, _generate_sync), timeout=self.config.generation_timeout ) return result except asyncio.TimeoutError: self.logger.error(f"Generation timeout after {self.config.generation_timeout} seconds") raise TimeoutError(f"Generation timeout after {self.config.generation_timeout} seconds") async def chat(self, messages: List[Dict[str, str]], max_new_tokens: Optional[int] = None, **kwargs) -> str: """ Chat dengan format conversation secara async Args: messages: List of messages dengan format [{"role": "user", "content": "..."}] max_new_tokens: Maximum token baru yang akan di-generate **kwargs: Parameter tambahan untuk generation Returns: Response text """ await self._check_model_loaded() def _format_chat(): try: # Format messages untuk chat formatted_prompt = self.tokenizer.apply_chat_template( messages, chat_template="rag", return_tensors="pt" ) return formatted_prompt except Exception as e: self.logger.error(f"Error during chat formatting: {e}") raise # Format chat template dalam thread pool formatted_prompt = await asyncio.get_event_loop().run_in_executor( self.executor, _format_chat ) return await self.generate( formatted_prompt, max_new_tokens=max_new_tokens, **kwargs ) async def update_config(self, **kwargs) -> None: """ Update konfigurasi model secara async Args: **kwargs: Parameter konfigurasi yang akan diupdate """ async with self._lock: for key, value in kwargs.items(): if hasattr(self.config, key): setattr(self.config, key, value) self.logger.info(f"Updated {key} to {value}") else: self.logger.warning(f"Unknown config parameter: {key}") # Update generation config jika model sudah loaded if self.is_loaded: self.generation_config = GenerationConfig( max_length=self.config.max_length, temperature=self.config.temperature, top_p=self.config.top_p, top_k=self.config.top_k, do_sample=self.config.do_sample, pad_token_id=self.config.pad_token_id or self.tokenizer.eos_token_id, eos_token_id=self.config.eos_token_id or self.tokenizer.eos_token_id, repetition_penalty = self.config.repetition_penalty,
) async def get_model_info(self) -> Dict[str, Any]: """ Dapatkan informasi model secara async Returns: Dictionary dengan informasi model """ info = { "model_name": self.config.model_name, "is_loaded": self.is_loaded, "config": self.config.__dict__ } if self.is_loaded: # Get model info dalam thread pool def _get_info(): return { "vocab_size": self.tokenizer.vocab_size, "model_parameters": sum(p.numel() for p in self.model.parameters()), "device": str(next(self.model.parameters()).device) } model_info = await asyncio.get_event_loop().run_in_executor( self.executor, _get_info ) info.update(model_info) return info async def batch_generate(self, prompts: List[str], max_new_tokens: Optional[int] = None, **kwargs) -> List[str]: """ Generate multiple prompts secara batch dan concurrent Args: prompts: List of prompts to generate max_new_tokens: Maximum token baru yang akan di-generate **kwargs: Parameter tambahan untuk generation Returns: List of generated texts """ await self._check_model_loaded() # Create tasks untuk concurrent generation tasks = [ asyncio.create_task( self.generate(prompt, max_new_tokens=max_new_tokens, **kwargs) ) for prompt in prompts ] # Wait for all tasks results = await asyncio.gather(*tasks, return_exceptions=True) # Process results processed_results = [] for i, result in enumerate(results): if isinstance(result, Exception): self.logger.error(f"Error generating prompt {i}: {result}") processed_results.append(f"Error: {str(result)}") else: processed_results.append(result) return processed_results async def close(self) -> None: """ Cleanup resources secara async """ self.logger.info("Closing LM...") # Shutdown executor self.executor.shutdown(wait=True) # Clear GPU memory if hasattr(self, 'model') and self.model is not None: del self.model if hasattr(self, 'tokenizer') and self.tokenizer is not None: del self.tokenizer if torch.cuda.is_available(): torch.cuda.empty_cache() self.is_loaded = False self.logger.info("LM closed successfully") async def __aenter__(self): """Async context manager entry""" await self.load_model() return self async def __aexit__(self, exc_type, exc_val, exc_tb): """Async context manager exit""" await self.close()5 unmodified lines6789101112 unmodified lines24252627282930129 unmodified lines1601611621631641651661671681691701711721731741751764 unmodified lines18118218318418518635 unmodified lines2222232242255 unmodified lines# Vector storesfrom langchain_community.vectorstores import Chroma, FAISS, Pinecone# Retriever basefrom langchain_core.vectorstores import VectorStoreRetriever12 unmodified lineslogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)class LangChainRetriever(BaseRetriever):"""LangChain-based retriever with multiple format support"""129 unmodified linesexcept Exception as e:logger.error(f"Error adding documents: {str(e)}")return Falseasync def _update_bm25_retriever(self, documents: List[Document]):try:self.bm25_retriever = BM25Retriever.from_documents(documents)self.retriever = ContextualCompressionRetriever(base_compressor=None, # Optional: add compressor like CohereRerank or LLM-basedbase_retriever=self.bm25_retriever # Example: use BM25 as base, can combine)except Exception as e:logger.error(f"Error updating BM25 retriever: {str(e)}")async def retrieve(self, query: str, k: int = 5) -> RetrievalResult:try:import time4 unmodified linesNone, self.retriever.get_relevant_documents, query)retrieved_docs = retrieved_docs[:k]scores = [0.9 - (i * 0.1) for i in range(len(retrieved_docs))]retrieval_time = time.time() - start_time35 unmodified linesreturn list(self.processed_documents.values())def get_supported_formats(self) -> List[str]:return self.document_loader.get_supported_extensions()5 unmodified lines678910111212 unmodified lines252627282930129 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921934 unmodified lines19819920020120220320435 unmodified lines2402412422435 unmodified lines# Vector storesfrom langchain_community.vectorstores import Chroma, FAISS, Pineconefrom langchain.retrievers import EnsembleRetriever# Retriever basefrom langchain_core.vectorstores import VectorStoreRetriever12 unmodified lineslogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)class LangChainRetriever(BaseRetriever):"""LangChain-based retriever with multiple format support"""129 unmodified linesexcept Exception as e:logger.error(f"Error adding documents: {str(e)}")return Falseasync def _update_bm25_retriever(self, documents: List[Document]):try:# Create BM25 retriever from documentsself.bm25_retriever = BM25Retriever.from_documents(documents)self.bm25_retriever.k = 10 # Set number of documents to retrieve# For hybrid search, you have several options:# Option 1: Use only BM25 retriever (simplest fix)self.retriever = self.bm25_retrievervector_retriever = VectorStoreRetriever(vectorstore=self.vectorstore,search_kwargs={"k": 10})self.retriever = EnsembleRetriever(retrievers=[vector_retriever, self.bm25_retriever],weights=[0.5, 0.5] # Equal weight to both retrievers)except Exception as e:logger.error(f"Error updating BM25 retriever: {str(e)}")# Fallback to vector retriever onlyself.retriever = VectorStoreRetriever(vectorstore=self.vectorstore,search_kwargs={"k": 10})async def retrieve(self, query: str, k: int = 5) -> RetrievalResult:try:import time4 unmodified linesNone, self.retriever.get_relevant_documents, query)retrieved_docs = retrieved_docs[:k]scores = [0.9 - (i * 0.1) for i in range(len(retrieved_docs))]retrieval_time = time.time() - start_time35 unmodified linesreturn list(self.processed_documents.values())def get_supported_formats(self) -> List[str]:return self.document_loader.get_supported_extensions()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364import fastapifrom fastapi.middleware.cors import CORSMiddleware
from fastrtc import ReplyOnPause, Stream, AlgoOptions, SileroVadOptions, get_cloudflare_turn_credentials_async, get_cloudflare_turn_credentialsfrom fastrtc.utils import audio_to_int16from openai import OpenAIfrom elevenlabs.client import ElevenLabsfrom dotenv import load_dotenvfrom tts.audio_edge_tts import EdgeTTSfrom rag import document_retrieverimport loggingimport timeimport platformimport socketimport osimport numpy as npimport ioimport waveimport asyncioimport librosafrom pydub import AudioSegment# from stt.whisper_stt import WhisperSTTfrom collections import dequeimport torchimport torchaudio.transforms as Timport asyncioimport concurrent.futuresimport threadingfrom config.constant import HF_TOKENimport threadingimport refrom openai import OpenAIfrom langchain_core.documents import Document
from rag import ddgs# Load .envload_dotenv()logging.basicConfig(level=logging.INFO)
class RTCHandler: def __init__(self, openai_client: OpenAI, whisper_stt = None, edge_tts : EdgeTTS = None):
"""Initialize RTC handler with OpenAI, ElevenLabs, and EdgeTTS""" self.whisper_stt = whisper_stt self.edge_tts = edge_tts self.prompt = "" self.sys_prompt = """ Kamu adalah customer service yang berbahasa Indonesia dengan baik sopan, santun, tapi santai pembawaannya. Kamu bisa menjelaskan sesuatu secara baik dan membimbing customer dalam menghadapi masalah yang ada!
Kamu akan menjawab customer dengan media call /telepon jadi anda harus memberikan respon seperlunya saja Tidak kepanjanngan, dan sangat jelas,
Tidak lebih dari 50 kata. """ self.openai_client = openai_client self.messages = [ { "role": "system", "content": self.sys_prompt } ] self.full_response = "" self.stream = None self.app = None
self._setup_webrtc_ip()
def _setup_webrtc_ip(self): """Setup WebRTC IP for Windows""" if platform.system() == 'Windows': s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('8.8.8.8', 80)) local_ip = s.getsockname()[0] except Exception: local_ip = '127.0.0.1' finally: s.close() os.environ['WEBRTC_IP'] = local_ip
def audio_to_bytes(self, audio_tuple, sample_rate=24000) -> io.BufferedReader: sr, audio_data = audio_tuple audio_int16 = audio_to_int16(audio_tuple)
buffer = io.BytesIO() with wave.open(buffer, "wb") as wf: wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(sr) wf.writeframes(audio_int16.tobytes()) buffer.seek(0) buffer.name = "audio.wav" return buffer def echo(self, audio): """Process audio input and generate audio response - Optimized version""" try: stt_time = time.time() logging.info("Performing STT")
# transcription = self.whisper_stt.transcribe(self.audio_to_bytes(audio)) transcription = self.openai_client.audio.transcriptions.create( model="whisper-1", file=self.audio_to_bytes(audio), language="id" ) self.prompt = transcription.text if self.prompt == "": logging.info("STT returned empty string") return logging.info(f"STT response: {transcription}") logging.info(f"STT took {time.time() - stt_time} seconds")
llm_time = time.time() self.full_response = ""
# Single async function to handle both text streaming and audio generation async def stream_text_to_audio(): # self.prompt = "Perhitungan BPJS" retrieval_result = await document_retriever.retrieve(query = self.prompt) contexts = "" search_results = [] async for result in ddgs.search(self.prompt, max_results=5): # self.logger.info(f"Processing SEO Result: {result[:100]}...") doc = Document( page_content=result, metadata={"source": "internet_search", "query": self.prompt} ) print(doc) search_results.append(doc) await document_retriever.add_documents([doc])
i = 1 for ctx in retrieval_result.documents: contexts += f"{i}. {ctx.page_content}" + "\n" print("Retrieved Contexts :", contexts) self.messages.append({"role": "user", "content": f""" Dari Konteks yang diberikan (jika diperlukan) : {contexts}
Berikan jawaban atas pertanyaan yang diberikan : {self.prompt} """}) response = self.openai_client.chat.completions.create( model="gpt-3.5-turbo", messages=self.messages, max_tokens=200, stream=True ) chunk_size = 1024 no_buffer = 0 text_buffer = "" for stream_data in response: print(stream_data.choices[0].delta.content) if stream_data.choices[0].finish_reason == "stop": if text_buffer: # Yield sisa text yield text_buffer break if stream_data.choices[0].delta.content: chunk = stream_data.choices[0].delta.content self.full_response += chunk text_buffer += chunk # Generate audio immediately for each text chunk if re.search(r'[.,?;!]', chunk): try: audio_buffer_gen = await self.edge_tts.generate_audio_buffer(text_buffer) audio_buffer = audio_buffer_gen[0] audio_buffer.seek(0) # Convert MP3 to PCM audio_segment = AudioSegment.from_file(audio_buffer, format="mp3") samples = np.array(audio_segment.get_array_of_samples()).astype(np.float32) / (2 ** 15) # Handle stereo to mono if audio_segment.channels == 2: samples = samples.reshape((-1, 2)).mean(axis=1) # # Resample to 24kHz # resampled = librosa.resample(samples, orig_sr=audio_segment.frame_rate, target_sr=24000) import torch import torchaudio # Check if CUDA is available device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Convert numpy array to torch tensor and move to GPU audio_tensor = torch.from_numpy(samples).unsqueeze(0).to(device) # Add batch dimension and move to GPU # Create resampler and move to GPU resampler = torchaudio.transforms.Resample( orig_freq=audio_segment.frame_rate, new_freq=24000 ).to(device) # Apply resampling on GPU resampled_tensor = resampler(audio_tensor) # Convert back to numpy (move to CPU first) resampled = resampled_tensor.squeeze(0).cpu().numpy() # Yield audio chunks for i in range(0, len(resampled), chunk_size): yield (24000, resampled[i:i + chunk_size]) no_buffer = 0 text_buffer = "" except Exception as e: logging.error(f"TTS generation failed for chunk: {e}") continue # elif stream_data["type"] == "metadata": # setup_time = stream_data['data']['setup_time'] # print(f"\nSetup completed in {setup_time:.2f}s") # elif stream_data["type"] == "complete": # total_time = stream_data['data']['total_time'] # print(f"\nTotal time: {total_time:.2f}s") # break
# Run the single async function loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: async_gen = stream_text_to_audio() while True: try: chunk = loop.run_until_complete(async_gen.__anext__()) yield chunk except StopAsyncIteration: break finally: loop.close()
self.messages.append({"role": "assistant", "content": self.full_response + " "}) logging.info(f"LLM response: {self.full_response}") logging.info(f"LLM took {time.time() - llm_time} seconds")
except Exception as e: logging.error(f"Error in echo function: {e}") error_audio = np.zeros(24000, dtype=np.float32) yield (24000, error_audio) def reset_conversation(self): logging.info("Resetting chat") self.messages = [{"role": "system", "content": self.sys_prompt}] self.full_response = ""
def create_stream(self): try: async def get_credentials(): return await get_cloudflare_turn_credentials_async(hf_token=HF_TOKEN) self.stream = Stream( rtc_configuration=get_credentials, server_rtc_configuration=get_cloudflare_turn_credentials(ttl=360_000), handler = ReplyOnPause( self.echo, algo_options=AlgoOptions( audio_chunk_duration=0.5, started_talking_threshold=0.1, speech_threshold=0.03 ), model_options=SileroVadOptions( threshold=0.90, min_speech_duration_ms=250, min_silence_duration_ms=2000, speech_pad_ms=400, max_speech_duration_s=15 ) ), modality="audio", mode="send-receive" ) return self.stream except Exception as e: logging.error(f"Error creating stream: {e}") raise
def create_fastapi_app(self): try: self.app = fastapi.FastAPI() self.app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
if not self.stream: self.create_stream() self.stream.mount(self.app)
@self.app.get("/reset") async def reset(): try: self.reset_conversation() return {"status": "success"} except Exception as e: logging.error(f"Error in reset endpoint: {e}") return {"status": "error", "message": str(e)}
@self.app.get("/status") async def status(): try: return { "status": "running", "messages_count": len(self.messages), "last_response": self.full_response } except Exception as e: logging.error(f"Error in status endpoint: {e}") return {"status": "error", "message": str(e)}
return self.app except Exception as e: logging.error(f"Error creating FastAPI app: {e}") raise
def start_server(self, host: str = "0.0.0.0", port: int = 7860): import uvicorn if not self.app: self.create_fastapi_app() logging.info(f"Starting server on {host}:{port}") try: uvicorn.run(self.app, host=host, port=port, log_level="info") except Exception as e: logging.error(f"Error starting server: {e}") raise def launch_ui(self, browser: bool = True): try: if not self.stream: self.create_stream() if not self.app: self.create_fastapi_app() logging.info("Launching RTC UI...") self.stream.ui.launch(self.app, server_name="0.0.0.0", server_port=7860, ) except Exception as e: logging.error(f"Error launching UI: {e}") raise
def get_conversation_history(self): return self.messages.copy()
def set_system_prompt(self, new_prompt: str): self.sys_prompt = new_prompt self.messages[0] = {"role": "system", "content": new_prompt}
def get_last_response(self): return self.full_response12345678910111213148 unmodified lines23242526272829303132333435363738394041423 unmodified lines464748495051524 unmodified lines57585960616263from rag.retriever.retriever_types import *from rag.pipeline.qwen_llm import QwenLLM, QwenConfigimport warningswarnings.filterwarnings("ignore")async def test_qwen_llm():print(" ===== Testing QWEN LLM ==== ")"""Example usage of async QwenLLM"""config = QwenConfig(temperature=0.5,max_length=512,generation_timeout=308 unmodified lines)# Using async context managerasync with QwenLLM(config) as llm:await test_qwen_single_generation(llm)await test_qwen_single_rag_generation(llm, contexts)await test_qwen_multiple_template_rag_generation(llm, contexts)await test_qwen_batch_generation(llm, contexts)print(" ===== Testing LLM DONE ==== ")async def test_qwen_single_generation(llm : QwenLLM):print(" * Test Single Generation * ")response = await llm.generate("Jelaskan tentang AI")print(f"Response: {response}")print(" * Test Single Generation Done * ")async def test_qwen_single_rag_generation(llm : QwenLLM, ctx : RetrievalResult):print(" * Test Single RAG Generation * ")rag_response = await llm.rag_generate(question="Apa itu AI dan machine learning?",3 unmodified linesprint(f"RAG Response: {rag_response}")print(" * Test Single RAG Generation Done * ")async def test_qwen_multiple_template_rag_generation(llm : QwenLLM,ctx : RetrievalResult):print(" * Test Multiple Template Generation * ")multi_responses = await llm.multi_template_generate(question="Apa itu AI?",4 unmodified linesprint(" * Test Multiple Template Generation Done* ")async def test_qwen_batch_generation(llm : QwenLLM, ctx : RetrievalResult):print(" * Test Batch Generation * ")batch_responses = await llm.batch_generate(["Jelaskan tentang Python",12345678910111213148 unmodified lines23242526272829303132333435363738394041423 unmodified lines464748495051524 unmodified lines57585960616263from rag.retriever.retriever_types import *from rag.pipeline.language_model import LM, LMConfigimport warningswarnings.filterwarnings("ignore")async def test_language_model():print(" ===== Testing QWEN LLM ==== ")"""Example usage of async LM"""config = LMConfig(temperature=0.5,max_length=512,generation_timeout=308 unmodified lines)# Using async context managerasync with LM(config) as llm:await test_qwen_single_generation(llm)await test_qwen_single_rag_generation(llm, contexts)await test_qwen_multiple_template_rag_generation(llm, contexts)await test_qwen_batch_generation(llm, contexts)print(" ===== Testing LLM DONE ==== ")async def test_qwen_single_generation(llm : LM):print(" * Test Single Generation * ")response = await llm.generate("Jelaskan tentang AI")print(f"Response: {response}")print(" * Test Single Generation Done * ")async def test_qwen_single_rag_generation(llm : LM, ctx : RetrievalResult):print(" * Test Single RAG Generation * ")rag_response = await llm.rag_generate(question="Apa itu AI dan machine learning?",3 unmodified linesprint(f"RAG Response: {rag_response}")print(" * Test Single RAG Generation Done * ")async def test_qwen_multiple_template_rag_generation(llm : LM,ctx : RetrievalResult):print(" * Test Multiple Template Generation * ")multi_responses = await llm.multi_template_generate(question="Apa itu AI?",4 unmodified linesprint(" * Test Multiple Template Generation Done* ")async def test_qwen_batch_generation(llm : LM, ctx : RetrievalResult):print(" * Test Batch Generation * ")batch_responses = await llm.batch_generate(["Jelaskan tentang Python",
12345678910111213from tests.inference_test import test_inferenceimport warningswarnings.filterwarnings("ignore")import asynciodef run_test():try:# await test_document_retriever()# await test_qwen_llm()asyncio.run(test_inference())except Exception as e:print(e)1234567891011121314from tests.inference_test import test_inferencefrom huggingface_hub import loginlogin(new_session=False)import warningswarnings.filterwarnings("ignore")import asynciodef run_test():try:# await test_document_retriever()# await test_language_model()test_inference()except Exception as e:print(e)
12345678# from tests.document_retriever_test import test_document_retriever# from tests.document_retriever_test import test_document_retriever# from tests.qwen_llm_test import test_qwen_llm# from tests.inference_test import test_inferencefrom tests.rtc_test import test_rtcimport warningswarnings.filterwarnings("ignore")123from tests.rtc_test import test_rtcimport warningswarnings.filterwarnings("ignore")
12345678910111213141516174 unmodified lines2223242526272829303132333435363738394041424344454647484950from rag.pipeline.qwen_llm import QwenLLM, QwenConfigfrom rag.retriever.langchain_retriever import LangChainRetrieverfrom rag.inference.inferencer import Inferencer, InferencerConfigconfig = QwenConfig(temperature=0.3,max_length=512,generation_timeout=30,repetition_penalty=1.1,max_workers = 1,do_sample = True,)llm = QwenLLM(config = config)4 unmodified lines)document_retriever = LangChainRetriever(embedding_model="all-MiniLM-L6-v2",vectorstore_type="chroma",vectorstore_path="./vectorstore",use_hybrid_search=True,chunk_size=1000,chunk_overlap=200)inferencer = Inferencer(model=llm,retriever=document_retriever,reranker=None,config=inferencer_config)async def get_response(question):result = await inferencer.infer(question, "rag_response")return resultasync def get_stream_response(question):async for item in inferencer.infer_stream(query = question,enable_reranking=False,template_type="main_template",k=3):print("Stream Response :", item)yield item12345678910111213141516171819202122232425262728293031323334353637383940414243444 unmodified lines495051525354555657585960616263646566676869707172737475767778798081828384858687888990from rag.pipeline.language_model import LM, LMConfigfrom rag.retriever.langchain_retriever import LangChainRetrieverfrom rag.inference.inferencer import Inferencer, InferencerConfigfrom rag.agents.customer_service_agent import CSAgentfrom rag.agents.query_maker_agent import QueryMakerAgentfrom langchain_core.documents import Documentfrom rag.web_search.duckduckgo_search import DuckDuckGoSearchfrom rag.chat_template import get_chat_templatefrom transformers import BitsAndBytesConfigimport torchimport loggingimport syslogging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s() - %(message)s',handlers=[logging.FileHandler('app.log'),logging.StreamHandler(sys.stdout)])bnb = BitsAndBytesConfig(load_in_4bit=True, # Enable 4-bit quantizationbnb_4bit_use_double_quant=True, # Use double quantizationbnb_4bit_quant_type="nf4", # Use NF4 quantizationbnb_4bit_compute_dtype=torch.bfloat16, # Compute dtype for 4bit base models)config = LMConfig(model_name = "Qwen/Qwen2.5-1.5B-Instruct",temperature=0.3,max_length=512,generation_timeout=100,repetition_penalty=1.1,max_workers = 2,quantization_config = bnb)llm = LM(config = config)4 unmodified lines)document_retriever = LangChainRetriever(embedding_model="sentence-transformers/all-MiniLM-L6-v2",vectorstore_type="chroma",vectorstore_path="vectorstore/",use_hybrid_search=True,chunk_size=1000,chunk_overlap=200)ddgs = DuckDuckGoSearch()cs_inferencer = Inferencer(model=llm,retriever=document_retriever,# search_engine = ddgs,reranker=None,config=inferencer_config)query_maker_inferencer = Inferencer(model=llm,config=inferencer_config)cs_agent = CSAgent(inferencer = cs_inferencer,prompt_template = get_chat_template("customer_service"))query_maker_chat_template = get_chat_template("query_maker")query_maker_chat_template[1]["content"] = """{question}"""query_maker_agent = QueryMakerAgent(inferencer = query_maker_inferencer,prompt_template = query_maker_chat_template)
12345622 unmodified lines2930313233343536373839404142431 unmodified line45464748495034 unmodified lines858687888990201 unmodified lines29229329429529629729822 unmodified lines32132232332432532632732834 unmodified lines36336436536636736836919 unmodified lines389390391392393394395396from rag.retriever.langchain_retriever import LangChainRetrieverfrom rag.pipeline.qwen_llm import QwenLLM, QwenConfigfrom rag.retriever.retriever_types import RetrievalResult# from rag.pipeline.reranker import BGEM3Rerankerfrom typing import List, Union, Dict, Any, Optional, AsyncGeneratorimport asyncio22 unmodified lines"""def __init__(self,model: QwenLLM,retriever: LangChainRetriever,reranker=None,config: Optional[InferencerConfig] = None):"""Initialize InferencerArgs:model: QwenLLM instanceretriever: LangChainRetriever instancereranker: Reranker instance (optional)config: InferencerConfig (optional)1 unmodified lineself.model = modelself.retriever = retrieverself.reranker = rerankerself.config = config or InferencerConfig()# Setup logging34 unmodified linestry:start_time = datetime.now()contexts = await self.retriever.retrieve(query, k=k)retrieval_time = (datetime.now() - start_time).total_seconds()self.logger.info(f"Retrieved {len(contexts.documents) if hasattr(contexts, 'documents') else len(contexts)} contexts in {retrieval_time:.2f}s")201 unmodified linesyield chunkasync def infer(self,query: Union[str, List[str]],response_type: Union[List[str], str] = None,k: Optional[int] = None,enable_reranking: Optional[bool] = None,22 unmodified linestry:# Step 1: Retrieve contextsretrieved_contexts = await self.retrieve_context(main_query, k=k)# Step 2: Rerank contexts (if enabled)enable_rerank = enable_reranking if enable_reranking is not None else self.config.enable_rerankingif enable_rerank:34 unmodified linesexcept Exception as e:self.logger.error(f"Error during inference: {e}")raiseasync def infer_stream(self,query: str,k: Optional[int] = None,19 unmodified linestry:# Step 1: Retrieve contextsretrieved_contexts = await self.retrieve_context(query, k=k)# Step 2: Rerank contexts (if enabled)enable_rerank = enable_reranking if enable_reranking is not None else self.config.enable_rerankingif enable_rerank:1234567822 unmodified lines313233343536373839404142434445461 unmodified line4849505152535434 unmodified lines89909192939495201 unmodified lines29729829930030130230322 unmodified lines32632732832933033133233333433533633734 unmodified lines37237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440519 unmodified lines425426427428429430431432433434435436437438from rag.retriever.langchain_retriever import LangChainRetrieverfrom rag.pipeline.language_model import LM, LMConfigfrom rag.retriever.retriever_types import RetrievalResultfrom rag.web_search.duckduckgo_search import DuckDuckGoSearchfrom langchain_core.documents import Document# from rag.pipeline.reranker import BGEM3Rerankerfrom typing import List, Union, Dict, Any, Optional, AsyncGeneratorimport asyncio22 unmodified lines"""def __init__(self,model: LM,retriever: LangChainRetriever = None,search_engine = None,reranker=None,config: Optional[InferencerConfig] = None):"""Initialize InferencerArgs:model: LM instanceretriever: LangChainRetriever instancereranker: Reranker instance (optional)config: InferencerConfig (optional)1 unmodified lineself.model = modelself.retriever = retrieverself.reranker = rerankerself.search_engine = search_engineself.config = config or InferencerConfig()# Setup logging34 unmodified linestry:start_time = datetime.now()contexts = await self.retriever.retrieve(query, k=k)self.logger.info(f"Retrieved Contexts : {contexts}")retrieval_time = (datetime.now() - start_time).total_seconds()self.logger.info(f"Retrieved {len(contexts.documents) if hasattr(contexts, 'documents') else len(contexts)} contexts in {retrieval_time:.2f}s")201 unmodified linesyield chunkasync def infer(self,query: str,response_type: Union[List[str], str] = None,k: Optional[int] = None,enable_reranking: Optional[bool] = None,22 unmodified linestry:# Step 1: Retrieve contextsif(self.search_engine):await self.retrieve_from_search_engine(query, k = k)if(self.retriever):retrieved_contexts = await self.retrieve_context(main_query, k=k)else:retrieved_contexts = ""# Step 2: Rerank contexts (if enabled)enable_rerank = enable_reranking if enable_reranking is not None else self.config.enable_rerankingif enable_rerank:34 unmodified linesexcept Exception as e:self.logger.error(f"Error during inference: {e}")raiseasync def retrieve_from_search_engine(self, query: str, k: int = 3):"""Alternative method: Process results as they come"""from langchain_core.documents import Documentsearch_results = []try:# Process results one by one as they comeasync for result in self.search_engine.search(query, max_results=k):self.logger.info(f"Processing SEO Result: {result[:100]}...")doc = Document(page_content=result,metadata={"source": "internet_search", "query": query})search_results.append(doc)# Optionally add to retriever immediatelyawait self.retriever.add_documents([doc])self.logger.info(f"Processed {len(search_results)} search results")return search_resultsexcept Exception as e:self.logger.error(f"Error in retrieve_from_search_engine_alternative: {e}", exc_info=True)raiseasync def infer_stream(self,query: str,k: Optional[int] = None,19 unmodified linestry:# Step 1: Retrieve contextsif(self.search_engine):await self.retrieve_from_search_engine(query, k = k)if(self.retriever is not None):retrieved_contexts = await self.retrieve_context(query, k=k)else:retrieved_contexts = ""# Step 2: Rerank contexts (if enabled)enable_rerank = enable_reranking if enable_reranking is not None else self.config.enable_rerankingif enable_rerank:
16 unmodified lines17181920212223262 unmodified lines28628728828929029129229329429529629729829916 unmodified lines@dataclassclass QwenConfig:"""Konfigurasi untuk model Qwen 0.5B"""model_name: str = "Qwen/Qwen2.5-0.5B-Instruct"device: str = "cuda"torch_dtype: torch.dtype = torch.float16max_length: int = 2048262 unmodified linesformatted_template = []for cht in template_data:# print("question for template = ", question)if("{context}" in cht["content"]):cht["content"] = cht["content"].format(context=formatted_context)if("{question}" in cht["content"]):cht["content"] = cht["content"].format(question=question)formatted_template.append(cht)self.logger.info("Formatted Template", formatted_template)print("Forrmatted Template", formatted_template)16 unmodified lines17181920212223262 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932016 unmodified lines@dataclassclass QwenConfig:"""Konfigurasi untuk model Qwen 0.5B"""model_name: str = "Qwen/Qwen2.5-1.5B-Instruct"device: str = "cuda"torch_dtype: torch.dtype = torch.float16max_length: int = 2048262 unmodified linesformatted_template = []for cht in template_data:# Create a copy of the content to avoid modifying the originalcontent = cht["content"]# Format both placeholders at once to avoid KeyErrorif "{context}" in content or "{question}" in content:try:content = content.format(context=formatted_context,question=question)except KeyError as e:self.logger.error(f"Missing placeholder in template: {e}")# Fallback: format only available placeholdersif "{context}" in content:content = content.replace("{context}", formatted_context)if "{question}" in content:content = content.replace("{question}", question)# Create new dict with formatted contentformatted_chat = {"role": cht["role"],"content": content}# Copy other fields if they existif "description" in cht:formatted_chat["description"] = cht["description"]formatted_template.append(formatted_chat)self.logger.info("Formatted Template", formatted_template)print("Forrmatted Template", formatted_template)
7 unmodified lines89101112131415161718192021222324257 unmodified lines1. Selalu berikan sapaan yang ramah dan profesional2. Gunakan HANYA informasi dari knowledge base yang tersedia3. Berikan jawaban yang jelas, mudah dipahami, dan terstruktur semuanya berdasarkan konteks yang diberikan yaitu :{context}4. Jika informasi tidak tersedia, tawarkan alternatif bantuan atau arahkan ke channel yang tepat5. Gunakan bahasa yang sopan dan empati terhadap kebutuhan pelanggan6. Akhiri dengan penawaran bantuan lebih lanjut""","description": "Template dengan system prompt untuk customer service professional"},{"role" : "user","content" : """Dari konteks yang diberikan context berikan jawaban atas pertanyaan saya yaitu : {question}"""},],7 unmodified lines891011121314151617181920212223242526277 unmodified lines1. Selalu berikan sapaan yang ramah dan profesional2. Gunakan HANYA informasi dari knowledge base yang tersedia3. Berikan jawaban yang jelas, mudah dipahami, dan terstruktur semuanya berdasarkan konteks yang diberikan user.4. Jika informasi tidak tersedia, tawarkan alternatif bantuan atau arahkan ke channel yang tepat5. Gunakan bahasa yang sopan dan empati terhadap kebutuhan pelanggan6. Akhiri dengan penawaran bantuan lebih lanjut""","description": "Template dengan system prompt untuk customer service professional"},{"role" : "user","content" : """Dari konteks yang diberikan : {context}berikan jawaban atas pertanyaan saya yaitu : {question}"""},],
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142from ddgs import DDGSfrom langchain_community.document_loaders import AsyncChromiumLoaderfrom langchain_community.document_transformers import BeautifulSoupTransformerimport reimport loggingfrom typing import AsyncGenerator, List
class DuckDuckGoSearch: def __init__(self, html_loader: AsyncChromiumLoader = None, html_parser = None): # Initialize dengan default values jika tidak diberikan self.html_loader = html_loader or AsyncChromiumLoader([]) self.html_parser = html_parser or BeautifulSoupTransformer() self.logger = logging.getLogger("ddgs_logger") async def get_page(self, urls: List[str]): """Get page content from URLs - returns list of documents""" try: self.html_loader.urls = urls html = await self.html_loader.aload() # This returns a LIST self.logger.info(f"search engine aload result: {len(html)} documents loaded") docs_transformed = self.html_parser.transform_documents( html, tags_to_extract=["p"], remove_unwanted_tags=["a"] ) return docs_transformed # Returns LIST of documents except Exception as e: self.logger.error(f"Error loading pages: {e}", exc_info=True) return [] # Return empty list on error def truncate(self, text: str, max_words: int = 400) -> str: """Truncate text to specified number of words""" if not text: return "" words = text.split() if len(words) <= max_words: return text truncated = " ".join(words[:max_words]) return truncated + "..." if len(words) > max_words else truncated async def search(self, query: str, max_results: int = 5) -> AsyncGenerator[str, None]: """ Search and yield page contents one by one FIXED VERSION: Properly handle async iteration """ try: self.logger.info(f"Searching for: {query} (max_results: {max_results})") # Step 1: Get search results from DDGS (regular iterator) results = DDGS().text(query, max_results=max_results) urls = [] # Step 2: Extract URLs using regular for loop (NOT async for) for result in results: # ← FIXED: Regular for loop url = result.get('href') if url: urls.append(url) self.logger.info(f"Found {len(urls)} URLs to process") if not urls: self.logger.warning("No URLs found from search results") return # Step 3: Get page content (await the coroutine first) docs = await self.get_page(urls) # ← FIXED: Await first, get list # Step 4: Process documents using regular for loop (NOT async for) for doc in docs: # ← FIXED: Regular for loop on list try: if hasattr(doc, 'page_content') and doc.page_content: # Clean up text page_text = re.sub(r"\n\n+", "\n", doc.page_content) page_text = page_text.strip() if page_text: # Only yield if there's actual content text = self.truncate(page_text) yield text # Yield makes this an async generator except Exception as e: self.logger.error(f"Error processing document: {e}") continue except Exception as e: self.logger.error(f"Error in search method: {e}", exc_info=True) # Don't re-raise, just log and return (generator will be empty) async def search_with_metadata(self, query: str, max_results: int = 5) -> AsyncGenerator[dict, None]: """ Alternative method that yields dictionaries with metadata """ try: results = DDGS().text(query, max_results=max_results) urls_and_titles = [] # Collect URLs and titles for result in results: url = result.get('href') title = result.get('title', 'No title') if url: urls_and_titles.append({'url': url, 'title': title}) if not urls_and_titles: return # Get page content urls = [item['url'] for item in urls_and_titles] docs = await self.get_page(urls) # Process and yield with metadata for i, doc in enumerate(docs): try: if hasattr(doc, 'page_content') and doc.page_content: page_text = re.sub(r"\n\n+", "\n", doc.page_content) page_text = page_text.strip() if page_text: text = self.truncate(page_text) # Get metadata if available metadata = {} if i < len(urls_and_titles): metadata = urls_and_titles[i] yield { 'content': text, 'url': metadata.get('url', 'Unknown'), 'title': metadata.get('title', 'No title'), 'word_count': len(text.split()) } except Exception as e: self.logger.error(f"Error processing document {i}: {e}") continue except Exception as e: self.logger.error(f"Error in search_with_metadata: {e}", exc_info=True)1 unmodified line234567891011121 unmodified linefrom elevenlabs.client import ElevenLabsfrom tts.audio_edge_tts import EdgeTTSfrom config.constant import OPENAI_API_KEY, ELEVENLABS_API_KEYfrom rtc.rtc_call import RTCHandlerfrom stt.whisper_stt import WhisperSTTwhisper_stt = WhisperSTT("turbo")edge_tts = EdgeTTS("id-ID-ArdiNeural", "+0%", "+0%")rtc_handler = RTCHandler(whisper_stt, edge_tts)def handle_rtc():1 unmodified line2345678910111213141 unmodified linefrom elevenlabs.client import ElevenLabsfrom tts.audio_edge_tts import EdgeTTSfrom config.constant import OPENAI_API_KEY, ELEVENLABS_API_KEY# from rtc.rtc_call import RTCHandlerfrom rtc.rtc_call import RTCHandlerfrom stt.whisper_stt import WhisperSTTwhisper_stt = WhisperSTT(model_size = "base", device = "cuda")edge_tts = EdgeTTS("id-ID-ArdiNeural", "+0%", "+0%")openai_client = OpenAI(api_key = OPENAI_API_KEY)rtc_handler = RTCHandler(whisper_stt, edge_tts)def handle_rtc():
space/README.md-1
space/space/space/Dockerfile+17-29
space/space/space/space/space/space/space/README.md-18
space/space/space/space/space/space/space/space/space/README.md+108-18
space/space/space/space/space/space/space/space/space/data/prompt_template/customer_service.txt+10-10
space/space/space/space/space/space/space/space/space/main.py+11-2
space/space/space/space/space/space/space/space/space/space/space/README.md-2
space/space/space/space/space/space/space/space/space/space/space/space/space/README.md+1-1
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/README.md+8-3
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/data/prompt_template/customer_service.txtAdded+12
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/data/prompt_template/query_maker.txtAdded+35
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/main.pyAdded+32
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/__chat__.py-2
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/__init__.py+1-1
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/pipeline/language_model.py+70-70
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/pipeline/preprocessing.py+70-70
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/base_retriever.py+4-4
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/document_loader.py+3-3
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/document_processor.py+3-3
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/langchain_retriever.py+11-11
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/web_search/duckduckgo_search.py+19-19
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rtc/rtc_call.py+15-15
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/stt/whisper_stt.py+10-10
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/tts/audio_edge_tts.py+3-3
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/__init__.py+2-2
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/__init__.pyAdded
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/agents.pyAdded+16
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/customer_service_agent.pyAdded+33
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/gpt_customer_service_agent.pyAdded+13
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/agents/query_maker_agent.pyAdded+13
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/chat_template/__init__.pyAdded+29
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/chat_template/customer_service.txtAdded+12
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/chat_template/query_maker.txtAdded+35
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/chat_template/query_maker_temp.txtAdded+30
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/inference/__init__.pyAdded
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/pipeline/language_model.pyAdded+947
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/__init__.pyAdded
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/retriever/langchain_retriever.py+25-7
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/web_search/__init__.pyAdded
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rtc/rtc_call_gpt.pyAdded+364
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/tests/qwen_llm_test.py+9-9
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/__chat__.py+4-3
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/__test__.py-5
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/app.logAdded
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/__init__.py+61-21
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/inference/inferencer.py+51-9
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/pipeline/qwen_llm.py+29-8
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/prompt_tuner/chat_template.py+6-4
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rag/web_search/duckduckgo_search.pyAdded+142
space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/space/app/rtc/__init__.py+3-1