VibeCoding / src /adapters /llm /workos_credentials.py
dellweb3's picture
Deploy verified conversational workbench and isolated Java application previews
5ca3c16 verified
Raw History Blame Contribute Delete
3.8 kB
"""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