Skip to content

Commit 176e0fd

Browse files
committed
feat(providers): allow per-provider HTTP/SOCKS proxy for LLM traffic
Route the LLM requests of a single provider through an optional proxy without affecting other providers or the process-wide env vars: - store extra_json.proxy on the provider row and forward it to the harness ProviderConfig (works with the octop-harness proxy field) - connectivity probes and remote model fetching also honor the proxy - return extra_json from the providers API so the UI can render it - dashboard: HTTP Proxy input in provider create/edit forms; test connection and fetch-models requests carry the proxy - add httpx[socks] so SOCKS proxy URLs work out of the box No DB schema change: proxy lives in the existing extra_json column.
1 parent e473dd3 commit 176e0fd

10 files changed

Lines changed: 126 additions & 2 deletions

File tree

‎dashboard/src/locales/en.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3194,6 +3194,8 @@
31943194
"nameLabel": "Name",
31953195
"namePlaceholder": "e.g., my-openai",
31963196
"baseUrlExtra": "OpenAI-compatible endpoint base URL. Leave blank to use the official default.",
3197+
"httpProxyLabel": "HTTP Proxy",
3198+
"httpProxyExtra": "Optional proxy for this provider's model requests only (e.g. http://127.0.0.1:7890). Leave empty for a direct connection.",
31973199
"defaultModelLabel": "Default Model",
31983200
"defaultModelPlaceholder": "e.g., gpt-4o-mini",
31993201
"noteLabel": "Note (optional)",

‎dashboard/src/locales/zh.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3192,6 +3192,8 @@
31923192
"nameLabel": "名称",
31933193
"namePlaceholder": "例如:my-openai",
31943194
"baseUrlExtra": "OpenAI 兼容 endpoint 的 base URL,留空则使用官方默认。",
3195+
"httpProxyLabel": "HTTP 代理",
3196+
"httpProxyExtra": "可选:仅该供应商的模型请求走此代理(如 http://127.0.0.1:7890),留空则直连。",
31953197
"defaultModelLabel": "默认模型",
31963198
"defaultModelPlaceholder": "例如:gpt-4o-mini",
31973199
"noteLabel": "备注(可选)",

‎dashboard/src/pages/Settings/Models/components/modals/CustomProviderModal.tsx‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ const KINDS = [
2828
{ value: "bedrock", labelKey: "bedrock" as const },
2929
];
3030

31+
/** Build ``extra_json`` from a draft proxy value (empty → ``null``). */
32+
function proxyExtraJson(proxy?: string): string | null {
33+
const trimmed = proxy?.trim();
34+
return trimmed ? JSON.stringify({ proxy: trimmed }) : null;
35+
}
36+
3137
export function CustomProviderModal({
3238
open,
3339
onClose,
@@ -44,6 +50,7 @@ export function CustomProviderModal({
4450
base_url?: string;
4551
api_key?: string;
4652
note?: string;
53+
proxy?: string;
4754
}>();
4855
const name = Form.useWatch("name", form) as string | undefined;
4956
const kind = Form.useWatch("kind", form) as string | undefined;
@@ -92,6 +99,7 @@ export function CustomProviderModal({
9299
base_url: values.base_url?.trim() || null,
93100
model_id: modelId,
94101
embedding: isEmbeddingModel(models.find((m) => m.id === modelId)),
102+
extra_json: proxyExtraJson(values.proxy),
95103
});
96104
};
97105

@@ -112,6 +120,7 @@ export function CustomProviderModal({
112120
kind: "openai",
113121
api_key: apiKey,
114122
base_url: (values.base_url as string | undefined)?.trim() || null,
123+
extra_json: proxyExtraJson(values.proxy as string | undefined),
115124
});
116125
if (!result.ok) {
117126
message.error(
@@ -184,6 +193,7 @@ export function CustomProviderModal({
184193
api_key: (values.api_key as string | undefined)?.trim() || null,
185194
models: modelEntries.length > 0 ? modelEntries : [],
186195
note: (values.note as string | undefined)?.trim() || null,
196+
extra_json: proxyExtraJson(values.proxy as string | undefined),
187197
}),
188198
});
189199
message.success(
@@ -262,6 +272,14 @@ export function CustomProviderModal({
262272
<Input placeholder="https://api.openai.com/v1" />
263273
</Form.Item>
264274

275+
<Form.Item
276+
name="proxy"
277+
label={t("models.httpProxyLabel")}
278+
extra={t("models.httpProxyExtra")}
279+
>
280+
<Input placeholder="http://127.0.0.1:7890" />
281+
</Form.Item>
282+
265283
<Form.Item name="api_key" label="API Key">
266284
<Input.Password placeholder="sk-..." visibilityToggle />
267285
</Form.Item>

‎dashboard/src/pages/Settings/Models/components/modals/ProviderConfigModal.tsx‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,41 @@ interface ProviderConfigForm {
6161
model?: string;
6262
note?: string;
6363
kind: string;
64+
proxy?: string;
65+
}
66+
67+
/** Read ``extra_json.proxy`` from a stored provider row ("" when absent). */
68+
function proxyFromExtra(extraJson?: string | null): string {
69+
if (!extraJson) return "";
70+
try {
71+
const extra = JSON.parse(extraJson) as Record<string, unknown>;
72+
return typeof extra.proxy === "string" ? extra.proxy : "";
73+
} catch {
74+
return "";
75+
}
76+
}
77+
78+
/**
79+
* Merge a draft proxy value into the original ``extra_json`` string.
80+
* Empty proxy removes the key; an empty object collapses to ``null``.
81+
*/
82+
function mergeExtraJson(
83+
original: string | null | undefined,
84+
proxy?: string,
85+
): string | null {
86+
let extra: Record<string, unknown> = {};
87+
if (original) {
88+
try {
89+
const parsed = JSON.parse(original) as Record<string, unknown>;
90+
if (parsed && typeof parsed === "object") extra = parsed;
91+
} catch {
92+
/* ignore malformed JSON */
93+
}
94+
}
95+
const trimmed = proxy?.trim();
96+
if (trimmed) extra.proxy = trimmed;
97+
else delete extra.proxy;
98+
return Object.keys(extra).length > 0 ? JSON.stringify(extra) : null;
6499
}
65100

66101
interface ProviderConfigModalProps {
@@ -663,6 +698,7 @@ export function ProviderConfigModal({
663698
api_key: undefined,
664699
model: currentDefaultModel,
665700
note: provider.note ?? "",
701+
proxy: proxyFromExtra(provider.extra_json),
666702
});
667703
setDraftModels(
668704
(provider.models ?? []).map((m) => ({
@@ -691,6 +727,10 @@ export function ProviderConfigModal({
691727
payload.api_key = values.api_key.trim();
692728
if ((values.note ?? "") !== (provider.note ?? ""))
693729
payload.note = values.note?.trim() || null;
730+
const draftProxy = values.proxy ?? "";
731+
if (draftProxy.trim() !== proxyFromExtra(provider.extra_json).trim()) {
732+
payload.extra_json = mergeExtraJson(provider.extra_json, draftProxy);
733+
}
694734
// default model
695735
const existingDefault = provider.models?.length
696736
? provider.models[0].id
@@ -825,6 +865,10 @@ export function ProviderConfigModal({
825865
base_url: draftBaseUrl || provider.base_url,
826866
model_id: modelId,
827867
embedding,
868+
extra_json: mergeExtraJson(
869+
provider.extra_json,
870+
values.proxy as string | undefined,
871+
),
828872
})
829873
: await request<{
830874
ok: boolean;
@@ -915,6 +959,10 @@ export function ProviderConfigModal({
915959
api_key: apiKey,
916960
base_url: draftBaseUrl || provider.base_url,
917961
name: provider.name,
962+
extra_json: mergeExtraJson(
963+
provider.extra_json,
964+
values.proxy as string | undefined,
965+
),
918966
});
919967
if (!result.ok) {
920968
message.error(
@@ -1018,6 +1066,14 @@ export function ProviderConfigModal({
10181066
<Input placeholder="https://api.openai.com/v1" />
10191067
</Form.Item>
10201068

1069+
<Form.Item
1070+
name="proxy"
1071+
label={t("models.httpProxyLabel")}
1072+
extra={t("models.httpProxyExtra")}
1073+
>
1074+
<Input placeholder="http://127.0.0.1:7890" />
1075+
</Form.Item>
1076+
10211077
<Form.Item name="api_key" label="API Key" extra={apiKeyExtra}>
10221078
<Input.Password
10231079
placeholder={apiKeyPlaceholder}

‎dashboard/src/pages/Settings/Models/useProviders.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ export interface ProviderRow {
7171
models: ProviderModel[];
7272
note: string | null;
7373
enabled: boolean;
74+
extra_json?: string | null;
7475
}
7576

7677
export interface UseProvidersResult {

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ dependencies = [
4545
"pypinyin>=0.53",
4646
"openpyxl>=3.1",
4747
"xlrd>=2.0.1",
48+
"httpx[socks]>=0.28.1",
4849
]
4950

5051
[project.optional-dependencies]

‎src/octop/api/routers/providers.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ def _row_to_dict(r: Any) -> dict[str, Any]:
135135
"models": models,
136136
"note": r.note,
137137
"enabled": bool(r.enabled),
138+
"extra_json": r.extra_json,
138139
}
139140

140141

‎src/octop/infra/agents/providers/probe.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,21 @@ def provider_headers(row: Any) -> dict[str, str]:
3535
return dict(headers) if isinstance(headers, dict) else {}
3636

3737

38+
def provider_proxy(row: Any) -> str | None:
39+
"""Return the optional ``extra_json.proxy`` value (trimmed) or ``None``."""
40+
raw = getattr(row, "extra_json", None)
41+
if not raw:
42+
return None
43+
try:
44+
extra = json.loads(raw)
45+
except json.JSONDecodeError:
46+
return None
47+
if not isinstance(extra, dict) or not extra.get("proxy"):
48+
return None
49+
proxy = str(extra["proxy"]).strip()
50+
return proxy or None
51+
52+
3853
def _is_codex_base_url(base_url: str | None) -> bool:
3954
return bool(base_url and "chatgpt.com/backend-api/codex" in base_url)
4055

@@ -64,6 +79,12 @@ def build_probe_chat_model(row: Any, *, model_id: str | None = None) -> Any:
6479
}
6580
if headers:
6681
kwargs["default_headers"] = dict(headers)
82+
proxy = provider_proxy(row)
83+
if proxy:
84+
import httpx
85+
86+
kwargs["http_client"] = httpx.Client(proxy=proxy, trust_env=False)
87+
kwargs["http_async_client"] = httpx.AsyncClient(proxy=proxy, trust_env=False)
6788
return ChatOpenAI(**kwargs)
6889

6990
provider = ProviderConfig(
@@ -73,6 +94,7 @@ def build_probe_chat_model(row: Any, *, model_id: str | None = None) -> Any:
7394
base_url=base_url,
7495
api_key=row.api_key or "",
7596
headers=headers,
97+
proxy=provider_proxy(row),
7698
)
7799
return build_chat_model(provider, model)
78100

‎src/octop/infra/agents/providers/store.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,15 @@ def build_harness_configs(self) -> list[ProviderConfig]:
141141
if not models:
142142
continue
143143
headers: dict[str, str] = {}
144+
proxy: str | None = None
144145
if row.extra_json:
145146
try:
146147
extra = json.loads(row.extra_json)
147-
if isinstance(extra, dict) and isinstance(extra.get("headers"), dict):
148-
headers = {str(k): str(v) for k, v in extra["headers"].items()}
148+
if isinstance(extra, dict):
149+
if isinstance(extra.get("headers"), dict):
150+
headers = {str(k): str(v) for k, v in extra["headers"].items()}
151+
if extra.get("proxy"):
152+
proxy = str(extra["proxy"]).strip() or None
149153
except Exception:
150154
pass
151155
out.append(
@@ -157,6 +161,7 @@ def build_harness_configs(self) -> list[ProviderConfig]:
157161
name=row.name,
158162
models=models,
159163
headers=headers,
164+
proxy=proxy,
160165
session_header=session_header_for_provider(row.name, row.base_url),
161166
)
162167
)

‎uv.lock‎

Lines changed: 16 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)