| import os |
| from typing import Any |
|
|
| from huggingface_hub import InferenceClient, get_token |
|
|
|
|
| DEFAULT_MODEL_ID = "Qwen/Qwen3-8B" |
| DEFAULT_PROVIDER = "auto" |
|
|
|
|
| def resolve_hf_token() -> str: |
| """ |
| Hugging Face erişim tokenını bulur. |
| |
| Öncelik: |
| 1. HF_TOKEN ortam değişkeni |
| 2. `hf auth login` ile kaydedilmiş yerel token |
| """ |
|
|
| token = os.getenv("HF_TOKEN") or get_token() |
|
|
| if not token: |
| raise RuntimeError( |
| "Hugging Face tokenı bulunamadı. " |
| "Terminalde `hf auth login` komutunu çalıştır." |
| ) |
|
|
| return token |
|
|
|
|
| class LLMClient: |
| """Hugging Face Inference Providers istemcisi.""" |
|
|
| def __init__( |
| self, |
| model_id: str | None = None, |
| provider: str | None = None, |
| ) -> None: |
| self.model_id = ( |
| model_id |
| or os.getenv("HF_MODEL") |
| or DEFAULT_MODEL_ID |
| ) |
|
|
| self.provider = ( |
| provider |
| or os.getenv("HF_PROVIDER") |
| or DEFAULT_PROVIDER |
| ) |
|
|
| self.client = InferenceClient( |
| provider=self.provider, |
| api_key=resolve_hf_token(), |
| timeout=120, |
| ) |
|
|
| def create_chat_completion( |
| self, |
| messages: list[Any], |
| *, |
| tools: list[dict[str, Any]] | None = None, |
| tool_choice: str = "auto", |
| max_tokens: int = 700, |
| temperature: float = 0.1, |
| ) -> Any: |
| """ |
| Modele sohbet isteği gönderir. |
| |
| tools verilirse model tool çağırabilir. |
| tools verilmezse normal metin cevabı üretir. |
| """ |
|
|
| request_parameters: dict[str, Any] = { |
| "model": self.model_id, |
| "messages": messages, |
| "max_tokens": max_tokens, |
| "temperature": temperature, |
| } |
|
|
| if tools is not None: |
| request_parameters["tools"] = tools |
| request_parameters["tool_choice"] = tool_choice |
|
|
| return self.client.chat.completions.create( |
| **request_parameters |
| ) |