import json from datetime import date, datetime import requests from django.conf import settings def _build_prompt(count, min_age): max_year = date.today().year - min_age return ( "Turkiye icin gercekci kisi verisi uret. " "Turkce isim ve soyisim oncelikli olsun. " f"{count} adet kayit uret. " f"Her kaydin dogum yili en fazla {max_year} olsun (yani en az {min_age} yas). " "Sadece JSON dondur. Baska metin yazma. " "Format tam olarak su olsun: " "{\"people\":[{\"first_name\":\"...\",\"last_name\":\"...\",\"gender\":\"E|K\",\"birth_date\":\"YYYY-MM-DD\"}]}" ) def _validate_people(items, min_age): valid = [] today = date.today() for item in items: first_name = str(item.get('first_name', '')).strip() last_name = str(item.get('last_name', '')).strip() gender = str(item.get('gender', '')).strip().upper() birth_date_raw = str(item.get('birth_date', '')).strip() if not first_name or not last_name: continue if gender not in {'E', 'K'}: continue try: birth_date = datetime.strptime(birth_date_raw, '%Y-%m-%d').date() except ValueError: continue age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day)) if age < min_age: continue valid.append({ 'first_name': first_name, 'last_name': last_name, 'gender': gender, 'birth_date': birth_date, }) return valid def generate_people_with_llm(count, min_age=20): """LLM API'den kisi verisi alir, validate edip dondurur.""" api_url = getattr(settings, 'LLM_API_URL', None) model = getattr(settings, 'LLM_MODEL', None) timeout = getattr(settings, 'LLM_TIMEOUT', 30) api_key = getattr(settings, 'LLM_API_KEY', None) if not api_url or not model: raise RuntimeError('LLM_API_URL veya LLM_MODEL ayari eksik.') prompt = _build_prompt(count=count, min_age=min_age) headers = {'Content-Type': 'application/json'} if api_key: headers['Authorization'] = f'Bearer {api_key}' # OpenAI uyumlu endpoint if '/v1/chat/completions' in api_url: payload = { 'model': model, 'response_format': {'type': 'json_object'}, 'messages': [ {'role': 'system', 'content': 'JSON disinda metin uretme.'}, {'role': 'user', 'content': prompt}, ], 'temperature': 0.8, } resp = requests.post(api_url, headers=headers, json=payload, timeout=timeout) resp.raise_for_status() content = resp.json()['choices'][0]['message']['content'] else: # Varsayilan: Ollama /api/chat payload = { 'model': model, 'stream': False, 'format': 'json', 'messages': [ {'role': 'system', 'content': 'JSON disinda metin uretme.'}, {'role': 'user', 'content': prompt}, ], } resp = requests.post(api_url, headers=headers, json=payload, timeout=timeout) resp.raise_for_status() body = resp.json() content = body.get('message', {}).get('content') or body.get('response') if not content: raise RuntimeError('LLM bos cevap dondurdu.') parsed = json.loads(content) people = parsed.get('people') if isinstance(parsed, dict) else None if not isinstance(people, list): raise RuntimeError('LLM cevabi beklenen JSON formatinda degil.') valid_people = _validate_people(people, min_age=min_age) if not valid_people: raise RuntimeError('LLM gecerli kisi verisi dondurmedi.') return valid_people