11"""AI services."""
2+
23from __future__ import annotations
34
45import json
6+ import logging
57from typing import Any , Dict , Generator
68
7- import httpx
89from django .conf import settings
910from django .core .exceptions import ImproperlyConfigured
1011
11- from core import enums
12+ import httpx
1213
13- import logging
14+ from core import enums
1415
1516if settings .LANGFUSE_PUBLIC_KEY :
1617 from langfuse .openai import OpenAI
1718else :
1819 from openai import OpenAI , OpenAIError
19-
20+
2021log = logging .getLogger (__name__ )
2122
2223
@@ -146,7 +147,6 @@ def translate(self, text, language):
146147 system_content = AI_TRANSLATE .format (language = language_display )
147148 return self .call_ai_api (system_content , text )
148149
149-
150150 def _filtered_headers (self , incoming_headers : Dict [str , str ]) -> Dict [str , str ]:
151151 hop_by_hop = {"host" , "connection" , "content-length" , "accept-encoding" }
152152 out : Dict [str , str ] = {}
@@ -189,22 +189,34 @@ def _harden_payload(self, payload: Dict[str, Any]) -> Dict[str, Any]:
189189
190190 # Force tool call if tools exist
191191 if payload .get ("tools" ):
192- payload ["tool_choice" ] = {"type" : "function" , "function" : {"name" : "applyDocumentOperations" }}
192+ payload ["tool_choice" ] = {
193+ "type" : "function" ,
194+ "function" : {"name" : "applyDocumentOperations" },
195+ }
193196
194197 # Convert non-standard "required"
195198 if payload .get ("tool_choice" ) == "required" :
196- payload ["tool_choice" ] = {"type" : "function" , "function" : {"name" : "applyDocumentOperations" }}
199+ payload ["tool_choice" ] = {
200+ "type" : "function" ,
201+ "function" : {"name" : "applyDocumentOperations" },
202+ }
197203
198204 # Inject strict system prompt once
199205 msgs = payload .get ("messages" )
200206 if isinstance (msgs , list ):
201207 need = True
202208 if msgs and isinstance (msgs [0 ], dict ) and msgs [0 ].get ("role" ) == "system" :
203209 c = msgs [0 ].get ("content" ) or ""
204- if isinstance (c , str ) and "applyDocumentOperations" in c and "blocks" in c :
210+ if (
211+ isinstance (c , str )
212+ and "applyDocumentOperations" in c
213+ and "blocks" in c
214+ ):
205215 need = False
206216 if need :
207- payload ["messages" ] = [{"role" : "system" , "content" : BLOCKNOTE_TOOL_STRICT_PROMPT }] + msgs
217+ payload ["messages" ] = [
218+ {"role" : "system" , "content" : BLOCKNOTE_TOOL_STRICT_PROMPT }
219+ ] + msgs
208220
209221 return _drop_nones (payload )
210222
@@ -214,7 +226,7 @@ def _maybe_harden_json_body(self, body: bytes, headers: Dict[str, str]) -> bytes
214226 return body
215227 try :
216228 payload = json .loads (body .decode ("utf-8" ))
217- except Exception :
229+ except json . JSONDecodeError :
218230 return body
219231 if isinstance (payload , dict ):
220232 payload = self ._harden_payload (payload )
@@ -234,7 +246,9 @@ def stream_proxy(
234246
235247 timeout = httpx .Timeout (connect = 10.0 , read = 300.0 , write = 60.0 , pool = 10.0 )
236248 with httpx .Client (timeout = timeout , follow_redirects = False ) as client :
237- with client .stream (method .upper (), url , headers = req_headers , content = req_body ) as r :
249+ with client .stream (
250+ method .upper (), url , headers = req_headers , content = req_body
251+ ) as r :
238252 for chunk in r .iter_bytes ():
239253 if chunk :
240254 yield chunk
0 commit comments