import os import gradio as gr from openai import OpenAI # 🔒 مفتاح API من البيئة API_KEY = os.getenv("API_KEY") client = OpenAI( base_url="https://integrate.api.nvidia.com/v1", api_key=API_KEY ) # سجل المحادثة history = [] # تخزين محتوى الملفات مؤقتًا قبل إرسالها للنموذج files_contents = [] def chat_with_model(message, file=None): global history, files_contents content = message # قراءة محتوى الملف إذا تم رفعه if file: try: file_content = file.read().decode() except Exception: file_content = "<تعذر قراءة الملف>" files_contents.append(f"# محتوى الملف {file.name}:\n{file_content}") # دمج كل محتويات الملفات في رسالة واحدة if files_contents: content += "\n\n".join(files_contents) # إضافة رسالة المستخدم لسجل المحادثة history.append({"role": "user", "content": content}) # طلب النموذج completion = client.chat.completions.create( model="qwen/qwen3-coder-480b-instruct", messages=history, temperature=0, top_p=0.61, max_tokens=16384, stream=True ) response_text = "" for chunk in completion: if chunk.choices[0].delta.content is not None: response_text += chunk.choices[0].delta.content print(chunk.choices[0].delta.content, end="") # إضافة الرد لسجل المحادثة history.append({"role": "assistant", "content": response_text}) # بعد الإرسال يمكن مسح قائمة الملفات أو الاحتفاظ بها حسب الرغبة files_contents.clear() return response_text, history # واجهة Gradio with gr.Blocks() as demo: gr.Markdown("# NVIDIA Qwen3 Chat (ملفات متعددة، رسالة واحدة للنموذج)") chatbot = gr.Chatbot(type="messages") msg = gr.Textbox(label="اكتب رسالتك هنا") file_input = gr.File( label="ارفع ملف Python أو نصي (يمكن رفع أكثر من مرة)", file_types=[".py", ".txt"] ) send = gr.Button("إرسال") def handle_submit(message, file): answer, history = chat_with_model(message, file) return gr.update(value=history), "", None send.click(handle_submit, [msg, file_input], [chatbot, msg, file_input]) demo.launch()