Skip to content
anvakaPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

61 Commits

Folders and files

Repository files navigation

@anvaka/vue-llm (WIP)

Browser-only LLM client + Vue 3 plugin, provider adapters, and lightweight components.

Features

  • Provider factory with 10 built-in providers (OpenAI, Anthropic, AWS, Grok, Gemini, Ollama, Llama Server, OpenRouter, DeepSeek, Custom) – extend with registerProvider()
  • AWS runs on the Bedrock Mantle endpoint and exposes the entire catalog (Claude, GPT-OSS, Qwen, Mistral, Gemma, …) from one model list — each request is routed to the right API surface automatically (Claude → Anthropic Messages, everything else → OpenAI Chat Completions)
  • Accounts own the keys. One account per credential (an AWS key covers Mantle and Bedrock runtime, every region); models hang under it. Rotate a key once and every model follows — in every open tab
  • A searchable model picker over every model on every account: starred and recent first, readable names, which models have worked, live-catalog freshness, and per-chat reasoning effort
  • LocalStorage-based config store (custom storage adapter supported)
  • Streaming + promise requests via llmClient.stream()
  • Normalized usage + USD cost on every response (override built-in rates per app or per model)
  • Automatic prompt caching for Claude (Anthropic + Bedrock) — caches the system+tools prefix, plus the rolling conversation in agent loops; opt out with promptCache: false
  • Image input on every vision-capable provider from one message format, with over-cap images compressed automatically to the provider's limit
  • Vue plugin for dependency injection
  • useLLM() composable with reactive streaming state
  • Ready-to-use components: LLMModelPicker, LLMConfigModal, ProviderSelector
  • CSS variable theming (--llm-* tokens)

Quick Start

import { createApp } from 'vue'
import App from './App.vue'
import { LLMPlugin } from '@anvaka/vue-llm'
import '@anvaka/vue-llm/styles/variables.css'

createApp(App)
  .use(LLMPlugin, { autoInit: false, namespace: 'myllm' })
  .mount('#app')

Accounts and models

Credentials live on accounts; every model you use is a model entry that points at one. Five AWS models are five entries and ONE key.

account  { provider: 'bedrock', label: 'AWS', apiKey, region }
entry    { accountId, model: 'us.anthropic.claude-fable-5-2', temperature, … }
  • configStore.getConfig(id) still returns the old flat config (key, base URL and provider merged in from the account), so LLMClient and existing code are unchanged. Its configuredAt is the later of the entry's and the account's, so a client cache keyed on it rebuilds after a key rotation.
  • configStore.saveConfig(id, flatConfig) still works: the config is filed under the account holding that key. Saving an existing entry with a new key rotates its account (every sibling follows) rather than forking a second account.
  • One AWS account covers both transports. The model id decides: an inference-profile id (us./global./eu.…) goes to bedrock-runtime, anything else to Mantle. The picker merges every spelling of one model into one row.
  • Pin ids. <entryId>#effort=high is "this model, at high effort" for one consumer (a chat, a graph) without a duplicate entry; #effort=default sends no effort setting. makePinId / parsePinId build and read them, and getConfig() resolves them.
  • Outcomes are recorded per request: a rejected key marks the account, a "not enabled for your account" marks that one model. The picker shows both.
  • Migration from the old one-key-per-config storage is automatic and keeps a backup at <namespace>:configs.v1-backup. Configs that used different keys for one provider become different accounts (the settings screen offers Merge).

Components

LLMModelPicker

A chip that opens a searchable list of every model on every account. Picking a model you have never used creates its entry on the spot.

<script setup>
import { ref } from 'vue'
import { LLMModelPicker } from '@anvaka/vue-llm'
const chatModel = ref('')   // a pin id, stored wherever your chat lives
</script>
<template>
  <!-- bound: changes only this chat's model; ⌘↵ also makes it the default -->
  <LLMModelPicker v-model="chatModel" @open-accounts="showConfig = true" />
  <!-- unbound: shows and sets the app-wide active provider -->
  <LLMModelPicker @open-accounts="showConfig = true" />
</template>

Keys: ⌘/ (Ctrl+/) opens the picker nearest the focused element · ↑↓ move · ↵ pick · ⌘↵ pick and make default · ⇥ cycle effort · ←→ switch route (e.g. Bedrock us / global / Mantle) · type any model id to use it as-is. Each account's section says whether its list is live, partly live, the last good list, or the built-in fallback — and why.

LLMConfigModal

Accounts & models: add an account (verify the key against the live catalog first), rotate a key (checks it works, and for AWS that it belongs to the same AWS account), merge duplicate accounts, and edit a starred model's defaults (temperature, max tokens, default effort).

<script setup>
import { ref } from 'vue'
import { LLMConfigModal } from '@anvaka/vue-llm'
const showConfig = ref(false)
</script>
<template>
  <LLMConfigModal 
    :is-visible="showConfig" 
    @close="showConfig = false"
    @config-changed="onConfigChanged" 
  />
</template>

Props:

  • isVisible (Boolean) – controls modal visibility
  • editTarget (Object) – { name, focusField }: open a model's settings directly
  • showJudge (Boolean) – enable judge mode UI
  • showAllMode (Boolean) – show all providers including disabled

Events:

  • close – emitted when modal closes
  • configChanged – emitted when an account or model is saved/deleted

ProviderSelector

Plain dropdown of configured model entries (the active provider).

<script setup>
import { ProviderSelector } from '@anvaka/vue-llm'
</script>
<template>
  <ProviderSelector @changed="onProviderChanged" @open-config="showModal = true" />
</template>

StoredKeysManager (deprecated)

Still exported for existing apps; it now reads and writes account keys (see KeyStore below). New UIs should use LLMConfigModal.

useLLM Composable

Access the LLM client, config store, and key store with reactive helpers.

import { useLLM } from '@anvaka/vue-llm'

const {
  // Core objects
  client,              // LLMClient instance
  configStore,         // ConfigStore instance
  keyStore,            // KeyStore instance

  // Streaming with reactive state
  stream,              // (messages, options) => Promise - stream with reactive updates
  isStreaming,         // ref<boolean>
  streamContent,       // ref<string> - accumulated response
  streamThinking,      // ref<string> - accumulated thinking content

  // Config management
  getEnabledConfigs,   // () => config[] - enabled providers only
  getAllConfigs,       // () => config[] - all providers including disabled
  getActiveConfig,     // () => config | null
  getActiveProviderId, // () => string | null
  setActiveProviderId, // (id) => boolean
  saveConfig,          // (id, config) => boolean
  deleteConfig,        // (id) => boolean
  enableProvider,      // (id) => boolean
  disableProvider,     // (id) => boolean
  getAvailableModels,  // (providerType, config) => Promise<string[]>
  testConnection,      // (config) => Promise<string>
  refresh,             // () => Promise<void>

  // Accounts, model entries, catalogs
  listAccounts,        // () => account[]  (with masked key + identity, e.g. "AWS …9012")
  saveAccount,         // (account) => accountId
  setAccountKey,       // (accountId, apiKey) => boolean — rotate; every model follows
  deleteAccount,       // (accountId) => boolean — removes its model entries too
  mergeAccount,        // (fromId, toId) => boolean — entries keep their ids
  listEntries,         // () => entry[]
  ensureEntry,         // (accountId, model) => entryId — created on first use
  updateEntry,         // (entryId, patch) => boolean
  setStarred,          // (entryId, starred) => boolean
  getCatalog,          // (accountId) => cached catalog | null
  refreshCatalog,      // (accountId) => Promise<catalog> — live fetch + cache
  verifyAccount,       // (draftAccount) => Promise<catalog> — check a key, store nothing

  // Key management (compatibility view over account keys)
  getStoredKey,        // (providerType | accountId) => string | null
  storeKey,            // (providerType, apiKey, options) => boolean — rotates that account
  deleteStoredKey,     // (id) => boolean — refuses while models use the account
  hasStoredKey,        // (providerType) => boolean
  getAllStoredKeys,    // () => Record<string, KeyData>
  getStoredKeyMeta     // (id) => KeyMeta | null
} = useLLM()

A catalog is { models: [{ id, backend }], source: 'live' | 'partial' | 'stale' | 'builtin', fetchedAt, errors, newIds } — it never silently substitutes the built-in list.

Non-Vue Usage

For scripts outside Vue components, use the singleton exports:

import { llmClient, configStore, keyStore } from '@anvaka/vue-llm'

// Stream directly
const { content, usage, cost } = await llmClient.stream(
  { messages: [...] },
  chunk => console.log(chunk.fullContent)
)

// Manage configs
configStore.saveConfig('my-provider', { ... })
configStore.setActiveProviderId('my-provider')

Usage & Cost

Every response carries a normalized usage object and a USD cost breakdown when the model's rates are known. Stream chunks expose a running fullUsage so consumers can render a live cost counter.

const { content, usage, cost } = await client.stream({ messages: [...] })

usage // { inputTokens, outputTokens, totalTokens,
      //   cachedInputTokens?, cacheCreationInputTokens?, reasoningTokens?, raw }
cost  // { total, input, cachedInput, cacheCreation, output, currency, rates }
      // or null when the model isn't in the rates table

runAgentLoop aggregates usage across all iterations (each tool round-trip is one call) and emits a usage event per iteration:

const { messages, usage, cost } = await client.runAgentLoop({
  messages: [{ role: 'user', content: '7 * 11?' }],
  tools, executors,
  onEvent: ev => {
    if (ev.type === 'usage') console.log(`iter cost: ${ev.cost?.total}`)
  }
})

Prompt caching (Claude)

Anthropic and Bedrock requests are sent with cache_control markers by default, so repeated prefixes are read from cache instead of re-billed at full input price. Two prefixes are tagged:

  • System + tools — on every Claude request. The static prefix recurs identically across calls and runs within the cache TTL (~5 min).
  • Rolling conversation — added by runAgentLoop only, since it re-sends the whole growing transcript each turn. Iteration N reads iterations 1..N-1 from cache and only writes the new turn.

Cache hits and writes surface in the usual usage fields (cachedInputTokens, cacheCreationInputTokens) and are priced via the cachedInput / cacheCreation rate keys. No setup is required — prefixes under the model's minimum cacheable length simply aren't cached (no error).

Disable it per call or per provider config:

client.stream({ messages: [...], promptCache: false })   // single request
configStore.saveConfig('claude', { ...cfg, promptCache: false }) // all requests for this provider

Overriding rates

Built-in rates are sourced from public pricing pages and will drift. Three ways to override, in priority order:

// 1. Per-instance — wins over everything
import { LLMClient } from '@anvaka/vue-llm'
const client = new LLMClient({
  pricing: {
    openai: { 'gpt-4o': { input: 1.50, output: 6.00, cachedInput: 0.75 } }
  }
})

// 2. Global runtime override
import { registerPricing } from '@anvaka/vue-llm'
registerPricing('openai', 'gpt-4o', { input: 1.50, output: 6.00 })

// 3. Inline (without LLMClient)
import { calculateCost } from '@anvaka/vue-llm/pricing'
const cost = calculateCost(usage, { provider: 'openai', model: 'gpt-4o' })

Rate keys: input (uncached prompt, per 1M tokens, USD), output, optional cachedInput (prompt-cache hits — defaults to input if omitted), optional cacheCreation (Anthropic-only cache-write premium).

Model lookup is exact match first, then longest-prefix match — so registering claude-haiku-4-5 automatically covers claude-haiku-4-5-20251001.

// Pricing-only import (no Vue):
import { calculateCost, formatCost, registerPricing, DEFAULT_RATES } from '@anvaka/vue-llm/pricing'
formatCost(0.00012) // "$0.000120"

Images (vision)

Attach images by giving a message an array of content parts instead of a string. The parts are spelled the OpenAI way; the library converts them to each provider's own wire format.

const { content } = await client.stream({
  messages: [{
    role: 'user',
    content: [
      { type: 'text', text: 'What is in this screenshot?' },
      { type: 'image_url', image_url: { url: dataUrlFromFileInput } }
    ]
  }]
})

url is either a base64 data: URL — what a browser <input type="file"> + FileReader.readAsDataURL() gives you — or a remote http(s) URL. Plain string content still works exactly as before; you only reach for the array form when a message carries an image.

Images may appear on any user message, not just the last one, so multi-turn conversations and runAgentLoop keep working with images in their history.

What each provider does with it

Provider Wire shape Remote URLs
OpenAI, Grok, OpenRouter, llama.cpp, Custom image_url — the canonical part, verbatim yes
Anthropic image.source.{media_type, data} (base64) yes (source.type: 'url')
Anthropic via Bedrock base64 only no — rejected up front
Gemini inlineData.{mimeType, data} no — Files API URIs only
Ollama images: ['<raw base64>'], outside content no
Bedrock Responses API input_image data / s3:// only
DeepSeek — no vision model exists

The media type is carried from your data URL, so a PNG stays a PNG — unless it has to be compressed to fit the provider's cap, which re-encodes it as JPEG (see below).

Capability gating

Sending an image to a model that can't see it throws before the request is made, rather than silently dropping it and billing you for a confident answer about an image the model never received:

Model 'deepseek-chat' on provider 'deepseek' does not support image input.
Remove the image parts from the conversation or switch to a vision-capable model.

Check first with client.getCapabilities().includes('vision'), or supportsVision(modelId) from @anvaka/vue-llm/providers. Vision support is a model property (src/providers/visionPolicy.js) and is deny-listed — a model is assumed to see unless it's a known text-only family — so newly released models work without a library update.

Oversized images are compressed, not rejected

Providers cap image size, and Anthropic's cap is easy to get wrong: 5 MB per image measured on the base64 string, not the file. Base64 inflates by 4/3, so the effective file limit is ~3.75 MB — a 4.8 MB photo is rejected as 6755172 bytes > 5242880 bytes.

Rather than fail, the client re-encodes anything over the active provider's limit before sending. A phone photo is routinely over the cap, and the request would otherwise always error when a re-encode would have worked. It tries JPEG at full resolution first (usually enough on its own — a screenshot PNG can be 10× its JPEG equivalent), then steps the dimensions down.

This is automatic and needs no configuration. To observe or disable it:

await client.stream({
  messages,
  onImageResize: ({ fromBytes, toBytes, width, height, mime }) =>
    console.log(`shrank ${fromBytes} → ${toBytes} (${width}×${height})`),
  imageQuality: 0.85,   // JPEG quality for the re-encode (default 0.85)
  resizeImages: false   // send originals and let the provider decide
})

resizeImages and imageQuality also work as provider-config defaults. Text-heavy screenshots are the case to watch: a lower-resolution JPEG can cost the model detail it would have read from the original, so raise imageQuality (or set resizeImages: false and shrink deliberately) if OCR accuracy matters more than bytes. The limit comes from the provider (provider.maxImageBytes, in base64 bytes; null means no known cap), so Bedrock-Claude inherits Anthropic's 5 MB automatically.

Compression is browser-only (canvas). Off-DOM — Node, SSR — messages pass through untouched. The pieces are exported for direct use:

import { fitImageParts, shrinkImageDataUrl, encodedBytes, hasOversizedImages } from '@anvaka/vue-llm/providers'

Reasoning effort

Reasoning models expose a graded effort control — how hard the model thinks before answering. It's a sub-setting of thinking: it only takes effect when enableThinking is on, and it's clamped to whatever levels the chosen model actually supports.

const { content, thinking, usage } = await client.stream({
  messages: [{ role: 'user', content: 'Prove n^5 - n is divisible by 30.' }],
  enableThinking: true,      // required — effort does nothing without it
  reasoningEffort: 'high'    // 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'
})

thinking // the model's reasoning text, when the provider returns it (see below)
usage.reasoningTokens // reasoning-token count, when reported

You can also set reasoningEffort on a provider config (via LLMConfigModal or saveConfig) as the default for every request; a per-call value overrides it.

Supported levels are a property of the model (see src/providers/reasoningPolicy.js), and the request carries the level whichever transport reaches the model — native, Bedrock (anthropic.claude-*), or an OpenRouter proxy id (anthropic/claude-*):

Model family Levels
Claude Opus 4.7+, Sonnet/Opus/Fable 5 low · medium · high · xhigh · max
Claude Opus 4.6 low · medium · high · max
OpenAI gpt-5 minimal · low · medium · high
OpenAI o-series low · medium · high
everything else none (control hidden)

A requested level outside a model's range is snapped to the nearest supported one (max → high on gpt-5, etc.). supportsReasoningEffort(model) / effortLevelsFor(model) are exported from @anvaka/vue-llm/providers to drive UI.

Each transport spells effort in its own wire field (handled for you): OpenAI Chat reasoning_effort, OpenAI Responses reasoning.effort, OpenRouter reasoning: { enabled, effort }, Anthropic/Bedrock output_config: { effort } alongside thinking: { type: 'adaptive' }.

Seeing the reasoning text (Claude / Bedrock)

Claude only returns readable thinking text when the request asks for it via thinking.display: 'summarized' — which this library sends automatically. On Opus 4.7+ the display defaults to omitted, which returns an empty thinking block with only an encrypted signature (Opus 4.6 defaulted to summarized). If you build requests by hand, remember to set it or the reasoning will be invisible even though it ran and was billed.

Two more things worth knowing:

  • Adaptive thinking may skip thinking on easy prompts (0 reasoning tokens, empty thinking) even at high effort — the model decides. Use a genuinely hard prompt to see it engage.
  • DeepSeek reasoner returns reasoning text too (mapped from reasoning_content). Grok/Gemini/OpenAI reasoning models report token counts but not always text.

Theming

Override any --llm-* CSS variable globally or per container.

:root { --llm-accent: #ff7e41; }
html[data-theme='light'] { --llm-bg: #fff; }

Extending Providers

import { BaseProvider, registerProvider } from '@anvaka/vue-llm/providers'

class MyProvider extends BaseProvider { 
  /* implement abstract methods */ 
}
registerProvider('my-provider', MyProvider)

Available Exports

// From '@anvaka/vue-llm/providers'
import { 
  BaseProvider,
  PROVIDERS,           // { OPENAI, ANTHROPIC, BEDROCK, GROK, GEMINI, OLLAMA, LLAMA_SERVER, OPENROUTER, DEEPSEEK, CUSTOM }
  DEFAULT_CONFIGS,     // Default configs for each provider type
  createProvider,      // (type, config) => Provider
  registerProvider,    // (type, ProviderClass) => void
  createProviderFlexible, // (type, config) => Provider (includes custom-registered)

  // Reasoning effort (model-side policy)
  effortLevelsFor,     // (modelId) => string[] | null
  supportsReasoningEffort, resolveEffort, clampEffort, DEFAULT_EFFORT,

  // Images
  supportsVision,      // (modelId) => boolean — can this model accept images?
  parseImageUrl,       // (url) => { kind:'data', mime, b64 } | { kind:'remote', url }
  normalizeImagePart, contentText, hasImageContent, messagesHaveImages,
  fitImageParts,       // (messages, {maxBytes, onResize}) => Promise<messages>
  shrinkImageDataUrl,  // (dataUrl, maxBytes) => Promise<{url, mime, width, height} | null>
  encodedBytes,        // (dataUrl) => base64 payload size — what providers measure
  hasOversizedImages   // (messages, maxBytes) => boolean
} from '@anvaka/vue-llm/providers'

// Helper for creating config objects
import { createDefaultConfig } from '@anvaka/vue-llm'
const config = createDefaultConfig('openai') // Returns template config object

License

MIT

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages