feat: add OpenCode Go provider and support for custom models
- Introduced OpenCode Go provider with relevant configurations. - Enhanced model management by allowing users to add and delete custom models. - Updated UI components to support model selection for image types. - Adjusted sidebar visibility to include image media kinds.
This commit is contained in:
@@ -823,6 +823,10 @@ function GenericExampleCard({ providerId, kind }) {
|
||||
const exConfig = KIND_EXAMPLE_CONFIG[kind];
|
||||
if (!kindConfig || !exConfig) return null;
|
||||
|
||||
// Get models for this kind (e.g., type="image")
|
||||
const kindModels = getModelsByProviderId(providerId).filter((m) => m.type === kind);
|
||||
const [selectedModel, setSelectedModel] = useState(kindModels[0]?.id ?? "");
|
||||
|
||||
const [input, setInput] = useState(exConfig.defaultInput);
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [useTunnel, setUseTunnel] = useState(false);
|
||||
@@ -848,9 +852,10 @@ function GenericExampleCard({ providerId, kind }) {
|
||||
|
||||
const endpoint = useTunnel ? tunnelEndpoint : localEndpoint;
|
||||
const apiPath = kindConfig.endpoint.path;
|
||||
const modelFull = selectedModel ? `${providerAlias}/${selectedModel}` : "";
|
||||
|
||||
const requestBody = {
|
||||
model: `${providerAlias}/model-name`,
|
||||
model: modelFull,
|
||||
[exConfig.bodyKey]: input,
|
||||
...exConfig.extraBody,
|
||||
};
|
||||
@@ -861,7 +866,7 @@ function GenericExampleCard({ providerId, kind }) {
|
||||
-d '${JSON.stringify(requestBody)}'`;
|
||||
|
||||
const handleRun = async () => {
|
||||
if (!input.trim()) return;
|
||||
if (!input.trim() || !modelFull) return;
|
||||
setRunning(true);
|
||||
setError("");
|
||||
setResult(null);
|
||||
@@ -869,7 +874,7 @@ function GenericExampleCard({ providerId, kind }) {
|
||||
try {
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
|
||||
const body = { ...requestBody, model: `${providerAlias}/model-name` };
|
||||
const body = { ...requestBody, model: modelFull };
|
||||
const res = await fetch(`/api${apiPath}`, {
|
||||
method: kindConfig.endpoint.method,
|
||||
headers,
|
||||
@@ -892,6 +897,21 @@ function GenericExampleCard({ providerId, kind }) {
|
||||
<Card>
|
||||
<h2 className="text-lg font-semibold mb-4">Example</h2>
|
||||
<div className="flex flex-col gap-2.5">
|
||||
{/* Model selector - only show if models available */}
|
||||
{kindModels.length > 0 && (
|
||||
<Row label="Model">
|
||||
<select
|
||||
value={selectedModel}
|
||||
onChange={(e) => setSelectedModel(e.target.value)}
|
||||
className="w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
|
||||
>
|
||||
{kindModels.map((m) => (
|
||||
<option key={m.id} value={m.id}>{m.name || m.id}</option>
|
||||
))}
|
||||
</select>
|
||||
</Row>
|
||||
)}
|
||||
|
||||
{/* Endpoint */}
|
||||
<Row label="Endpoint">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -953,11 +973,11 @@ function GenericExampleCard({ providerId, kind }) {
|
||||
<span className="material-symbols-outlined text-[14px]">{copiedCurl ? "check" : "content_copy"}</span>
|
||||
{copiedCurl ? "Copied" : "Copy"}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleRun}
|
||||
disabled={running || !input.trim()}
|
||||
className="flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<button
|
||||
onClick={handleRun}
|
||||
disabled={running || !input.trim() || !modelFull}
|
||||
className="flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<span className="material-symbols-outlined text-[14px]" style={running ? { animation: "spin 1s linear infinite" } : undefined}>
|
||||
play_arrow
|
||||
</span>
|
||||
@@ -990,6 +1010,13 @@ function GenericExampleCard({ providerId, kind }) {
|
||||
<pre className="bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre opacity-70">
|
||||
{result ? resultJson : exConfig.defaultResponse}
|
||||
</pre>
|
||||
{kind === "image" && result?.data?.data?.[0] && (
|
||||
<img
|
||||
src={result.data.data[0].b64_json ? `data:image/png;base64,${result.data.data[0].b64_json}` : result.data.data[0].url}
|
||||
alt="Generated"
|
||||
className="max-w-full rounded-lg border border-border mt-2"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -111,6 +111,7 @@ AddCustomModelModal.propTypes = {
|
||||
export default function ModelsCard({ providerId, kindFilter }) {
|
||||
const { copied, copy } = useCopyToClipboard();
|
||||
const [modelAliases, setModelAliases] = useState({});
|
||||
const [customModels, setCustomModels] = useState([]);
|
||||
const [modelTestResults, setModelTestResults] = useState({});
|
||||
const [testingModelId, setTestingModelId] = useState(null);
|
||||
const [testError, setTestError] = useState("");
|
||||
@@ -118,17 +119,21 @@ export default function ModelsCard({ providerId, kindFilter }) {
|
||||
const [connections, setConnections] = useState([]);
|
||||
|
||||
const providerAlias = getProviderAlias(providerId);
|
||||
const effectiveType = kindFilter || "llm";
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const [aliasRes, connRes] = await Promise.all([
|
||||
const [aliasRes, connRes, customRes] = await Promise.all([
|
||||
fetch("/api/models/alias"),
|
||||
fetch("/api/providers", { cache: "no-store" }),
|
||||
fetch("/api/models/custom", { cache: "no-store" }),
|
||||
]);
|
||||
const aliasData = await aliasRes.json();
|
||||
const connData = await connRes.json();
|
||||
const customData = await customRes.json();
|
||||
if (aliasRes.ok) setModelAliases(aliasData.aliases || {});
|
||||
if (connRes.ok) setConnections((connData.connections || []).filter((c) => c.provider === providerId));
|
||||
if (customRes.ok) setCustomModels(customData.models || []);
|
||||
} catch (e) { console.log("ModelsCard fetch error:", e); }
|
||||
}, [providerId]);
|
||||
|
||||
@@ -153,6 +158,25 @@ export default function ModelsCard({ providerId, kindFilter }) {
|
||||
} catch (e) { console.log("delete alias error:", e); }
|
||||
};
|
||||
|
||||
const handleAddCustomModel = async (modelId) => {
|
||||
try {
|
||||
const res = await fetch("/api/models/custom", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ providerAlias, id: modelId, type: effectiveType }),
|
||||
});
|
||||
if (res.ok) await fetchData();
|
||||
} catch (e) { console.log("add custom model error:", e); }
|
||||
};
|
||||
|
||||
const handleDeleteCustomModel = async (modelId) => {
|
||||
try {
|
||||
const params = new URLSearchParams({ providerAlias, id: modelId, type: effectiveType });
|
||||
const res = await fetch(`/api/models/custom?${params}`, { method: "DELETE" });
|
||||
if (res.ok) await fetchData();
|
||||
} catch (e) { console.log("delete custom model error:", e); }
|
||||
};
|
||||
|
||||
const handleTestModel = async (modelId) => {
|
||||
if (testingModelId) return;
|
||||
setTestingModelId(modelId);
|
||||
@@ -171,28 +195,23 @@ export default function ModelsCard({ providerId, kindFilter }) {
|
||||
} finally { setTestingModelId(null); }
|
||||
};
|
||||
|
||||
// Get models — filter by kindFilter if provided
|
||||
const allModels = getModelsByProviderId(providerId);
|
||||
const displayModels = kindFilter
|
||||
? allModels.filter((m) => {
|
||||
// Built-in models — filter by kindFilter if provided
|
||||
const allBuiltIn = getModelsByProviderId(providerId);
|
||||
const builtInModels = kindFilter
|
||||
? allBuiltIn.filter((m) => {
|
||||
if (m.kinds) return m.kinds.includes(kindFilter);
|
||||
if (m.type) return m.type === kindFilter;
|
||||
return kindFilter === "llm";
|
||||
return (m.type || "llm") === kindFilter;
|
||||
})
|
||||
: allModels;
|
||||
: allBuiltIn;
|
||||
|
||||
// Custom models added via alias
|
||||
const customModels = Object.entries(modelAliases)
|
||||
.filter(([alias, fullModel]) => {
|
||||
const prefix = `${providerAlias}/`;
|
||||
if (!fullModel.startsWith(prefix)) return false;
|
||||
const modelId = fullModel.slice(prefix.length);
|
||||
return !displayModels.some((m) => m.id === modelId) && alias === modelId;
|
||||
})
|
||||
.map(([alias, fullModel]) => ({
|
||||
id: fullModel.slice(`${providerAlias}/`.length),
|
||||
alias,
|
||||
}));
|
||||
// Custom models for this provider + kind, dedupe vs built-in
|
||||
const myCustomModels = customModels.filter(
|
||||
(m) => m.providerAlias === providerAlias
|
||||
&& (m.type || "llm") === effectiveType
|
||||
&& !builtInModels.some((b) => b.id === m.id)
|
||||
);
|
||||
|
||||
const displayModels = builtInModels;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -224,16 +243,15 @@ export default function ModelsCard({ providerId, kindFilter }) {
|
||||
);
|
||||
})}
|
||||
|
||||
{customModels.map((model) => (
|
||||
{myCustomModels.map((model) => (
|
||||
<ModelRow
|
||||
key={model.id}
|
||||
model={{ id: model.id }}
|
||||
key={`${model.id}-${model.type}`}
|
||||
model={{ id: model.id, name: model.name }}
|
||||
fullModel={`${providerAlias}/${model.id}`}
|
||||
alias={model.alias}
|
||||
copied={copied}
|
||||
onCopy={copy}
|
||||
onSetAlias={() => {}}
|
||||
onDeleteAlias={() => handleDeleteAlias(model.alias)}
|
||||
onDeleteAlias={() => handleDeleteCustomModel(model.id)}
|
||||
testStatus={modelTestResults[model.id]}
|
||||
onTest={connections.length > 0 ? () => handleTestModel(model.id) : undefined}
|
||||
isTesting={testingModelId === model.id}
|
||||
@@ -254,7 +272,7 @@ export default function ModelsCard({ providerId, kindFilter }) {
|
||||
<AddCustomModelModal
|
||||
isOpen={showAddCustomModel}
|
||||
onSave={async (modelId) => {
|
||||
await handleSetAlias(modelId, modelId);
|
||||
await handleAddCustomModel(modelId);
|
||||
setShowAddCustomModel(false);
|
||||
}}
|
||||
onClose={() => setShowAddCustomModel(false)}
|
||||
|
||||
48
src/app/api/models/custom/route.js
Normal file
48
src/app/api/models/custom/route.js
Normal file
@@ -0,0 +1,48 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getCustomModels, addCustomModel, deleteCustomModel } from "@/models";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// GET /api/models/custom - List all custom models
|
||||
export async function GET() {
|
||||
try {
|
||||
const models = await getCustomModels();
|
||||
return NextResponse.json({ models });
|
||||
} catch (error) {
|
||||
console.log("Error fetching custom models:", error);
|
||||
return NextResponse.json({ error: "Failed to fetch custom models" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/models/custom - Add custom model
|
||||
export async function POST(request) {
|
||||
try {
|
||||
const { providerAlias, id, type, name } = await request.json();
|
||||
if (!providerAlias || !id) {
|
||||
return NextResponse.json({ error: "providerAlias and id required" }, { status: 400 });
|
||||
}
|
||||
const added = await addCustomModel({ providerAlias, id, type: type || "llm", name });
|
||||
return NextResponse.json({ success: true, added });
|
||||
} catch (error) {
|
||||
console.log("Error adding custom model:", error);
|
||||
return NextResponse.json({ error: "Failed to add custom model" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/models/custom?providerAlias=xxx&id=yyy&type=zzz
|
||||
export async function DELETE(request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const providerAlias = searchParams.get("providerAlias");
|
||||
const id = searchParams.get("id");
|
||||
const type = searchParams.get("type") || "llm";
|
||||
if (!providerAlias || !id) {
|
||||
return NextResponse.json({ error: "providerAlias and id required" }, { status: 400 });
|
||||
}
|
||||
await deleteCustomModel({ providerAlias, id, type });
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.log("Error deleting custom model:", error);
|
||||
return NextResponse.json({ error: "Failed to delete custom model" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
16
src/app/api/v1/images/generations/route.js
Normal file
16
src/app/api/v1/images/generations/route.js
Normal file
@@ -0,0 +1,16 @@
|
||||
import { handleImageGeneration } from "@/sse/handlers/imageGeneration.js";
|
||||
|
||||
export async function OPTIONS() {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "*",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** POST /v1/images/generations - OpenAI-compatible image generation endpoint */
|
||||
export async function POST(request) {
|
||||
return await handleImageGeneration(request);
|
||||
}
|
||||
Reference in New Issue
Block a user