import gradio as gr import pandas as pd from openai import OpenAI import json import os # تنظیم API کلاینت با متغیر محیطی api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError("OPENAI_API_KEY در متغیرهای محیطی تنظیم نشده است.") client = OpenAI(api_key=api_key) # متغیرهای سراسری iteration_count = 0 iteration_history = "" prompt_output = "" knowledge_base_output = "" faq_output = "" business_info = None product_info = None # پرامپت مادر با جزئیات کامل mother_prompt = """ You are the Nova System, an innovative problem-solving approach implemented by a dynamic consortium of virtual experts, each serving a distinct role. Your goal is to assist the user in generating high-quality prompts, a comprehensive knowledge base, and an automatically generated Frequently Asked Questions (FAQ) section for chatbots. **Nova System Process:** The Nova System process is iterative and cyclical, involving the following key stages: 1. **Receiving and Processing User Information Forms:** Process the information from the Business Information Form and Product/Service Information Form provided by the user. 2. **Assigning Expert Roles:** - **Discussion Continuity Expert (DCE):** Manage and guide the process, provide instructions, summarize progress, and define goals for each iteration. - **Prompt Engineering Expert (PEE):** Generate initial drafts of: - Chatbot prompt in English with sections: Persona, Tone, Guidelines, About Us, Responses to Common Questions, Contact Information, Additional Guidelines. Tone must be friendly, casual, concise (under 100 words per response unless necessary), and use loving emojis. - Knowledge base in JSON-like format with fields: name, description, variants (size and price), objectID. - FAQ in JSON-like format with categories, topics, questions, and short, friendly answers. - **Critical Analysis Expert (CAE):** Review and critique outputs, ensuring they match the desired tone, structure, and detail level, providing improvement suggestions. 3. **Iterations and Expert Dialogue:** Conduct iterations with the following steps in Persian (Farsi): - **DCE's Instructions:** Provide instructions for PEE and CAE. - **PEE Output:** Generate or refine chatbot prompt, knowledge base, and FAQ. - **CAE Analysis:** Critique PEE outputs and suggest improvements. - **DCE Summary:** Summarize progress and set goals for the next iteration. 4. **Iterate the Process:** Continue until high-quality outputs are achieved. 5. **Present the Final Outputs:** - Final prompt in English with specified sections. - Knowledge base in JSON-like format. - FAQ in JSON-like format. - Separate each section with exactly "---" (three dashes) and nothing else. **Do not add any extra text before, after, or between sections (e.g., no "Here is the output", no headings like "### Prompt:", no explanations).** Conduct all dialogues in Persian, but output the final prompt in English and knowledge base/FAQ in JSON-like format. Ensure the tone is friendly, casual, and uses loving emojis where appropriate. """ # تابع برای تبدیل داده‌ها به فرمت JSON-serializable def convert_to_serializable(obj): if isinstance(obj, pd.Timestamp): return obj.isoformat() elif isinstance(obj, list): return [convert_to_serializable(item) for item in obj] elif isinstance(obj, dict): return {key: convert_to_serializable(value) for key, value in obj.items()} return obj # تابع برای اعتبارسنجی و اصلاح خروجی def validate_and_fix_output(output): print("خروجی خام مدل:", output) # چاپ خروجی خام برای دیباگ parts = output.split("---") parts = [part.strip() for part in parts if part.strip()] # حذف بخش‌های خالی print("بخش‌های جدا شده:", parts) # چاپ بخش‌ها برای دیباگ # اگه متن اضافی قبل از اولین --- بود، اون رو نادیده بگیر if len(parts) > 3 and not parts[0].startswith("**Persona:") and not parts[0].startswith("["): parts = parts[1:] # متن اضافی رو حذف کن و از بخش بعدی شروع کن # تخصیص بخش‌ها بر اساس ترتیب prompt_part = parts[0] if len(parts) > 0 else "پرامپت تولید نشد 😔" kb_part = parts[1] if len(parts) > 1 else "پایگاه دانش تولید نشد 😕" faq_part = parts[2] if len(parts) > 2 else "FAQ تولید نشد 🥳" return [prompt_part, kb_part, faq_part] # تابع برای خوندن و پردازش فایل‌های اکسل def process_excel_files(file1, file2): global business_info, product_info business_info = pd.read_excel(file1.name).to_dict(orient="records")[0] product_info = pd.read_excel(file2.name).to_dict(orient="records") return business_info, product_info # تابع شروع فرایند def start_process(file1, file2): global iteration_count, iteration_history, business_info, product_info iteration_count = 1 iteration_history = "سلام عزیزم! من سیستم نوا هستم، یه دستیار باحال برای ساخت پرامپت، پایگاه دانش و FAQ 😍 فرایند شروع شد!\n" # پردازش فایل‌ها business_info, product_info = process_excel_files(file1, file2) business_info_serializable = convert_to_serializable(business_info) product_info_serializable = convert_to_serializable(product_info) # دستورات DCE dce_instructions = f"iteration {iteration_count}: لطفاً یه پرامپت به انگلیسی (با بخش‌های Persona, Tone, Guidelines, About Us و غیره)، پایگاه دانش به فرمت JSON (با name, description, variants, objectID) و FAQ به فرمت JSON (با دسته‌بندی و جواب‌های کوتاه و دوستانه) بسازید." iteration_history += f"**دستورات DCE:** {dce_instructions}\n" # تولید توسط PEE pee_prompt = f""" {mother_prompt} شما Prompt Engineering Expert (PEE) هستید. بر اساس اطلاعات زیر، پرامپت، پایگاه دانش و FAQ رو بسازید: اطلاعات کسب‌وکار: {json.dumps(business_info_serializable, ensure_ascii=False)} اطلاعات محصولات: {json.dumps(product_info_serializable, ensure_ascii=False)} {dce_instructions} خروجی رو با --- جدا کنید. """ pee_response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "system", "content": pee_prompt}] ) pee_output = pee_response.choices[0].message.content iteration_history += f"**خروجی PEE:**\n{pee_output}\n" # نقد توسط CAE cae_prompt = f""" {mother_prompt} شما Critical Analysis Expert (CAE) هستید. خروجی PEE رو نقد کنید، مطمئن شید لحن دوستانه‌ست، ساختار JSON درسته و جزئیات کافی داره: خروجی PEE:\n{pee_output} """ cae_response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "system", "content": cae_prompt}] ) cae_output = cae_response.choices[0].message.content iteration_history += f"**نقد CAE:**\n{cae_output}\n" # جمع‌بندی DCE dce_summary = f""" **جمع‌بندی DCE:** iteration {iteration_count} تموم شد 🌟 **وضعیت فعلی:** پرامپت، پایگاه دانش و FAQ اولیه ساخته شدن. **اهداف بعدی:** #G-{iteration_count}-1: بهبود لحن و جزئیات بر اساس نقد CAE. #G-{iteration_count}-2: تکمیل فرمت JSON. **پایان iteration {iteration_count}** """ iteration_history += dce_summary return iteration_history, "", "", "" # تابع ادامه Iteration def continue_iteration(): global iteration_count, iteration_history iteration_count += 1 business_info_serializable = convert_to_serializable(business_info) product_info_serializable = convert_to_serializable(product_info) # دستورات DCE dce_instructions = f"iteration {iteration_count}: لطفاً خروجی قبلی رو بر اساس نقد CAE بهبود بدید، لحن رو دوستانه‌تر کنید و فرمت JSON رو دقیق‌تر کنید." iteration_history += f"**دستورات DCE:** {dce_instructions}\n" # تولید توسط PEE pee_prompt = f""" {mother_prompt} شما Prompt Engineering Expert (PEE) هستید. خروجی قبلی رو بر اساس نقد CAE بهبود بدید: اطلاعات کسب‌وکار: {json.dumps(business_info_serializable, ensure_ascii=False)} اطلاعات محصولات: {json.dumps(product_info_serializable, ensure_ascii=False)} تاریخچه iteration قبلی:\n{iteration_history} {dce_instructions} خروجی رو با --- جدا کنید. """ pee_response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "system", "content": pee_prompt}] ) pee_output = pee_response.choices[0].message.content iteration_history += f"**خروجی PEE:**\n{pee_output}\n" # نقد توسط CAE cae_prompt = f""" {mother_prompt} شما Critical Analysis Expert (CAE) هستید. خروجی جدید PEE رو نقد کنید و مطمئن شید لحن دوستانه‌ست و فرمت JSON درسته: خروجی PEE:\n{pee_output} """ cae_response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "system", "content": cae_prompt}] ) cae_output = cae_response.choices[0].message.content iteration_history += f"**نقد CAE:**\n{cae_output}\n" # جمع‌بندی DCE dce_summary = f""" **جمع‌بندی DCE:** iteration {iteration_count} تموم شد 😊 **وضعیت فعلی:** خروجی‌ها بهبود یافتن. **اهداف بعدی:** #G-{iteration_count}-1: ادامه بهبود یا اتمام فرایند. **پایان iteration {iteration_count}** """ iteration_history += dce_summary return iteration_history, "", "", "" # تابع پایان و تولید خروجی نهایی def end_process(): global iteration_history, prompt_output, knowledge_base_output, faq_output business_info_serializable = convert_to_serializable(business_info) product_info_serializable = convert_to_serializable(product_info) # تولید خروجی نهایی final_prompt = f""" {mother_prompt} فرایند iteration‌ها تموم شده. لطفاً خروجی نهایی رو به این ترتیب تولید کنید: 1. پرامپت چت‌بات به انگلیسی با بخش‌های: - Persona - Tone - Guidelines - About Us - Responses to Common Questions - Contact Information - Additional Guidelines لحن باید دوستانه، عامیانه، کوتاه (زیر 100 کلمه) و با ایموجی‌های جذاب باشه. --- 2. پایگاه دانش به فرمت JSON-like با فیلدهای: name, description, variants (شامل size و price), objectID. برای هر محصول یا خدمت یه ورودی جدا بساز. --- 3. FAQ به فرمت JSON-like با دسته‌بندی‌ها (مثل Services, Care)، موضوعات، سوالات و جواب‌های کوتاه و دوستانه. اطلاعات کسب‌وکار: {json.dumps(business_info_serializable, ensure_ascii=False)} اطلاعات محصولات: {json.dumps(product_info_serializable, ensure_ascii=False)} تاریخچه iteration‌ها:\n{iteration_history} **هر بخش رو با دقیقاً "---" جدا کن. هیچ متن اضافی قبل، بعد یا بین بخش‌ها نذار (مثل "Here is the output" یا تیترهایی مثل "### Prompt:"). اگه هر بخش تولید نشد، به جاش یه نمونه حداقلی بساز.** """ final_response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "system", "content": final_prompt}] ) final_output = final_response.choices[0].message.content print("خروجی خام نهایی:", final_output) # چاپ خروجی خام برای دیباگ # اعتبارسنجی و جداسازی خروجی‌ها parts = validate_and_fix_output(final_output) prompt_output = parts[0] knowledge_base_output = parts[1] faq_output = parts[2] iteration_history += "\n**فرایند تموم شد و خروجی نهایی آماده‌ست! 🎉**\n" return iteration_history, prompt_output, knowledge_base_output, faq_output # رابط کاربری Gradio with gr.Blocks() as demo: gr.Markdown("# سیستم نوا 🌟") with gr.Row(): file1 = gr.File(label="فرم اطلاعات اولیه وردست") file2 = gr.File(label="فرم اطلاعات محصولات/خدمات") start_btn = gr.Button("شروع") iteration_box = gr.Textbox(label="تاریخچه Iteration", lines=10) continue_btn = gr.Button("ادامه دهید") end_btn = gr.Button("پایان") prompt_box = gr.Textbox(label="پرامپت نهایی (انگلیسی)") kb_box = gr.Textbox(label="پایگاه دانش (JSON)") faq_box = gr.Textbox(label="پرسش و پاسخ‌ها (JSON)") start_btn.click(start_process, inputs=[file1, file2], outputs=[iteration_box, prompt_box, kb_box, faq_box]) continue_btn.click(continue_iteration, inputs=[], outputs=[iteration_box, prompt_box, kb_box, faq_box]) end_btn.click(end_process, inputs=[], outputs=[iteration_box, prompt_box, kb_box, faq_box]) demo.launch()