Spaces:
Running
Running
Update app.py
Browse files12 unmodified lines1314151617181920212223242526272 unmodified lines3031323334353637383940414243444546474849505152535455565758596027 unmodified lines8889909192939423 unmodified lines1181191201211221231241251265 unmodified lines1321331341351361371381391401413 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681695 unmodified lines17517617717817918018130 unmodified lines21221321421521621721821922012 unmodified linesopenai_client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))groq_client = Groq(api_key=os.getenv('groq_key'))# 模型設定OPENAI_MODELS = ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"]GROQ_MODELS = ["llama3-8b-8192", "gemma2-9b-it"]MODEL_CONFIGS = {"openai": {"gpt-3.5-turbo": {"max_tokens": 4096, "temperature": 0.7},"gpt-4": {"max_tokens": 8192, "temperature": 0.7},"gpt-4-turbo": {"max_tokens": 4096, "temperature": 0.7}},"groq": {"llama3-8b-8192": {"max_tokens": 4090, "temperature": 0.7},2 unmodified lines}def get_llm_response(prompt, provider, model):if provider == "openai":response = openai_client.chat.completions.create(model=model,messages=[{"role": "system", "content": "你是一位資深的國文作文評閱委員,請依據提供的評分規準進行評分。"},{"role": "user", "content": prompt}],**MODEL_CONFIGS["openai"][model])return response.choices[0].message.contentelse: # groqcompletion = groq_client.chat.completions.create(model=model,messages=[{"role": "system", "content": "你是一位資深的國文作文評閱委員,請依據提供的評分規準進行評分。"},{"role": "user", "content": prompt}],**MODEL_CONFIGS["groq"][model],stream=False,top_p=1,stop=None)return completion.choices[0].message.contentdef evaluate_essay(message, additional_prompt, provider, model):if not message.strip():return [], gr.Markdown("### 請輸入作文內容進行評分")27 unmodified lines{additional_prompt if additional_prompt else ''}請依三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)評分,並提供簡短評語。如果是缺考、未作答、完全文不對題或作答內容完全照抄試題,請給予0分。請按以下格式回覆:23 unmodified linesall_feedback[criterion] = feedbackfor criterion in criteria:history.append(("", all_feedback[criterion]))total_score_display = f"""# 總評分結果## 使用模型:{provider} ({model})5 unmodified linesexcept Exception as e:return [("", f"評分過程發生錯誤:{str(e)}")], gr.Markdown("### ❌ 評分失敗")# 模型選擇切換函數def update_model_choices(provider):if provider == "openai":return gr.Dropdown(choices=OPENAI_MODELS, value="gpt-3.5-turbo")else:return gr.Dropdown(choices=GROQ_MODELS, value="llama3-8b-8192")3 unmodified lines# 國文作文自動評分系統## 評分標準說明本系統採用以下四個面向進行評分:- 題旨發揮 (40%)- 資料掌握 (20%)- 結構安排 (20%)- 字句運用 (20%)評分採用三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)""")# 輸入區塊msg = gr.Textbox(label="請輸入作文內容",placeholder="在此輸入作文...",lines=6)additional_prompt = gr.Textbox(label="額外評分提示(選填)",placeholder="可輸入額外的評分要求或提示...",lines=2)# 模型選擇with gr.Row():5 unmodified linesmodel = gr.Dropdown(choices=OPENAI_MODELS,label="選擇模型",value="gpt-3.5-turbo",interactive=True)30 unmodified linesoutputs=[chatbot, score_display])clear.click(lambda: [None, None, "openai", "gpt-3.5-turbo", [], gr.Markdown("### 等待評分...")],outputs=[msg, additional_prompt, provider, model, chatbot, score_display])# 啟動應用demo.launch()12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667682 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411527 unmodified lines14314414514614714814923 unmodified lines1731741751761771781791801811821831841851861871881891901911921931945 unmodified lines2002012022032042052062072082093 unmodified lines2132142152162172182192202212222232242252262272282292302312322332342352362372385 unmodified lines24424524624724824925030 unmodified lines28128228328428528628728828929012 unmodified linesopenai_client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))groq_client = Groq(api_key=os.getenv('groq_key'))# 更新後的模型設定,包含最新的模型OPENAI_MODELS = [# GPT-4o 系列"gpt-4o", # 最新的旗艦模型"gpt-4o-2024-08-06", # 支援結構化輸出的版本"gpt-4o-mini", # 輕量快速版本"chatgpt-4o-latest", # ChatGPT使用的持續更新版本# GPT-4 Turbo 系列"gpt-4-turbo", # 最新的GPT-4 Turbo"gpt-3.5-turbo", # GPT-3.5 Turbo]GROQ_MODELS = ["llama3-8b-8192", "gemma2-9b-it"]MODEL_CONFIGS = {"openai": {# GPT-4o 系列配置"gpt-4o": {"max_tokens": 16384,"temperature": 0.7,"context_window": 128000},"gpt-4o-2024-08-06": {"max_tokens": 16384,"temperature": 0.7,"context_window": 128000},"gpt-4o-mini": {"max_tokens": 16384,"temperature": 0.7,"context_window": 128000},"chatgpt-4o-latest": {"max_tokens": 16384,"temperature": 0.7,"context_window": 128000},# GPT-4 Turbo 系列配置"gpt-4-turbo": {"max_tokens": 4096,"temperature": 0.7,"context_window": 128000},"gpt-3.5-turbo": {"max_tokens": 4096,"temperature": 0.7,"context_window": 16385}},"groq": {"llama3-8b-8192": {"max_tokens": 4090, "temperature": 0.7},2 unmodified lines}def get_llm_response(prompt, provider, model):"""獲取LLM回應的函數"""try:if provider == "openai":response = openai_client.chat.completions.create(model=model,messages=[{"role": "system", "content": """你是一位資深的國文作文評閱委員,請依據以下評分規準進行評分:1. 題旨發揮 (40%): 檢視作文是否切合題目要求、思路清晰、感發得宜、體悟深刻2. 資料掌握 (20%): 評估材料運用是否恰當、例證是否充實3. 結構安排 (20%): 審視文章結構是否完整、條理是否分明4. 字句運用 (20%): 考察遣詞造句是否精確、修辭是否優美請依三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)評分。若有缺考、未作答、完全文不對題或作答內容完全照抄試題者,則給予0分。"""},{"role": "user", "content": prompt}],temperature=MODEL_CONFIGS["openai"][model]["temperature"],max_tokens=MODEL_CONFIGS["openai"][model]["max_tokens"])return response.choices[0].message.contentelse: # groqcompletion = groq_client.chat.completions.create(model=model,messages=[{"role": "system", "content": "你是一位資深的國文作文評閱委員,請依據提供的評分規準進行評分。"},{"role": "user", "content": prompt}],**MODEL_CONFIGS["groq"][model],stream=False,top_p=1,stop=None)return completion.choices[0].message.contentexcept Exception as e:return f"評分過程發生錯誤:{str(e)}"def evaluate_essay(message, additional_prompt, provider, model):"""評估作文的主函數"""if not message.strip():return [], gr.Markdown("### 請輸入作文內容進行評分")27 unmodified lines{additional_prompt if additional_prompt else ''}請依三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)評分,並提供詳細評語。如果是缺考、未作答、完全文不對題或作答內容完全照抄試題,請給予0分。請按以下格式回覆:23 unmodified linesall_feedback[criterion] = feedback# 添加各項評分到歷史記錄for criterion in criteria:history.append(("", all_feedback[criterion]))# 生成總評total_evaluation = """### 綜合評語本作文各項得分如下:"""for criterion, details in criteria.items():total_evaluation += f"- {criterion}:{all_feedback[criterion].split('得分**:')[1].split('/')[0]}/{details['max_score']}\n"total_evaluation += f"\n### 總分:{total_score:.1f}/100"history.append(("", total_evaluation))total_score_display = f"""# 總評分結果## 使用模型:{provider} ({model})5 unmodified linesexcept Exception as e:return [("", f"評分過程發生錯誤:{str(e)}")], gr.Markdown("### ❌ 評分失敗")def update_model_choices(provider):"""更新模型選擇的函數"""if provider == "openai":return gr.Dropdown(choices=OPENAI_MODELS, value="gpt-4o")else:return gr.Dropdown(choices=GROQ_MODELS, value="llama3-8b-8192")3 unmodified lines# 國文作文自動評分系統## 評分標準說明本系統採用以下四個面向進行評分:- 題旨發揮 (40%): 檢視作文是否切合題目要求、思路清晰、感發得宜、體悟深刻- 資料掌握 (20%): 評估材料運用是否恰當、例證是否充實- 結構安排 (20%): 審視文章結構是否完整、條理是否分明- 字句運用 (20%): 考察遣詞造句是否精確、修辭是否優美評分採用三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)""")# 輸入區塊with gr.Column():msg = gr.Textbox(label="請輸入作文內容",placeholder="在此輸入作文...",lines=10)additional_prompt = gr.Textbox(label="額外評分提示(選填)",placeholder="可輸入額外的評分要求或提示...",lines=2)# 模型選擇with gr.Row():5 unmodified linesmodel = gr.Dropdown(choices=OPENAI_MODELS,label="選擇模型",value="gpt-4o",interactive=True)30 unmodified linesoutputs=[chatbot, score_display])clear.click(lambda: [None, None, "openai", "gpt-4o", [], gr.Markdown("### 等待評分...")],outputs=[msg, additional_prompt, provider, model, chatbot, score_display])# 啟動應用if __name__ == "__main__":demo.launch()
app.py+119-49