Spaces:
Running
Running
File size: 7,706 Bytes
2a55e2a |
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 |
"""
DeepSeek Provider Integration
Handles API calls to DeepSeek for AI model inference
"""
import os
import requests
import time
import json
import logging
from typing import Dict, Any, Optional, List
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("deepseek")
class DeepSeekProvider:
"""DeepSeek API provider for model inference"""
def __init__(self, api_key: Optional[str] = None):
"""Initialize the DeepSeek provider with API key"""
self.api_key = api_key or os.getenv("DEEPSEEK_API_KEY")
if not self.api_key:
logger.warning("No DeepSeek API key provided. Set DEEPSEEK_API_KEY env variable.")
self.base_url = "https://api.deepseek.com/v1"
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
def generate_text(self,
prompt: str,
model: str = "deepseek-chat",
max_tokens: int = 1000,
temperature: float = 0.7,
system_message: str = "You are a helpful assistant.",
**kwargs) -> Dict[str, Any]:
"""Generate text using DeepSeek models"""
if not self.api_key:
return {"success": False, "error": "DeepSeek API key not provided"}
start_time = time.time()
try:
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": prompt}
]
payload = {
"model": model,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
**kwargs
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload
)
# Check for errors
if response.status_code != 200:
logger.error(f"Error from DeepSeek API: {response.status_code} - {response.text}")
return {
"success": False,
"error": f"DeepSeek API error: {response.status_code}",
"response_time": time.time() - start_time,
"model": model,
"provider": "deepseek"
}
result = response.json()
# Extract the generated text
generated_text = result["choices"][0]["message"]["content"]
return {
"success": True,
"text": generated_text,
"model": model,
"provider": "deepseek",
"response_time": time.time() - start_time,
"tokens": {
"prompt": result.get("usage", {}).get("prompt_tokens", 0),
"completion": result.get("usage", {}).get("completion_tokens", 0),
"total": result.get("usage", {}).get("total_tokens", 0)
},
"raw_response": result
}
except Exception as e:
logger.error(f"Error generating text with DeepSeek: {e}")
return {
"success": False,
"error": str(e),
"response_time": time.time() - start_time,
"model": model,
"provider": "deepseek"
}
def generate_code(self,
prompt: str,
model: str = "deepseek-coder",
max_tokens: int = 2000,
temperature: float = 0.5,
**kwargs) -> Dict[str, Any]:
"""Generate code using DeepSeek Coder models"""
if not self.api_key:
return {"success": False, "error": "DeepSeek API key not provided"}
start_time = time.time()
try:
messages = [
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": prompt}
]
payload = {
"model": model,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
**kwargs
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload
)
# Check for errors
if response.status_code != 200:
logger.error(f"Error from DeepSeek API: {response.status_code} - {response.text}")
return {
"success": False,
"error": f"DeepSeek API error: {response.status_code}",
"response_time": time.time() - start_time,
"model": model,
"provider": "deepseek"
}
result = response.json()
# Extract the generated code
generated_code = result["choices"][0]["message"]["content"]
return {
"success": True,
"text": generated_code,
"model": model,
"provider": "deepseek",
"response_time": time.time() - start_time,
"tokens": {
"prompt": result.get("usage", {}).get("prompt_tokens", 0),
"completion": result.get("usage", {}).get("completion_tokens", 0),
"total": result.get("usage", {}).get("total_tokens", 0)
},
"raw_response": result
}
except Exception as e:
logger.error(f"Error generating code with DeepSeek: {e}")
return {
"success": False,
"error": str(e),
"response_time": time.time() - start_time,
"model": model,
"provider": "deepseek"
}
def get_available_models(self) -> List[Dict[str, Any]]:
"""Get available DeepSeek models"""
if not self.api_key:
return []
# DeepSeek doesn't have a list models endpoint yet, so we hardcode the currently available models
models = [
{
"id": "deepseek-chat",
"name": "DeepSeek Chat",
"description": "General-purpose language model for chat",
"context_length": 4096
},
{
"id": "deepseek-coder",
"name": "DeepSeek Coder",
"description": "Specialized model for code generation",
"context_length": 8192
},
{
"id": "deepseek-math",
"name": "DeepSeek Math",
"description": "Model fine-tuned for mathematical reasoning",
"context_length": 4096
}
]
return models
# Example usage
if __name__ == "__main__":
# Test the provider
provider = DeepSeekProvider()
result = provider.generate_text("Write a short poem about AI.")
print(json.dumps(result, indent=2)) |