Update app.py
Browse files
app.py
CHANGED
|
@@ -11,21 +11,80 @@ load_dotenv()
|
|
| 11 |
def create_deepseek_interface():
|
| 12 |
# 환경 변수에서 API 키 가져오기
|
| 13 |
api_key = os.getenv("FW_API_KEY")
|
|
|
|
|
|
|
| 14 |
if not api_key:
|
| 15 |
print("경고: FW_API_KEY 환경 변수가 설정되지 않았습니다.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# 스트리밍 방식으로 DeepSeek API 호출 함수
|
| 18 |
-
def query_deepseek_streaming(message, history):
|
| 19 |
if not api_key:
|
| 20 |
yield history, "환경 변수 FW_API_KEY가 설정되지 않았습니다. 서버에서 환경 변수를 확인해주세요."
|
| 21 |
return
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# API 요청을 위한 대화 기록 준비
|
| 24 |
messages = []
|
| 25 |
for user, assistant in history:
|
| 26 |
messages.append({"role": "user", "content": user})
|
| 27 |
messages.append({"role": "assistant", "content": assistant})
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
# 새 사용자 메시지 추가
|
| 30 |
messages.append({"role": "user", "content": message})
|
| 31 |
|
|
@@ -105,35 +164,24 @@ def create_deepseek_interface():
|
|
| 105 |
"""
|
| 106 |
)
|
| 107 |
|
| 108 |
-
# 메인 레이아웃
|
| 109 |
with gr.Row():
|
| 110 |
-
# 사이드바 - 모델 정보
|
| 111 |
-
with gr.Column(scale=1):
|
| 112 |
-
gr.Markdown(
|
| 113 |
-
"""
|
| 114 |
-
## 📊 모델 세부 정보
|
| 115 |
-
- **모델**: DeepSeek-V3-0324
|
| 116 |
-
- **제공자**: Fireworks AI
|
| 117 |
-
- **최대 토큰**: 20,480
|
| 118 |
-
- **온도**: 0.6
|
| 119 |
-
- **기능**: 고급 언어 이해와 실시간 스트리밍 응답
|
| 120 |
-
|
| 121 |
-
> **참고**: API 키는 환경 변수(FW_API_KEY)에서 자동으로 로드됩니다.
|
| 122 |
-
"""
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
# 오류 메시지 표시
|
| 126 |
-
error_box = gr.Markdown("")
|
| 127 |
-
|
| 128 |
# 메인 콘텐츠 영역
|
| 129 |
-
with gr.Column(
|
| 130 |
-
# 채팅 인터페이스
|
| 131 |
chatbot = gr.Chatbot(
|
| 132 |
height=500,
|
| 133 |
show_label=False,
|
| 134 |
container=True
|
| 135 |
)
|
| 136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
# 입력 영역
|
| 138 |
with gr.Row():
|
| 139 |
msg = gr.Textbox(
|
|
@@ -157,11 +205,14 @@ def create_deepseek_interface():
|
|
| 157 |
],
|
| 158 |
inputs=msg
|
| 159 |
)
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
# 버튼과 기능 연결
|
| 162 |
submit.click(
|
| 163 |
query_deepseek_streaming,
|
| 164 |
-
inputs=[msg, chatbot],
|
| 165 |
outputs=[chatbot, error_box]
|
| 166 |
).then(
|
| 167 |
lambda: "",
|
|
@@ -172,7 +223,7 @@ def create_deepseek_interface():
|
|
| 172 |
# Enter 키 제출 허용
|
| 173 |
msg.submit(
|
| 174 |
query_deepseek_streaming,
|
| 175 |
-
inputs=[msg, chatbot],
|
| 176 |
outputs=[chatbot, error_box]
|
| 177 |
).then(
|
| 178 |
lambda: "",
|
|
|
|
| 11 |
def create_deepseek_interface():
|
| 12 |
# 환경 변수에서 API 키 가져오기
|
| 13 |
api_key = os.getenv("FW_API_KEY")
|
| 14 |
+
serphouse_api_key = os.getenv("SERPHOUSE_API_KEY")
|
| 15 |
+
|
| 16 |
if not api_key:
|
| 17 |
print("경고: FW_API_KEY 환경 변수가 설정되지 않았습니다.")
|
| 18 |
+
if not serphouse_api_key:
|
| 19 |
+
print("경고: SERPHOUSE_API_KEY 환경 변수가 설정되지 않았습니다.")
|
| 20 |
+
|
| 21 |
+
# SerpHouse API를 사용하여 검색 수행 함수
|
| 22 |
+
def search_with_serphouse(query):
|
| 23 |
+
if not serphouse_api_key:
|
| 24 |
+
return "SERPHOUSE_API_KEY가 설정되지 않았습니다."
|
| 25 |
+
|
| 26 |
+
url = "https://api.serphouse.com/serp/live"
|
| 27 |
+
payload = {
|
| 28 |
+
"q": query,
|
| 29 |
+
"domain": "google.com",
|
| 30 |
+
"loc": "us",
|
| 31 |
+
"lang": "en",
|
| 32 |
+
"device": "desktop",
|
| 33 |
+
"serp_type": "web",
|
| 34 |
+
"page": 1,
|
| 35 |
+
"num": 5 # 상위 5개 결과만 가져오기
|
| 36 |
+
}
|
| 37 |
+
headers = {
|
| 38 |
+
"Content-Type": "application/json",
|
| 39 |
+
"Authorization": f"Bearer {serphouse_api_key}"
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 44 |
+
response.raise_for_status()
|
| 45 |
+
|
| 46 |
+
search_results = response.json()
|
| 47 |
+
|
| 48 |
+
# 검색 결과 파싱 및 포맷팅
|
| 49 |
+
formatted_results = []
|
| 50 |
+
if "organic" in search_results and len(search_results["organic"]) > 0:
|
| 51 |
+
for result in search_results["organic"][:5]: # 상위 5개 결과만 사용
|
| 52 |
+
title = result.get("title", "제목 없음")
|
| 53 |
+
snippet = result.get("snippet", "내용 없음")
|
| 54 |
+
link = result.get("link", "#")
|
| 55 |
+
formatted_results.append(f"제목: {title}\n내용: {snippet}\n링크: {link}\n\n")
|
| 56 |
+
|
| 57 |
+
return "".join(formatted_results)
|
| 58 |
+
else:
|
| 59 |
+
return "검색 결과가 없습니다."
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return f"검색 중 오류 발생: {str(e)}"
|
| 63 |
|
| 64 |
# 스트리밍 방식으로 DeepSeek API 호출 함수
|
| 65 |
+
def query_deepseek_streaming(message, history, use_deep_research):
|
| 66 |
if not api_key:
|
| 67 |
yield history, "환경 변수 FW_API_KEY가 설정되지 않았습니다. 서버에서 환경 변수를 확인해주세요."
|
| 68 |
return
|
| 69 |
|
| 70 |
+
search_context = ""
|
| 71 |
+
if use_deep_research:
|
| 72 |
+
# 검색 수행
|
| 73 |
+
search_results = search_with_serphouse(message)
|
| 74 |
+
if not search_results.startswith("검색 중 오류 발생") and not search_results.startswith("SERPHOUSE_API_KEY"):
|
| 75 |
+
search_context = f"다음은 사용자 질문과 관련된 최신 검색 결과입니다. 이 정보를 참고하여 정확하고 최신 정보가 반영된 응답을 제공하세요:\n\n{search_results}\n\n사용자 질문에 답변하세요.\n\n"
|
| 76 |
+
|
| 77 |
# API 요청을 위한 대화 기록 준비
|
| 78 |
messages = []
|
| 79 |
for user, assistant in history:
|
| 80 |
messages.append({"role": "user", "content": user})
|
| 81 |
messages.append({"role": "assistant", "content": assistant})
|
| 82 |
|
| 83 |
+
# 검색 컨텍스트가 있으면 시스템 메시지 추가
|
| 84 |
+
if search_context:
|
| 85 |
+
# DeepSeek 모델은 시스템 메시지를 지원합니다
|
| 86 |
+
messages.insert(0, {"role": "system", "content": search_context})
|
| 87 |
+
|
| 88 |
# 새 사용자 메시지 추가
|
| 89 |
messages.append({"role": "user", "content": message})
|
| 90 |
|
|
|
|
| 164 |
"""
|
| 165 |
)
|
| 166 |
|
| 167 |
+
# 메인 레이아웃
|
| 168 |
with gr.Row():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
# 메인 콘텐츠 영역
|
| 170 |
+
with gr.Column():
|
| 171 |
+
# 채팅 인터페이스
|
| 172 |
chatbot = gr.Chatbot(
|
| 173 |
height=500,
|
| 174 |
show_label=False,
|
| 175 |
container=True
|
| 176 |
)
|
| 177 |
|
| 178 |
+
# Deep Research 토글 추가
|
| 179 |
+
with gr.Row():
|
| 180 |
+
use_deep_research = gr.Checkbox(
|
| 181 |
+
label="Deep Research 활성화",
|
| 182 |
+
info="최신 웹 검색 결과를 활용한 응답 생성"
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
# 입력 영역
|
| 186 |
with gr.Row():
|
| 187 |
msg = gr.Textbox(
|
|
|
|
| 205 |
],
|
| 206 |
inputs=msg
|
| 207 |
)
|
| 208 |
+
|
| 209 |
+
# 오류 메시지 표시
|
| 210 |
+
error_box = gr.Markdown("")
|
| 211 |
|
| 212 |
# 버튼과 기능 연결
|
| 213 |
submit.click(
|
| 214 |
query_deepseek_streaming,
|
| 215 |
+
inputs=[msg, chatbot, use_deep_research],
|
| 216 |
outputs=[chatbot, error_box]
|
| 217 |
).then(
|
| 218 |
lambda: "",
|
|
|
|
| 223 |
# Enter 키 제출 허용
|
| 224 |
msg.submit(
|
| 225 |
query_deepseek_streaming,
|
| 226 |
+
inputs=[msg, chatbot, use_deep_research],
|
| 227 |
outputs=[chatbot, error_box]
|
| 228 |
).then(
|
| 229 |
lambda: "",
|