File size: 7,500 Bytes
c3e5767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import google.generativeai as genai
from openai import OpenAI
from anthropic import Anthropic
import httpx

# Desteklenen LLM Sağlayıcıları ve Modelleri
LLM_PROVIDERS = {
    "Gemini": {
        "models": [
            "gemini-pro",
            "gemini-1.5-pro-latest",
            "gemini-1.5-flash-latest"
        ],
        "api_key_env": "GEMINI_API_KEY"
    },
    "OpenAI": {
        "models": [], # Dinamik olarak çekilecek
        "api_key_env": "OPENAI_API_KEY"
    },
    "Anthropic": {
        "models": [], # Dinamik olarak çekilecek
        "api_key_env": "ANTHROPIC_API_KEY"
    },
    "OpenRouter": {
        "models": [], # Dinamik olarak çekilecek
        "api_key_env": "OPENROUTER_API_KEY"
    }
}

def get_llm_models(provider_name, api_key):
    """Seçilen sağlayıcının modellerini dinamik olarak çeker."""
    models = []
    if provider_name == "Gemini":
        # Gemini modelleri statik olarak tanımlanmıştır, API'den çekmeye gerek yok
        models = LLM_PROVIDERS["Gemini"]["models"]
    elif provider_name == "OpenAI":
        try:
            client = OpenAI(api_key=api_key)
            response = client.models.list()
            models = [model.id for model in response.data if "gpt" in model.id and "vision" not in model.id and "instruct" not in model.id]
            models.sort()
        except Exception as e:
            print(f"OpenAI modelleri çekilirken hata oluştu: {e}")
            models = []
    elif provider_name == "Anthropic":
        try:
            client = Anthropic(api_key=api_key)
            # Anthropic API'sinde modelleri listeleme endpoint'i yok, bilinenleri manuel ekle
            models = [
                "claude-3-opus-20240229",
                "claude-3-sonnet-20240229",
                "claude-3-haiku-20240307"
            ]
        except Exception as e:
            print(f"Anthropic modelleri çekilirken hata oluştu: {e}")
            models = []
    elif provider_name == "OpenRouter":
        try:
            # OpenRouter API'sinden modelleri çek
            headers = {"Authorization": f"Bearer {api_key}"}
            response = httpx.get("https://openrouter.ai/api/v1/models", headers=headers)
            response.raise_for_status()
            data = response.json()
            models = [model["id"] for model in data["data"]]
            models.sort()
        except Exception as e:
            print(f"OpenRouter modelleri çekilirken hata oluştu: {e}")
            models = []
    return models

def validate_api_key(provider_name, api_key):
    """Seçilen sağlayıcının API anahtarını doğrular."""
    if not api_key:
        return False, "API Anahtarı boş olamaz."

    try:
        if provider_name == "Gemini":
            genai.configure(api_key=api_key)
            # Küçük bir model çağrısı ile anahtarı doğrula
            model = genai.GenerativeModel('gemini-pro')
            model.generate_content("test")
            return True, "API Anahtarı Geçerli!"
        elif provider_name == "OpenAI":
            client = OpenAI(api_key=api_key)
            client.models.list() # Modelleri listelemek anahtarı doğrular
            return True, "API Anahtarı Geçerli!"
        elif provider_name == "Anthropic":
            client = Anthropic(api_key=api_key)
            client.messages.create(
                model="claude-3-haiku-20240307", # En küçük model
                max_tokens=1,
                messages=[{"role": "user", "content": "hi"}]
            )
            return True, "API Anahtarı Geçerli!"
        elif provider_name == "OpenRouter":
            headers = {"Authorization": f"Bearer {api_key}"}
            response = httpx.get("https://openrouter.ai/api/v1/models", headers=headers)
            response.raise_for_status() # HTTP 2xx dışında bir durum kodu hata fırlatır
            return True, "API Anahtarı Geçerli!"
        else:
            return False, "Bilinmeyen sağlayıcı."
    except Exception as e:
        return False, f"API Anahtarı Geçersiz veya Bir Hata Oluştu: {e}"





def call_llm(provider_name, model_name, api_key, prompt):
    """Seçilen LLM sağlayıcısını kullanarak bir çağrı yapar."""
    try:
        if provider_name == "Gemini":
            genai.configure(api_key=api_key)
            model = genai.GenerativeModel(model_name)
            response = model.generate_content(prompt)
            return response.text
        elif provider_name == "OpenAI":
            client = OpenAI(api_key=api_key)
            response = client.chat.completions.create(
                model=model_name,
                messages=[
                    {"role": "user", "content": prompt}
                ]
            )
            return response.choices[0].message.content
        elif provider_name == "Anthropic":
            client = Anthropic(api_key=api_key)
            response = client.messages.create(
                model=model_name,
                max_tokens=4000, # Yeterli token sağlamak için
                messages=[
                    {"role": "user", "content": prompt}
                ]
            )
            return response.content[0].text
        elif provider_name == "OpenRouter":
            headers = {
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            }
            data = {
                "model": model_name,
                "messages": [
                    {"role": "user", "content": prompt}
                ]
            }
            response = httpx.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=data)
            response.raise_for_status()
            return response.json()["choices"][0]["message"]["content"]
        else:
            return "Bilinmeyen LLM sağlayıcısı."
    except Exception as e:
        return f"LLM çağrısı sırasında hata oluştu: {e}"




import re
import zipfile
import io

def parse_llm_output(llm_output):
    """LLM çıktısını dosya yolları ve içerikleri olarak ayrıştırır."""
    files = {}
    # Her bir dosya başlığını yakalamak için regex
    # Başlıklar: # context/01_persona.md, # context/02_project_overview.md vb.
    # İçerik, bir sonraki başlığa veya string'in sonuna kadar devam eder.
    matches = re.finditer(r'^#\s*(context/[\w\d_\-]+\.md)\s*\n', llm_output, re.MULTILINE)

    last_end = 0
    last_file_path = None

    for match in matches:
        current_file_path = match.group(1).strip()
        current_start = match.end()

        if last_file_path:
            # Önceki dosyanın içeriğini al
            content = llm_output[last_end:match.start()].strip()
            files[last_file_path] = content

        last_file_path = current_file_path
        last_end = current_start
    
    # Son dosyanın içeriğini ekle
    if last_file_path:
        content = llm_output[last_end:].strip()
        files[last_file_path] = content

    return files

def create_zip_from_files(files_dict):
    """Bir dosya sözlüğünden (yol:içerik) bir ZIP dosyası oluşturur ve baytlarını döndürür."""
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED, False) as zip_file:
        for file_path, content in files_dict.items():
            # ZIP içinde klasör yapısını korumak için
            zip_file.writestr(file_path, content.encode("utf-8"))
    zip_buffer.seek(0)
    return zip_buffer.getvalue()