Spaces:
Paused
Paused
Fix OpenAI gpt-4.1 API parameters: role 'developer', max_completion_tokens, and reasoning effort support; update max_tokens in default config
Browse filesFiles changed (2)
- config/environments/default.yaml+4-4
- main.py+56-21
22 unmodified lines2324252627282930313222 unmodified lines# Generation Settingsgeneration:max_tokens:openai: 4096anthropic: 4096gemini: 4096deepseek: 4096max_tokens_analysis: 4000temperature: 0.522 unmodified lines2324252627282930313222 unmodified lines# Generation Settingsgeneration:max_tokens:openai: 2048anthropic: 2048gemini: 2048deepseek: 2048max_tokens_analysis: 4000temperature: 0.5
243 unmodified lines24424524624724824925030 unmodified lines2812822832842852862872886 unmodified lines295296297298299300301302303304305306307308309310311312313290 unmodified lines604605606607608609610611612613614615616617618619620621622623624625626627628629630631632243 unmodified linesclass LLMAnalyzer:"""Class for handling different LLM providers."""def __init__(self, provider: ModelProvider, model_name: AnalysisModelName):self.provider = providerself.model_name = model_name30 unmodified linesasync def _analyze_with_openai(self, prompt: str, response_schema: dict) -> str:"""Analyze text using OpenAI."""messages = [ChatMessage(role="system", content=SYSTEM_PROMPT),ChatMessage(role="user", content=prompt)]6 unmodified lines}try:response = self.client.chat.completions.create(model=self.model_name,messages=[{"role": m.role, "content": m.content} for m in messages],response_format=response_format,temperature=0)response_text = response.choices[0].message.content# Verify it's valid JSONjson_data = extract_json_from_text(response_text)return json.dumps(json_data, ensure_ascii=False) if json_data else response_textexcept Exception as e:raise RuntimeError(f"Error in OpenAI analysis: {str(e)}")async def _analyze_with_deepseek(self, prompt: str) -> str:"""Analyze text using DeepSeek."""290 unmodified linesclient = OpenAI(api_key=OPENAI_API_KEY)try:print(f"[DEBUG] OpenAI Generation - Model: {model_name}")response = client.chat.completions.create(model=model_name,messages=[{"role": "system", "content": system_prompt},{"role": "user", "content": content},],temperature=GENERATION_TEMPERATURE,max_tokens=MAX_TOKENS_CONFIG["openai"],)response_text = response.choices[0].message.contentprint(f"[DEBUG] OpenAI response length: {len(response_text)}")json_response = extract_json_from_text(response_text)if json_response and all(key in json_response for key in ["title", "text", "proceeding", "category"]):return json_responseelse:print(f"[WARNING] Invalid JSON structure from OpenAI. Text: {response_text[:300]}...")raise ValueError("Invalid JSON structure")except Exception as e:print(f"[ERROR] OpenAI generation/parsing failed: {e}")return {"title": "Автоматично сформований заголовок (OpenAI)","text": response_text.strip() if 'response_text' in locals() else "Помилка при отриманні відповіді","proceeding": "Не визначено","category": "Помилка парсингу"}243 unmodified lines24424524624724824925030 unmodified lines2812822832842852862872882892902912922932942956 unmodified lines302303304305306307308309310311312313314315316317318319320321322323324325290 unmodified lines616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667243 unmodified linesclass LLMAnalyzer:"""Class for handling different LLM providers."""def __init__(self, provider: "ModelProvider", model_name: "AnalysisModelName"):self.provider = providerself.model_name = model_name30 unmodified linesasync def _analyze_with_openai(self, prompt: str, response_schema: dict) -> str:"""Analyze text using OpenAI."""# Determine model name and if it's a reasoning modelmodel_val = self.model_name.value if hasattr(self.model_name, "value") else str(self.model_name)is_reasoning_model = any(m in model_val.lower() for m in ["gpt-4.1", "gpt-4.5", "o1", "o3"])# Use developer role for newer modelsrole = "developer" if is_reasoning_model else "system"messages = [ChatMessage(role=role, content=SYSTEM_PROMPT),ChatMessage(role="user", content=prompt)]6 unmodified lines}try:completion_params = {"model": model_val,"messages": [{"role": m.role, "content": m.content} for m in messages],"response_format": response_format,}# Reasoning models usually require temperature=1.0 or noneif not is_reasoning_model:completion_params["temperature"] = 0response = self.client.chat.completions.create(**completion_params)response_text = response.choices[0].message.content# Verify it's valid JSONjson_data = extract_json_from_text(response_text)return json.dumps(json_data, ensure_ascii=False) if json_data else response_textexcept Exception as e:raise RuntimeError(f"Error in OpenAI analysis ({model_val}): {str(e)}")async def _analyze_with_deepseek(self, prompt: str) -> str:"""Analyze text using DeepSeek."""290 unmodified linesclient = OpenAI(api_key=OPENAI_API_KEY)try:print(f"[DEBUG] OpenAI Generation - Model: {model_name}")# Check for reasoning models (gpt-4.1, o1, etc.)is_reasoning_model = any(m in model_name.lower() for m in ["gpt-4.1", "gpt-4.5", "o1", "o3"])# Use developer role for newer models, system for othersrole = "developer" if is_reasoning_model else "system"messages = [{"role": role, "content": system_prompt},{"role": "user", "content": content},]# Parameters for chat completioncompletion_params = {"model": model_name,"messages": messages,}# Set tokens based on model capabilitiesif is_reasoning_model:completion_params["max_completion_tokens"] = MAX_TOKENS_CONFIG["openai"]else:completion_params["max_tokens"] = MAX_TOKENS_CONFIG["openai"]# Handle thinking/reasoningif thinking_enabled and is_reasoning_model:completion_params["reasoning_effort"] = thinking_level.lower()# Reasoning models usually don't support temperature or it must be 1.0else:completion_params["temperature"] = GENERATION_TEMPERATUREresponse = client.chat.completions.create(**completion_params)response_text = response.choices[0].message.contentprint(f"[DEBUG] OpenAI response length: {len(response_text) if response_text else 0}")json_response = extract_json_from_text(response_text)if json_response and all(key in json_response for key in ["title", "text", "proceeding", "category"]):return json_responseelse:print(f"[WARNING] Invalid JSON structure from OpenAI. Text: {response_text[:300] if response_text else 'None'}...")raise ValueError("Invalid JSON structure")except Exception as e:print(f"[ERROR] OpenAI generation/parsing failed: {e}")return {"title": "Автоматично сформований заголовок (OpenAI)","text": response_text.strip() if 'response_text' in locals() and response_text else f"Помилка при отриманні відповіді: {str(e)}","proceeding": "Не визначено","category": "Помилка парсингу"}
config/environments/default.yaml+4-4
main.py+56-21