Update app.py
Browse files
app.py
CHANGED
@@ -18,14 +18,65 @@ def create_deepseek_interface():
|
|
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":
|
29 |
"domain": "google.com",
|
30 |
"loc": "us",
|
31 |
"lang": "en",
|
@@ -47,6 +98,8 @@ def create_deepseek_interface():
|
|
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", "제목 없음")
|
@@ -56,7 +109,7 @@ def create_deepseek_interface():
|
|
56 |
|
57 |
return "".join(formatted_results)
|
58 |
else:
|
59 |
-
return "검색 결과가 없습니다."
|
60 |
|
61 |
except Exception as e:
|
62 |
return f"검색 중 오류 발생: {str(e)}"
|
@@ -68,11 +121,23 @@ def create_deepseek_interface():
|
|
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"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
# API 요청을 위한 대화 기록 준비
|
78 |
messages = []
|
@@ -112,12 +177,15 @@ def create_deepseek_interface():
|
|
112 |
response = requests.request("POST", url, headers=headers, data=json.dumps(payload), stream=True)
|
113 |
response.raise_for_status() # HTTP 오류 발생 시 예외 발생
|
114 |
|
115 |
-
# 메시지를 추가하고 초기
|
116 |
new_history = history.copy()
|
117 |
-
|
|
|
|
|
|
|
118 |
|
119 |
# 응답 전체 텍스트
|
120 |
-
full_response =
|
121 |
|
122 |
# 스트리밍 응답 처리
|
123 |
for line in response.iter_lines():
|
@@ -179,7 +247,7 @@ def create_deepseek_interface():
|
|
179 |
with gr.Row():
|
180 |
use_deep_research = gr.Checkbox(
|
181 |
label="Deep Research 활성화",
|
182 |
-
info="
|
183 |
)
|
184 |
|
185 |
# 입력 영역
|
|
|
18 |
if not serphouse_api_key:
|
19 |
print("경고: SERPHOUSE_API_KEY 환경 변수가 설정되지 않았습니다.")
|
20 |
|
21 |
+
# 키워드 추출 함수 (LLM 기반)
|
22 |
+
def extract_keywords_with_llm(query):
|
23 |
+
if not api_key:
|
24 |
+
return "LLM 키워드 추출을 위한 FW_API_KEY가 설정되지 않았습니다.", query
|
25 |
+
|
26 |
+
# LLM을 사용하여 키워드 추출 (DeepSeek 모델 사용)
|
27 |
+
url = "https://api.fireworks.ai/inference/v1/chat/completions"
|
28 |
+
payload = {
|
29 |
+
"model": "accounts/fireworks/models/deepseek-v3-0324",
|
30 |
+
"max_tokens": 200,
|
31 |
+
"temperature": 0.1, # 일관된 결과를 위해 낮은 온도 사용
|
32 |
+
"messages": [
|
33 |
+
{
|
34 |
+
"role": "system",
|
35 |
+
"content": "사용자의 질문에서 웹 검색에 효과적인 핵심 키워드 3-5개를 추출하세요. 키워드만 쉼표로 구분하여 출력하고 다른 설명이나 부가 정보는 제공하지 마세요."
|
36 |
+
},
|
37 |
+
{
|
38 |
+
"role": "user",
|
39 |
+
"content": query
|
40 |
+
}
|
41 |
+
]
|
42 |
+
}
|
43 |
+
headers = {
|
44 |
+
"Accept": "application/json",
|
45 |
+
"Content-Type": "application/json",
|
46 |
+
"Authorization": f"Bearer {api_key}"
|
47 |
+
}
|
48 |
+
|
49 |
+
try:
|
50 |
+
response = requests.post(url, headers=headers, json=payload)
|
51 |
+
response.raise_for_status()
|
52 |
+
result = response.json()
|
53 |
+
|
54 |
+
# 응답에서 키워드 추출
|
55 |
+
keywords = result["choices"][0]["message"]["content"].strip()
|
56 |
+
|
57 |
+
# 키워드가 너무 길거나 형식이 잘못된 경우 원본 쿼리 사용
|
58 |
+
if len(keywords) > 100 or "," not in keywords:
|
59 |
+
return f"추출된 키워드: {keywords}", query
|
60 |
+
|
61 |
+
return f"추출된 키워드: {keywords}", keywords
|
62 |
+
|
63 |
+
except Exception as e:
|
64 |
+
print(f"키워드 추출 중 오류 발생: {str(e)}")
|
65 |
+
return f"키워드 추출 중 오류 발생: {str(e)}", query
|
66 |
+
|
67 |
# SerpHouse API를 사용하여 검색 수행 함수
|
68 |
def search_with_serphouse(query):
|
69 |
if not serphouse_api_key:
|
70 |
return "SERPHOUSE_API_KEY가 설정되지 않았습니다."
|
71 |
|
72 |
+
# 키워드 추출
|
73 |
+
extraction_result, search_query = extract_keywords_with_llm(query)
|
74 |
+
print(f"원본 쿼리: {query}")
|
75 |
+
print(extraction_result)
|
76 |
+
|
77 |
url = "https://api.serphouse.com/serp/live"
|
78 |
payload = {
|
79 |
+
"q": search_query,
|
80 |
"domain": "google.com",
|
81 |
"loc": "us",
|
82 |
"lang": "en",
|
|
|
98 |
|
99 |
# 검색 결과 파싱 및 포맷팅
|
100 |
formatted_results = []
|
101 |
+
formatted_results.append(f"검색어: {search_query}\n\n")
|
102 |
+
|
103 |
if "organic" in search_results and len(search_results["organic"]) > 0:
|
104 |
for result in search_results["organic"][:5]: # 상위 5개 결과만 사용
|
105 |
title = result.get("title", "제목 없음")
|
|
|
109 |
|
110 |
return "".join(formatted_results)
|
111 |
else:
|
112 |
+
return f"검색어 '{search_query}'에 대한 검색 결과가 없습니다."
|
113 |
|
114 |
except Exception as e:
|
115 |
return f"검색 중 오류 발생: {str(e)}"
|
|
|
121 |
return
|
122 |
|
123 |
search_context = ""
|
124 |
+
search_info = ""
|
125 |
if use_deep_research:
|
126 |
+
# 검색 수행 (첫 메시지 전달)
|
127 |
+
yield history + [(message, "🔍 최적의 키워드 추출 및 웹 검색 중...")], ""
|
128 |
+
|
129 |
+
# 검색 실행
|
130 |
search_results = search_with_serphouse(message)
|
131 |
if not search_results.startswith("검색 중 오류 발생") and not search_results.startswith("SERPHOUSE_API_KEY"):
|
132 |
+
search_context = f"""
|
133 |
+
다음은 사용자 질문과 관련된 최신 검색 결과입니다. 이 정보를 참고하여 정확하고 최신 정보가 반영된 응답을 제공하세요:
|
134 |
+
|
135 |
+
{search_results}
|
136 |
+
|
137 |
+
위 검색 결과를 기반으로 사용자의 다음 질문에 답변하세요. 검색 결과에서 명확한 답변을 찾을 수 없는 경우, 당신의 지식을 활용하여 최선의 답변을 제공하세요.
|
138 |
+
검색 결과를 인용할 때는 출처를 명시하고, 답변이 최신 ���보를 반영하도록 하세요.
|
139 |
+
"""
|
140 |
+
search_info = f"🔍 Deep Research 기능 활성화: 관련 웹 검색 결과를 기반으로 응답 생성 중..."
|
141 |
|
142 |
# API 요청을 위한 대화 기록 준비
|
143 |
messages = []
|
|
|
177 |
response = requests.request("POST", url, headers=headers, data=json.dumps(payload), stream=True)
|
178 |
response.raise_for_status() # HTTP 오류 발생 시 예외 발생
|
179 |
|
180 |
+
# 메시지를 추가하고 초기 응답으로 시작
|
181 |
new_history = history.copy()
|
182 |
+
|
183 |
+
# search_info가 있으면 시작 메시지에 포함
|
184 |
+
start_msg = search_info if search_info else ""
|
185 |
+
new_history.append((message, start_msg))
|
186 |
|
187 |
# 응답 전체 텍스트
|
188 |
+
full_response = start_msg
|
189 |
|
190 |
# 스트리밍 응답 처리
|
191 |
for line in response.iter_lines():
|
|
|
247 |
with gr.Row():
|
248 |
use_deep_research = gr.Checkbox(
|
249 |
label="Deep Research 활성화",
|
250 |
+
info="최적의 키워드 추출 및 웹 검색을 통한 최신 정보 활용"
|
251 |
)
|
252 |
|
253 |
# 입력 영역
|