File size: 14,036 Bytes
036a3b5
 
9c85117
036a3b5
9f7cbcd
9c85117
9f7cbcd
 
 
f35f433
9f7cbcd
9c85117
9f7cbcd
9c85117
 
 
 
 
 
 
 
3f1dfc5
9c85117
 
 
 
 
 
 
f35f433
3f1dfc5
 
 
 
949b395
f35f433
 
 
 
 
9c85117
3f1dfc5
 
949b395
 
21893ce
9c85117
3f1dfc5
9c85117
 
9f7cbcd
 
 
 
 
 
 
 
 
 
949b395
 
f988283
949b395
f988283
8ed396a
f988283
21893ce
 
 
 
 
8ed396a
 
 
f988283
 
949b395
9c85117
 
 
9f7cbcd
 
9c85117
 
 
 
 
 
3f1dfc5
9c85117
 
 
9f7cbcd
 
 
3f1dfc5
 
9c85117
 
3f1dfc5
f35f433
 
3f1dfc5
f35f433
 
 
3f1dfc5
f35f433
9c85117
 
f35f433
a9a9353
9c85117
f35f433
 
3f1dfc5
f35f433
 
3f1dfc5
f35f433
 
9c85117
 
f35f433
a9a9353
9c85117
f35f433
 
3f1dfc5
f35f433
3f1dfc5
 
 
 
 
f35f433
 
 
9c85117
 
 
 
 
 
 
 
9f7cbcd
 
 
3f1dfc5
 
9c85117
 
3f1dfc5
f35f433
 
3f1dfc5
f35f433
 
 
 
3f1dfc5
f35f433
9c85117
 
f35f433
a9a9353
9c85117
f35f433
 
3f1dfc5
f35f433
 
3f1dfc5
f35f433
 
9c85117
 
f35f433
9c85117
 
f35f433
 
3f1dfc5
f35f433
3f1dfc5
 
 
f35f433
 
 
 
9c85117
 
 
 
 
 
 
9f7cbcd
 
 
9c85117
f35f433
 
21893ce
69c690a
 
 
 
 
 
 
 
 
f988283
69c690a
f988283
69c690a
f35f433
 
 
21893ce
f35f433
9c85117
 
f35f433
9c85117
 
f988283
9c85117
949b395
 
f988283
 
 
9c85117
3f1dfc5
9c85117
 
 
 
3f1dfc5
9c85117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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()