File size: 3,799 Bytes
caf8059
 
 
 
 
 
 
 
 
 
5ca3c16
 
 
 
 
caf8059
 
 
 
 
 
5ca3c16
 
 
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
 
 
caf8059
 
 
 
5ca3c16
caf8059
 
5ca3c16
caf8059
 
 
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
67
68
69
70
71
72
73
"""Explicit, read-only credential bridge authorized for the local validation session."""
import re
from pathlib import Path
from urllib.parse import urlsplit
from src.adapters.llm.chat_completion import ChatCompletionProvider


def workos_provider(path, *, model='qwen3.8-flash'):
    # No environment export, original service import, persistent copy or exception echo.
    try:
        if Path(path).suffix == '.dpapi':
            from scripts.local_model_key import read
            raw = read(Path(path))
        else:
            raw = Path(path).read_text(encoding='utf-8-sig')
        values = {}
        for line in raw.splitlines():
            match = re.fullmatch(r'\s*(?:export\s+)?(DASHSCOPE_API_KEY|DASHSCOPE_BASE_URL)\s*=\s*(.*?)\s*', line)
            if match:
                values[match[1]] = match[2].strip('\"\'')
        token = values.get('DASHSCOPE_API_KEY')
        if not token:
            if raw.strip().startswith('sk-') and '\n' not in raw.strip():
                token = raw.strip()
        if not token:
            # Legacy WorkOS bootstrap also accepts one explicitly embedded key.
            # Reject ambiguity; do not guess among accounts or search other files.
            candidates = re.findall(r'(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]+', raw)
            if len(candidates) != 1:
                raise ValueError()
            token = candidates[0]
        # Providers also issue non-sk credentials; preserve the explicitly named value.
        # In particular, never replace a configured value with an example in a comment.
        if not re.fullmatch(r'[!-~]{8,8192}', token):
            raise ValueError()
        base = values.get('DASHSCOPE_BASE_URL', 'https://dashscope.aliyuncs.com/compatible-mode/v1').rstrip('/')
        url = urlsplit(base)
        if (url.scheme != 'https' or url.hostname not in {'dashscope.aliyuncs.com', 'dashscope-intl.aliyuncs.com',
                'dashscope-us.aliyuncs.com', 'cn-hongkong.dashscope.aliyuncs.com'}
                or url.path != '/compatible-mode/v1' or url.port not in {None, 443}
                or url.username or url.password or url.query or url.fragment):
            raise ValueError()
        return ChatCompletionProvider(name='workos-authorized-' + model, endpoint=base + '/chat/completions',
                                      model=model, token=token, timeout=120, enable_thinking=False)
    except Exception:
        raise ValueError('WORKOS_CREDENTIAL_CONFIGURATION_INVALID') from None


def bailian_providers(path, *, health_file=None):
    """Share the explicitly authorized in-memory credential across approved model routes."""
    import json
    from src.modules.llm_gateway.routing import PROFILES,VERSION
    base=workos_provider(path)
    health={}
    if health_file and Path(health_file).is_file():
        try:
            data=json.loads(Path(health_file).read_text(encoding='utf-8'))
            import time
            if data['endpoint']==base.endpoint and data['credential_mtime_ns']==Path(path).stat().st_mtime_ns:
                stale=time.time()-data['checked_at']>=86400
                health={name:{**row,**({'stale':True} if stale else {})} for name,row in data['models'].items()}
        except (ValueError,KeyError,TypeError,OSError):pass
    result=[]
    for model,profile in PROFILES.items():
        provider=ChatCompletionProvider(name='bailian-'+model,endpoint=base.endpoint,model=model,token=base._token,
            timeout=300,enable_thinking=profile['thinking'],json_mode=profile['json_mode'])
        provider.routing_version=VERSION
        provider.task_roles=profile['roles']
        provider.selectable=profile.get('selectable',False)
        provider.health=health.get(model,{'status':'not_probed'})
        result.append(provider)
    return result