|
|
|
|
|
import os |
|
|
import gradio as gr |
|
|
from langchain_core.prompts import ChatPromptTemplate |
|
|
from langchain_core.output_parsers import StrOutputParser |
|
|
from langchain_openai import ChatOpenAI |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model = ChatOpenAI( |
|
|
model=”gpt-4o-mini”, |
|
|
api_key=openai_api_key, |
|
|
) |
|
|
|
|
|
|
|
|
def agent1(input_text:str): |
|
|
return f”Agent1:{input_text.upper()}” |
|
|
|
|
|
def agent2(input_from_agent1:str): |
|
|
return f”Agent2: {input_from_agent1} processed!” |
|
|
|
|
|
|
|
|
prompt_template = ChatPromptTemplate.from_template( |
|
|
“你是航空公司客服助理。” |
|
|
“用戶詢問航空資訊時, 提供法蘭克福直飛行程 (來回經濟艙NT$33,000),” |
|
|
“並建議轉機至慕尼黑。請根據以下對話回答:\n{conversation}” |
|
|
) |
|
|
|
|
|
parser = StrOutputParser() |
|
|
chain = prompt_template〡model〡parser |
|
|
|
|
|
|
|
|
Shared_context = {“latest_output”:””} |
|
|
|
|
|
|
|
|
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] |
|
|
) |
|
|
|
|
|
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}) |
|
|
|
|
|
|
|
|
with gr.Blocks(title=Multi-Agent & Chatbot”) as demo: |
|
|
gr.Markdown( |
|
|
|
|
|
with gr.Tabs(): |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
def run_agent2(input_text): |
|
|
out = agent2(input_text) |
|
|
shared_context[“latest_output”] = out |
|
|
return out |
|
|
|
|
|
btn2.click(fn=agent2, inputs=output1,outputs=output2) |
|
|
|
|
|
with gr.Tab(“牛牛機器人”): |
|
|
gr.ChatInterface( |
|
|
fn=generate_response, |
|
|
title= “Tour Inquiry Chatbot”, |
|
|
description=”詢問航班資訊, 例如訂票或轉機建議。” |
|
|
) |
|
|
|
|
|
If_name_== ”_main_”: |
|
|
demo.launch() |
|
|
|
|
|
|
|
|
|
|
|
|