File size: 7,458 Bytes
d93e680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
DeepSeek API ํด๋ผ์ด์–ธํŠธ ๋ชจ๋“ˆ
"""

import os
import json
import logging
from typing import List, Dict, Any, Optional, Union
from dotenv import load_dotenv
import requests

# ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ๋กœ๋“œ
load_dotenv()

# ๋กœ๊ฑฐ ์„ค์ •
logger = logging.getLogger("DeepSeekLLM")
if not logger.hasHandlers():
    handler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)

class DeepSeekLLM:
    """DeepSeek API ๋ž˜ํผ ํด๋ž˜์Šค"""
    
    def __init__(self):
        """DeepSeek LLM ํด๋ž˜์Šค ์ดˆ๊ธฐํ™”"""
        self.api_key = os.getenv("DEEPSEEK_API_KEY")
        self.api_base = os.getenv("DEEPSEEK_API_BASE", "https://api.deepseek.com")
        self.model = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
        
        if not self.api_key:
            logger.warning("DeepSeek API ํ‚ค๊ฐ€ .env ํŒŒ์ผ์— ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
            logger.warning("DEEPSEEK_API_KEY๋ฅผ ํ™•์ธํ•˜์„ธ์š”.")
        else:
            logger.info("DeepSeek API ํ‚ค ๋กœ๋“œ ์™„๋ฃŒ.")
    
    def chat_completion(
        self, 
        messages: List[Dict[str, str]], 
        temperature: float = 0.7, 
        max_tokens: int = 1000,
        **kwargs
    ) -> Dict[str, Any]:
        """
        DeepSeek ์ฑ„ํŒ… ์™„์„ฑ API ํ˜ธ์ถœ
        
        Args:
            messages: ์ฑ„ํŒ… ๋ฉ”์‹œ์ง€ ๋ชฉ๋ก
            temperature: ์ƒ์„ฑ ์˜จ๋„ (๋‚ฎ์„์ˆ˜๋ก ๊ฒฐ์ •์ )
            max_tokens: ์ƒ์„ฑํ•  ์ตœ๋Œ€ ํ† ํฐ ์ˆ˜
            **kwargs: ์ถ”๊ฐ€ API ๋งค๊ฐœ๋ณ€์ˆ˜
        
        Returns:
            API ์‘๋‹ต (๋”•์…”๋„ˆ๋ฆฌ)
        """
        if not self.api_key:
            logger.error("API ํ‚ค๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•„ DeepSeek API๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
            raise ValueError("DeepSeek API ํ‚ค๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
        
        try:
            logger.info(f"DeepSeek API ์š”์ฒญ ์ „์†ก ์ค‘ (๋ชจ๋ธ: {self.model})")
            
            # API ์š”์ฒญ ํ—ค๋” ๋ฐ ๋ฐ์ดํ„ฐ ์ค€๋น„
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            }
            
            data = {
                "model": self.model,
                "messages": messages,
                "temperature": temperature,
                "max_tokens": max_tokens
            }
            
            # ์ถ”๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜ ๋ณ‘ํ•ฉ
            for key, value in kwargs.items():
                if key not in data:
                    data[key] = value
            
            # API ์š”์ฒญ ๋ณด๋‚ด๊ธฐ
            endpoint = f"{self.api_base}/v1/chat/completions"
            response = requests.post(
                endpoint,
                headers=headers,
                json=data
            )
            
            # ์‘๋‹ต ๊ฒ€์ฆ
            response.raise_for_status()
            return response.json()
                
        except requests.exceptions.RequestException as e:
            logger.error(f"DeepSeek API ์š”์ฒญ ์‹คํŒจ: {e}")
            raise Exception(f"DeepSeek API ์š”์ฒญ ์‹คํŒจ: {e}")
        except json.JSONDecodeError as e:
            logger.error(f"DeepSeek API ์‘๋‹ต ํŒŒ์‹ฑ ์‹คํŒจ: {e}")
            raise Exception(f"DeepSeek API ์‘๋‹ต ํŒŒ์‹ฑ ์‹คํŒจ: {e}")
    
    def generate(
        self, 
        prompt: str, 
        system_prompt: Optional[str] = None,
        temperature: float = 0.7,
        max_tokens: int = 1000,
        **kwargs
    ) -> str:
        """
        ๊ฐ„๋‹จํ•œ ํ…์ŠคํŠธ ์ƒ์„ฑ ์ธํ„ฐํŽ˜์ด์Šค
        
        Args:
            prompt: ์‚ฌ์šฉ์ž ํ”„๋กฌํ”„ํŠธ
            system_prompt: ์‹œ์Šคํ…œ ํ”„๋กฌํ”„ํŠธ (์„ ํƒ ์‚ฌํ•ญ)
            temperature: ์ƒ์„ฑ ์˜จ๋„
            max_tokens: ์ƒ์„ฑํ•  ์ตœ๋Œ€ ํ† ํฐ ์ˆ˜
            **kwargs: ์ถ”๊ฐ€ API ๋งค๊ฐœ๋ณ€์ˆ˜
        
        Returns:
            ์ƒ์„ฑ๋œ ํ…์ŠคํŠธ
        """
        messages = []
        
        if system_prompt:
            messages.append({"role": "system", "content": system_prompt})
        
        messages.append({"role": "user", "content": prompt})
        
        try:
            response = self.chat_completion(
                messages=messages,
                temperature=temperature,
                max_tokens=max_tokens,
                **kwargs
            )
            
            # ์‘๋‹ต ๊ฒ€์ฆ ๋ฐ ์ฒ˜๋ฆฌ
            if not response or 'choices' not in response or not response['choices']:
                logger.error("DeepSeek API ์‘๋‹ต์—์„œ ์ƒ์„ฑ๋œ ํ…์ŠคํŠธ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
                return ""
            
            return response['choices'][0]['message']['content'].strip()
            
        except Exception as e:
            logger.error(f"ํ…์ŠคํŠธ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
            return f"์˜ค๋ฅ˜: {str(e)}"
    
    def rag_generate(
        self, 
        query: str, 
        context: List[str],
        system_prompt: Optional[str] = None,
        temperature: float = 0.3,
        max_tokens: int = 1000,
        **kwargs
    ) -> str:
        """
        RAG ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋ฅผ ํ™œ์šฉํ•œ ํ…์ŠคํŠธ ์ƒ์„ฑ
        
        Args:
            query: ์‚ฌ์šฉ์ž ์งˆ์˜
            context: ๊ฒ€์ƒ‰๋œ ๋ฌธ๋งฅ ๋ชฉ๋ก
            system_prompt: ์‹œ์Šคํ…œ ํ”„๋กฌํ”„ํŠธ (์„ ํƒ ์‚ฌํ•ญ)
            temperature: ์ƒ์„ฑ ์˜จ๋„
            max_tokens: ์ƒ์„ฑํ•  ์ตœ๋Œ€ ํ† ํฐ ์ˆ˜
            **kwargs: ์ถ”๊ฐ€ API ๋งค๊ฐœ๋ณ€์ˆ˜
        
        Returns:
            ์ƒ์„ฑ๋œ ํ…์ŠคํŠธ
        """
        if not system_prompt:
            system_prompt = """๋‹น์‹ ์€ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•˜๋Š” ๋„์šฐ๋ฏธ์ž…๋‹ˆ๋‹ค.
- ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋Š” <context> ํƒœ๊ทธ ์•ˆ์— ์ œ๊ณต๋ฉ๋‹ˆ๋‹ค.
- ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ์— ๋‹ต๋ณ€์ด ์žˆ์œผ๋ฉด ํ•ด๋‹น ์ •๋ณด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ช…ํ™•ํ•˜๊ฒŒ ๋‹ต๋ณ€ํ•˜์„ธ์š”.
- ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ์— ๋‹ต๋ณ€์ด ์—†์œผ๋ฉด "๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ์— ๊ด€๋ จ ์ •๋ณด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค"๋ผ๊ณ  ๋งํ•˜์„ธ์š”.
- ๊ฒ€์ƒ‰ ๋‚ด์šฉ์„ ๊ทธ๋Œ€๋กœ ๋ณต์‚ฌํ•˜์ง€ ๋ง๊ณ , ์ž์—ฐ์Šค๋Ÿฌ์šด ํ•œ๊ตญ์–ด๋กœ ๋‹ต๋ณ€์„ ์ž‘์„ฑํ•˜์„ธ์š”.
- ๋‹ต๋ณ€์€ ๊ฐ„๊ฒฐํ•˜๊ณ  ์ •ํ™•ํ•˜๊ฒŒ ์ œ๊ณตํ•˜์„ธ์š”."""
        
        # ์ค‘์š”: ์ปจํ…์ŠคํŠธ ๊ธธ์ด ์ œํ•œ
        max_context = 10
        if len(context) > max_context:
            logger.warning(f"์ปจํ…์ŠคํŠธ๊ฐ€ ๋„ˆ๋ฌด ๊ธธ์–ด ์ฒ˜์Œ {max_context}๊ฐœ๋งŒ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.")
            context = context[:max_context]
        
        # ๊ฐ ์ปจํ…์ŠคํŠธ ์•ก์„ธ์Šค
        limited_context = []
        for i, doc in enumerate(context):
            # ๊ฐ ๋ฌธ์„œ๋ฅผ 1000์ž๋กœ ์ œํ•œ
            if len(doc) > 1000:
                logger.warning(f"๋ฌธ์„œ {i+1}์˜ ๊ธธ์ด๊ฐ€ ์ œํ•œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค ({len(doc)} -> 1000)")
                doc = doc[:1000] + "...(์ƒ๋žต)"
            limited_context.append(doc)
        
        context_text = "\n\n".join([f"๋ฌธ์„œ {i+1}: {doc}" for i, doc in enumerate(limited_context)])
        
        prompt = f"""์งˆ๋ฌธ: {query}

<context>
{context_text}
</context>

์œ„ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•ด ์ฃผ์„ธ์š”."""
        
        try:
            return self.generate(
                prompt=prompt,
                system_prompt=system_prompt,
                temperature=temperature,
                max_tokens=max_tokens,
                **kwargs
            )
        except Exception as e:
            logger.error(f"RAG ํ…์ŠคํŠธ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
            return f"์˜ค๋ฅ˜: {str(e)}"