openfree commited on
Commit
1f1f6a2
·
verified ·
1 Parent(s): 73fe1ee

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -0
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import requests
4
+ import json
5
+ import time
6
+ from dotenv import load_dotenv
7
+
8
+ # .env 파일 로드 (있는 경우)
9
+ load_dotenv()
10
+
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
+
32
+ # API 요청 준비
33
+ url = "https://api.fireworks.ai/inference/v1/chat/completions"
34
+ payload = {
35
+ "model": "accounts/fireworks/models/deepseek-v3-0324",
36
+ "max_tokens": 20480,
37
+ "top_p": 1,
38
+ "top_k": 40,
39
+ "presence_penalty": 0,
40
+ "frequency_penalty": 0,
41
+ "temperature": 0.6,
42
+ "messages": messages,
43
+ "stream": True # 스트리밍 활성화
44
+ }
45
+ headers = {
46
+ "Accept": "application/json",
47
+ "Content-Type": "application/json",
48
+ "Authorization": f"Bearer {api_key}"
49
+ }
50
+
51
+ try:
52
+ # 스트리밍 응답 요청
53
+ response = requests.request("POST", url, headers=headers, data=json.dumps(payload), stream=True)
54
+ response.raise_for_status() # HTTP 오류 발생 시 예외 발생
55
+
56
+ # 메시지를 추가하고 초기 빈 응답으로 시작
57
+ new_history = history.copy()
58
+ new_history.append((message, ""))
59
+
60
+ # 응답 전체 텍스트
61
+ full_response = ""
62
+
63
+ # 스트리밍 응답 처리
64
+ for line in response.iter_lines():
65
+ if line:
66
+ line_text = line.decode('utf-8')
67
+
68
+ # 'data: ' 접두사 제거
69
+ if line_text.startswith("data: "):
70
+ line_text = line_text[6:]
71
+
72
+ # 스트림 종료 메시지 확인
73
+ if line_text == "[DONE]":
74
+ break
75
+
76
+ try:
77
+ # JSON 파싱
78
+ chunk = json.loads(line_text)
79
+ chunk_content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
80
+
81
+ if chunk_content:
82
+ full_response += chunk_content
83
+ # 채팅 기록 업데이트
84
+ new_history[-1] = (message, full_response)
85
+ yield new_history, ""
86
+ except json.JSONDecodeError:
87
+ continue
88
+
89
+ # 최종 응답 반환
90
+ yield new_history, ""
91
+
92
+ except requests.exceptions.RequestException as e:
93
+ error_msg = f"API 오류: {str(e)}"
94
+ if hasattr(e, 'response') and e.response and e.response.status_code == 401:
95
+ error_msg = "인증 실패. 환경 변수 FW_API_KEY를 확인해주세요."
96
+ yield history, error_msg
97
+
98
+ # Gradio 인터페이스 생성
99
+ with gr.Blocks(theme="soft", fill_height=True) as demo:
100
+ # 헤더 섹션
101
+ gr.Markdown(
102
+ """
103
+ # 🤖 DeepSeek V3 스트리밍 인터페이스
104
+ ### Fireworks AI가 제공하는 고급 AI 모델 - 실시간 응답 지원
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(scale=2):
130
+ # 채팅 인터페이스
131
+ chatbot = gr.Chatbot(
132
+ height=500,
133
+ show_label=False,
134
+ container=True,
135
+ bubble=True,
136
+ avatar_images=("👤", "🤖")
137
+ )
138
+
139
+ # 입력 영역
140
+ with gr.Row():
141
+ msg = gr.Textbox(
142
+ label="메시지",
143
+ placeholder="여기에 프롬프트를 입력하세요...",
144
+ show_label=False,
145
+ scale=9
146
+ )
147
+ submit = gr.Button("전송", variant="primary", scale=1)
148
+
149
+ # 대화 초기화 버튼
150
+ with gr.Row():
151
+ clear = gr.ClearButton([msg, chatbot], value="🧹 대화 초기화")
152
+
153
+ # 예제 쿼리
154
+ gr.Examples(
155
+ examples=[
156
+ "딥러닝에서 트랜스포머와 RNN의 차이점을 설명해주세요.",
157
+ "특정 범위 내의 소수를 찾는 파이썬 함수를 작성해주세요.",
158
+ "강화학습의 주요 개념을 요약해주세요."
159
+ ],
160
+ inputs=msg
161
+ )
162
+
163
+ # 버튼과 기능 연결
164
+ submit.click(
165
+ query_deepseek_streaming,
166
+ inputs=[msg, chatbot],
167
+ outputs=[chatbot, error_box]
168
+ ).then(
169
+ lambda: "",
170
+ None,
171
+ [msg]
172
+ )
173
+
174
+ # Enter 키 제출 허용
175
+ msg.submit(
176
+ query_deepseek_streaming,
177
+ inputs=[msg, chatbot],
178
+ outputs=[chatbot, error_box]
179
+ ).then(
180
+ lambda: "",
181
+ None,
182
+ [msg]
183
+ )
184
+
185
+ return demo
186
+
187
+ # 인터페이스 실행
188
+ if __name__ == "__main__":
189
+ demo = create_deepseek_interface()
190
+ demo.launch(debug=True)