File size: 2,944 Bytes
115b94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Official OpenAI endpoint, selectable server-owned medium routes; no secret copies."""
import json
import re
import time
from pathlib import Path
from src.adapters.llm.chat_completion import ChatCompletionProvider

ENDPOINT='https://api.openai.com/v1/chat/completions'
MODELS=('gpt-6.1-sol','gpt-6-astra','gpt-5.5')


def read_token(path):
    try:
        raw=Path(path).read_text(encoding='utf-8-sig')
        candidates=set(re.findall(r'(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]+',raw))
        if len(candidates)!=1:raise ValueError()
        return candidates.pop()
    except Exception:
        raise ValueError('OPENAI_CREDENTIAL_CONFIGURATION_INVALID') from None


class OpenAICodeProvider(ChatCompletionProvider):
    def __init__(self,*,model,token,transport=None):
        if model not in MODELS:raise ValueError('OPENAI_CODING_MODEL_NOT_ALLOWED')
        super().__init__(name='openai-'+model,endpoint=ENDPOINT,model=model,token=token,
            timeout=300,json_mode=True,transport=transport)
        from src.modules.llm_gateway.routing import VERSION
        self.routing_version=VERSION
        self.task_roles=['chat','design','diagnose','code','repair']
        self.selectable=True
        self.provider_family='openai'
        self.policy_version='openai-medium-v2'
        self.reasoning_effort='medium'
        self.health={'status':'not_probed'}

    def payload(self,messages,max_tokens):
        return {'model':self.model,'messages':messages,'max_completion_tokens':max_tokens,
            'reasoning_effort':self.reasoning_effort,'response_format':{'type':'json_object'},
            'stream':False,'store':False}


def providers_from_connection(connection_path):
    """Enable only exact, recently validated endpoint/credential/model bindings."""
    path=Path(connection_path)
    if not path.is_file():return []
    try:
        config=json.loads(path.read_text(encoding='utf8'))
        if config['endpoint']!=ENDPOINT or config['reasoning_effort']!='medium':raise ValueError()
        source=Path(config['credential_source'])
        health=json.loads((path.parent/'health.json').read_text(encoding='utf8'))
        if (health['endpoint']!=ENDPOINT or health['reasoning_effort']!='medium'
                or health['credential_source']!=str(source)
                or health['credential_mtime_ns']!=source.stat().st_mtime_ns
                or not 0<=time.time()-health['checked_at']<86400):
            return []
        token=read_token(source);result=[]
        for model in MODELS:
            row=health.get('models',{}).get(model,{})
            if row.get('status')!='healthy':continue
            p=OpenAICodeProvider(model=model,token=token)
            p.health={'status':'healthy','checked_at':health['checked_at'],
                'verified_scope':'bounded-java-code'};result.append(p)
        return result
    except Exception:
        raise ValueError('OPENAI_ROUTE_CONFIGURATION_INVALID') from None