diff --git a/backend/ads/tasks.py b/backend/ads/tasks.py index b387836..9d04874 100644 --- a/backend/ads/tasks.py +++ b/backend/ads/tasks.py @@ -37,7 +37,12 @@ def evaluate_ad_with_ai(self, evaluation_id): return try: - client = OpenAI(api_key=api_key) + # Support OpenRouter keys seamlessly + client_kwargs = {"api_key": api_key} + if api_key.startswith("sk-or-"): + client_kwargs["base_url"] = "https://openrouter.ai/api/v1" + + client = OpenAI(**client_kwargs) system_instruction = ( "You are an expert Iranian market analyst. Your job is to read listing descriptions " @@ -53,13 +58,17 @@ def evaluate_ad_with_ai(self, evaluation_id): f"Ad Description:\n{ad.description}" ) + default_model = "openrouter/free" if api_key.startswith("sk-or-") else "gpt-4o-mini" + model_name = os.getenv("OPENAI_MODEL", default_model) + completion = client.beta.chat.completions.parse( - model="gpt-4o-mini", + model=model_name, messages=[ {"role": "system", "content": system_instruction}, {"role": "user", "content": user_content} ], response_format=AdEvaluationResult, + max_tokens=300, timeout=25 )