Spaces:
Running
Running
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() | |