import os from langchain.chat_models import ChatOpenAI from langchain import ConversationChain from openai import OpenAI import gradio as gr # API 키를 환경 변수로 설정 os.environ["OPENAI_API_KEY"] = os.environ.get("GPT_API_KEY") # LangChain을 위한 LLM 초기화 llm = ChatOpenAI(temperature=0, # 창의성 0으로 설정 model_name='gpt-4o-mini', # 모델명 (예: "gpt-4") ) # ConversationChain 초기화 conversation = ConversationChain(llm=llm, verbose=True) # OpenAI 클라이언트 초기화 client = OpenAI() # 챗봇 응답 함수 def chatbot_response(message, chat_history): # ConversationChain을 사용하여 응답 생성 bot_message = conversation.predict(input=message) # 채팅 히스토리에 사용자 메시지와 챗봇 응답 추가 chat_history.append((message, bot_message)) return "", chat_history # Gradio 인터페이스 생성 with gr.Blocks() as demo: # 채팅 히스토리를 저장할 컴포넌트 chatbot = gr.Chatbot(label="채팅 기록") # 사용자 입력을 받을 텍스트 박스 msg = gr.Textbox(label="메시지 입력", placeholder="여기에 메시지를 입력하고 엔터를 누르세요.") # 전송 버튼 (옵션) send_button = gr.Button("전송") # 채팅 히스토리 초기화 버튼 clear_button = gr.Button("초기화") # 엔터 키 또는 전송 버튼 클릭 시 동작 msg.submit( chatbot_response, # 응답 함수 inputs=[msg, chatbot], # 입력: 메시지와 채팅 기록 outputs=[msg, chatbot], # 출력: 메시지 박스 초기화 및 채팅 기록 업데이트 ) send_button.click( chatbot_response, # 응답 함수 inputs=[msg, chatbot], # 입력: 메시지와 채팅 기록 outputs=[msg, chatbot], # 출력: 메시지 박스 초기화 및 채팅 기록 업데이트 ) # 초기화 버튼 클릭 시 동작 clear_button.click( lambda: None, # 아무 동작도 하지 않음 inputs=None, outputs=chatbot, # 채팅 기록 초기화 queue=False, # 큐 비활성화 ) # 인터페이스 실행 demo.launch(share=True)