import os import gradio as gr from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_openai import ChatOpenAI # 讀取API Key #openai_api_key = os.getenv(“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”) # 初始化 API 模型 model = ChatOpenAI( model=”gpt-4o-mini”, api_key=openai_api_key, ) # Multi-Agent 的簡單函數 def agent1(input_text:str): return f”Agent1:{input_text.upper()}” def agent2(input_from_agent1:str): return f”Agent2: {input_from_agent1} processed!” # LangChain prompt: 模板 prompt_template = ChatPromptTemplate.from_template( “你是航空公司客服助理。” “用戶詢問航空資訊時, 提供法蘭克福直飛行程 (來回經濟艙NT$33,000),” “並建議轉機至慕尼黑。請根據以下對話回答:\n{conversation}” ) parser = StrOutputParser() chain = prompt_template〡model〡parser #建立一個全域共享變數, 讓 Multi-Agent 的輸出能傳給 Chatbot Shared_context = {“latest_output”:””} #Chatbot 回應函數 (含歷史記憶 + shared context) def generate_response(message, history): formatted_history = “\n”.join( [f”User:{h[0]}\nBot:{h[1]}” for h in history if h[1] is not None] ) # 加入 Multi-Agent 輸出的上下文 If shared_context[“latest_output”]: formatted_history += f”\n(系統提示 : 這是來自 Multi-Agent 的資訊 {shared_context[‘latest_output’]})\n” full_input = formatted_history + f”\nUser:{message}\nBot:” return chain.invoke({“conversation”: full_input}) # Gradio 介面 with gr.Blocks(title=Multi-Agent & Chatbot”) as demo: gr.Markdown(##🐮多智能體與航班客服助理”) with gr.Tabs(): #------------Multi-Agent” 分頁 ------------ with gr.Tab(“Multi-Agent”): with gr.Row(): input1 = gr.Textbox( label = “輸入給 Agent1”, value = “農曆春節期間, 貴公司有沒有直飛到德國慕尼黑的行程?” ) with gr.Row(): btn1 = gr.Button (“執行 Agent1”) output1 = gr.Textbox(label=”Agent1 輸出”, interative=False ) with gr.Row(): btn2 = gr.Button(“執行 Agent2”) output2 = gr.Textbox(lagel=”Agent2 輸出”, interactive=False) # 按鈕綁定 btn1.click(fn=agent1, inputs=input1, outputs=output1) #Agent2 產出時, 同步更新 shared_context def run_agent2(input_text): out = agent2(input_text) shared_context[“latest_output”] = out return out btn2.click(fn=agent2, inputs=output1,outputs=output2) #------------Chatbot 分頁 ------------ with gr.Tab(“牛牛機器人”): gr.ChatInterface( fn=generate_response, title= “Tour Inquiry Chatbot”, description=”詢問航班資訊, 例如訂票或轉機建議。” ) If_name_== ”_main_”: demo.launch()