Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/api/providers/fetchers/modelCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ export const getModels = async (
models = await getGlamaModels()
break
case "unbound":
models = await getUnboundModels()
// Unbound models endpoint requires an API key to fetch application specific models
models = await getUnboundModels(apiKey)
break
case "litellm":
if (apiKey && baseUrl) {
Expand Down
11 changes: 9 additions & 2 deletions src/api/providers/fetchers/unbound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@ import axios from "axios"

import { ModelInfo } from "../../../shared/api"

export async function getUnboundModels(): Promise<Record<string, ModelInfo>> {
export async function getUnboundModels(apiKey?: string | null): Promise<Record<string, ModelInfo>> {
const models: Record<string, ModelInfo> = {}

try {
const response = await axios.get("https://api.getunbound.ai/models")
const headers: Record<string, string> = {}

if (apiKey) {
headers["Authorization"] = `Bearer ${apiKey}`
}

const response = await axios.get("https://api.getunbound.ai/models", { headers })

if (response.data) {
const rawModels: Record<string, any> = response.data
Expand Down Expand Up @@ -40,6 +46,7 @@ export async function getUnboundModels(): Promise<Record<string, ModelInfo>> {
}
} catch (error) {
console.error(`Error fetching Unbound models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`)
return {}
}

return models
Expand Down
104 changes: 103 additions & 1 deletion webview-ui/src/components/settings/providers/Unbound.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { useCallback } from "react"
import { useCallback, useState } from "react"
import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import { useQueryClient } from "@tanstack/react-query"

import { ProviderSettings, RouterModels, unboundDefaultModelId } from "@roo/shared/api"

import { useAppTranslation } from "@src/i18n/TranslationContext"
import { VSCodeButtonLink } from "@src/components/common/VSCodeButtonLink"
import { vscode } from "@src/utils/vscode"
import { Button } from "@src/components/ui"

import { inputEventTransform } from "../transforms"
import { ModelPicker } from "../ModelPicker"
Expand All @@ -17,6 +20,9 @@ type UnboundProps = {

export const Unbound = ({ apiConfiguration, setApiConfigurationField, routerModels }: UnboundProps) => {
const { t } = useAppTranslation()
const [didRefetch, setDidRefetch] = useState<boolean>()
const [isInvalidKey, setIsInvalidKey] = useState<boolean>(false)
const queryClient = useQueryClient()

const handleInputChange = useCallback(
<K extends keyof ProviderSettings, E>(
Expand All @@ -29,6 +35,80 @@ export const Unbound = ({ apiConfiguration, setApiConfigurationField, routerMode
[setApiConfigurationField],
)

const saveConfiguration = useCallback(async () => {
vscode.postMessage({
type: "upsertApiConfiguration",
text: "default",
apiConfiguration: apiConfiguration,
})

const waitForStateUpdate = new Promise<void>((resolve) => {
const messageHandler = (event: MessageEvent) => {
const message = event.data
if (message.type === "state") {
window.removeEventListener("message", messageHandler)
resolve()
}
}
window.addEventListener("message", messageHandler)
})

await waitForStateUpdate
}, [apiConfiguration])

const requestModels = useCallback(async () => {
vscode.postMessage({ type: "flushRouterModels", text: "unbound" })

const modelsPromise = new Promise<void>((resolve) => {
const messageHandler = (event: MessageEvent) => {
const message = event.data
if (message.type === "routerModels") {
window.removeEventListener("message", messageHandler)
resolve()
}
}
window.addEventListener("message", messageHandler)
})

vscode.postMessage({ type: "requestRouterModels" })

await modelsPromise

await queryClient.invalidateQueries({ queryKey: ["routerModels"] })

// After refreshing models, check if current model is in the updated list
// If not, select the first available model
const updatedModels = queryClient.getQueryData<{ unbound: RouterModels }>(["routerModels"])?.unbound
if (updatedModels && Object.keys(updatedModels).length > 0) {
const currentModelId = apiConfiguration?.unboundModelId
const modelExists = currentModelId && Object.prototype.hasOwnProperty.call(updatedModels, currentModelId)

if (!currentModelId || !modelExists) {
const firstAvailableModelId = Object.keys(updatedModels)[0]
setApiConfigurationField("unboundModelId", firstAvailableModelId)
}
}

if (!updatedModels || Object.keys(updatedModels).includes("error")) {
return false
} else {
return true
}
}, [queryClient, apiConfiguration, setApiConfigurationField])

const handleRefresh = useCallback(async () => {
await saveConfiguration()
const requestModelsResult = await requestModels()

if (requestModelsResult) {
setDidRefetch(true)
setTimeout(() => setDidRefetch(false), 2000)
} else {
setIsInvalidKey(true)
setTimeout(() => setIsInvalidKey(false), 2000)
}
}, [saveConfiguration, requestModels])

return (
<>
<VSCodeTextField
Expand All @@ -47,6 +127,28 @@ export const Unbound = ({ apiConfiguration, setApiConfigurationField, routerMode
{t("settings:providers.getUnboundApiKey")}
</VSCodeButtonLink>
)}
<div className="flex justify-end">
<Button variant="outline" onClick={handleRefresh} className="w-1/2 max-w-xs">
<div className="flex items-center gap-2 justify-center">
<span className="codicon codicon-refresh" />
{t("settings:providers.refreshModels.label")}
</div>
</Button>
</div>
{didRefetch && (
<div className="flex items-center text-vscode-charts-green">
{t("settings:providers.refreshModels.success", {
defaultValue: "Models list updated! You can now select from the latest models.",
})}
</div>
)}
{isInvalidKey && (
<div className="flex items-center text-vscode-errorForeground">
{t("settings:providers.invalidApiKey", {
defaultValue: "Invalid API key. Please check your API key and try again.",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use Translate mode to add translations for these strings in all supported languages? We prefer to just translate into all and not have a defaultValue. Happy to help, let me know.

})}
</div>
)}
<ModelPicker
apiConfiguration={apiConfiguration}
defaultModelId={unboundDefaultModelId}
Expand Down