### Development setup and test commands Source: https://github.com/keyveve/veqen-sdks/blob/main/README.md Commands to install the Python package in editable mode with test dependencies, run the Python test suite, install JavaScript dependencies, and run JS tests. Requires Python and Node.js environments. ```sh python -m pip install -e 'python[test]' python -m pytest python/tests cd js npm ci --ignore-scripts npm test ``` -------------------------------- ### Run locally with npm commands Source: https://github.com/keyveve/veqen-sdks/blob/main/examples/vercel-ai-cost-starter/README.md Install dependencies, run tests, and start the development server. Requires Node.js 22 or later. After starting, open http://localhost:3000. ```sh npm ci npm test npm run dev ``` -------------------------------- ### Install Python SDK with pip Source: https://github.com/keyveve/veqen-sdks/blob/main/README.md Install the Veqen Python SDK version 1.x. Requires Python 3.10+ and has no runtime dependencies. ```sh pip install 'veqen>=1,<2' ``` -------------------------------- ### Install JavaScript SDK with npm Source: https://github.com/keyveve/veqen-sdks/blob/main/README.md Install the Veqen JavaScript SDK version 1.x. Requires Node.js 20+, ESM, TypeScript declarations, and no runtime dependencies. ```sh npm install @veqen/sdk@^1 ``` -------------------------------- ### Register VeqenLogger with LiteLLM Source: https://github.com/keyveve/veqen-sdks/blob/main/python/README.md Install veqen[litellm]>=1.1.0 and register the VeqenLogger as a LiteLLM callback. Call veqen.init() optionally with VEQEN_API_KEY for the hosted ledger. The logger copies allowlisted cost metadata, not prompts or responses, and observes completed calls without enforcing pre-call budgets. ```python import litellm import veqen from veqen.integrations.litellm_logger import VeqenLogger veqen.init() # optional VEQEN_API_KEY for the hosted ledger litellm.callbacks = [VeqenLogger()] ``` -------------------------------- ### Usage Example Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-integrations.md Example showing how to register the VeqenTracingProcessor with the OpenAI Agents SDK. ```python from agents import add_trace_processor from veqen.integrations.openai_agents import VeqenTracingProcessor add_trace_processor(VeqenTracingProcessor(feature="support-agent")) ``` -------------------------------- ### Install veqen-pricebook and @veqen/pricebook Source: https://github.com/keyveve/veqen-sdks/blob/main/pricebook-packages/js/README.md Install the Python and npm packages. No runtime dependencies, no network requests, no account or API key required. ```bash pip install veqen-pricebook npm install @veqen/pricebook ``` -------------------------------- ### Example usage of veqen.flush Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-core.md Example showing how to initialize Veqen and flush events before shutdown, with a warning if some events were not uploaded. ```python import veqen veqen.init(api_key=os.environ["VEQEN_API_KEY"]) # ... request handling ... ok = veqen.flush(timeout=3.0) if not ok: log.warning("some Veqen events were not uploaded before shutdown") ``` -------------------------------- ### Install @veqen/sdk with npm Source: https://github.com/keyveve/veqen-sdks/blob/main/js/README.md Install the veqen SDK package. Requires Node.js 20+, ESM, no dependencies, TypeScript types included. ```bash npm install @veqen/sdk ``` -------------------------------- ### Install veqen with pip Source: https://github.com/keyveve/veqen-sdks/blob/main/python/README.md Install the base veqen package. Requires Python 3.10+ and works offline with no dependencies. Optional integrations include veqen[langchain], veqen[litellm], veqen[llamaindex], and veqen[haystack] (Python 3.11+ for Haystack). ```bash pip install veqen ``` -------------------------------- ### Wrap OpenAI client and tag requests in JavaScript Source: https://github.com/keyveve/veqen-sdks/blob/main/README.md Wrap an OpenAI client with wrap and use withTags to attribute requests to a customer. Works locally without an account. ```javascript import OpenAI from "openai"; import { wrap, withTags } from "@veqen/sdk"; const client = wrap(new OpenAI(), { feature: "support-bot" }); await withTags({ customer: "acme" }, () => client.responses.create({ model: "gpt-5-mini", input: "Where is my order?" })); ``` -------------------------------- ### Install langchain-veqen and langchain-openai Source: https://github.com/keyveve/veqen-sdks/blob/main/integrations/langchain/README.md Install the Veqen LangChain integration and the OpenAI chat model package. Required before using the callback handler. ```bash pip install langchain-veqen langchain-openai ``` -------------------------------- ### Usage example with withTags and wrap Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Shows how to set a budget and use it with withTags and wrap. ```js import { budget, withTags, wrap } from "@veqen/sdk"; budget(5, { customer: "*" }); await withTags({ customer: "acme" }, () => wrappedClient.chat.completions.create({ ... })); ``` -------------------------------- ### handleLLMStart Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-wrap.md Callback invoked when an LLM starts. Delegates to handleChatModelStart to perform the same budget check and metadata storage. ```APIDOC ## handleLLMStart ### Description Callback invoked when an LLM starts. Delegates to handleChatModelStart to perform the same budget check and metadata storage. ### Method `handleLLMStart(llm, prompts, runId, parentRunId, extra, tags, metadata)` ### Parameters - `llm` - The language model instance. - `prompts` - The prompts sent to the model. - `runId` (string) - The run identifier. - `parentRunId` - The parent run identifier. - `extra` - Additional data. - `tags` - Tags associated with the run. - `metadata` (object) - Metadata for the run. ### Behavior - Calls `handleChatModelStart` with the same arguments. ``` -------------------------------- ### Wrap OpenAI client and tag requests in Python Source: https://github.com/keyveve/veqen-sdks/blob/main/README.md Wrap an OpenAI client with veqen.wrap and use veqen.tags to attribute requests to a customer. Works locally without an account. ```python import veqen from openai import OpenAI client = veqen.wrap(OpenAI(), feature="support-bot") with veqen.tags(customer="acme"): client.responses.create(model="gpt-5-mini", input="Where is my order?") ``` -------------------------------- ### veqen init [dir] Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-cli.md Initializes the current project by inspecting package.json, requirements.txt, and pyproject.toml to detect AI SDKs and prints setup instructions. Always prints the VEQEN_API_KEY note. ```APIDOC ## veqen init [dir] ### Description Prints the setup for the current project by inspecting `package.json` (detects the Vercel AI SDK `ai`, `openai`, `@anthropic-ai/sdk`, `@google/genai`), `requirements.txt` and `pyproject.toml` (detects `anthropic`, `google-genai`, `langchain`, `litellm`, `openai-agents`, otherwise defaults to `OpenAI()`). Always prints the `VEQEN_API_KEY` note. ### Method CLI command ### Endpoint `veqen init [dir]` ### Parameters #### Path Parameters - **dir** (string) - Optional - Directory to initialize (defaults to current directory) ### Request Example ```bash npx @veqen/sdk@1 init ``` ### Response #### Success Response Prints setup instructions and the VEQEN_API_KEY note. ``` -------------------------------- ### providerForUrl usage example Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-pricing.md Example usage of providerForUrl with sample URLs. ```javascript import { providerForUrl } from "@veqen/sdk"; providerForUrl("https://api.together.xyz/v1"); // "together" providerForUrl("https://api.openai.com/v1"); // "openai" ``` -------------------------------- ### PriceBook usage example Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-pricing.md Shows how to load the price book, access its version, resolve a provider from a URL, and compute a cost for a model with usage. The example prints the version and provider, then calculates the cost for a specific model. ```python import veqen book = veqen.price_book() print(book.version) # 2026-10-23 print(book.provider_for_url("https://api.together.xyz")) # together usd = book.cost("meta-llama/Llama-3.3-70B-Instruct-Turbo", veqen.Usage(input_tokens=1000, output_tokens=250), provider="together") ``` -------------------------------- ### Example: record with tags Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Example usage of record with provider 'anthropic' and model 'claude-sonnet-5-5', passing inputTokens and outputTokens, and tags. Logs cost_usd and price_version. ```javascript import { record } from "@veqen/sdk"; const event = record("anthropic", "claude-sonnet-5-5", { inputTokens: 1200, outputTokens: 300, }, { tags: { customer: "acme" } }); console.log(event.cost_usd, event.price_version); ``` -------------------------------- ### Python: veqen_pricebook.load usage example Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/pricebook-packages.md Example of using the load function to access the price-book snapshot. Prints the version, schema, and standard rates for a model. ```python from veqen_pricebook import load book = load() print(book["version"], book["schema"]) # 2026-10-23 2 print(book["models"]["openai/gpt-4o"]["rates"]["standard"]) # {'in': 2.5, 'out': 10.0} ``` -------------------------------- ### Build and install the local package Source: https://github.com/keyveve/veqen-sdks/blob/main/vscode-extension/README.md Run these commands from the extension directory using Node.js 22 to install dependencies, prepare data, run tests, and package the VSIX. After packaging, install the generated VSIX via 'Extensions: Install from VSIX…' in VS Code. ```sh npm ci --ignore-scripts npm run prepare-data npm test npm run package ``` -------------------------------- ### Usage example for flush with init Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Shows how to initialize the SDK with an API key and flush events before a serverless function returns. If flush returns false, events remain queued for the next interval. ```javascript import { init, flush } from "@veqen/sdk"; init({ apiKey: process.env.VEQEN_API_KEY }); // ... work ... const ok = await flush(); if (!ok) console.warn("events remain queued for the next interval"); ``` -------------------------------- ### lookup usage example Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-pricing.md Example usage of lookup with a model and provider. ```javascript import { lookup } from "@veqen/sdk"; const price = lookup("gpt-4o-mini"); console.log(price.provider, price.model, price.retires ?? "no retirement"); lookup("us.anthropic.claude-sonnet-4-5-20250929-v1:0", "bedrock"); ``` -------------------------------- ### init with ledgerFile and environment Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Example usage of init with a ledger file and environment. The ledger file appends one JSON line per event; the parent directory is created automatically. ```js import { init } from "@veqen/sdk"; init({ ledgerFile: ".veqen/ledger.jsonl", environment: "production" }); ``` -------------------------------- ### Veqen SDK CLI commands for scanning, diffing, auditing, and reporting Source: https://github.com/keyveve/veqen-sdks/blob/main/README.md Run these commands from a terminal to scan model references for prices and retirement dates, compare model changes, import provider usage locally with your admin key, or report on a local ledger. The cost-review Action adds a pull-request summary and optional retirement checks; it never executes the reviewed application's code. Use `pull_request`, not `pull_request_target`. ```sh npx @veqen/sdk@1 scan npx @veqen/sdk@1 diff origin/main npx @veqen/sdk@1 audit npx @veqen/sdk@1 report ``` -------------------------------- ### Example: record with explicit cost Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Example usage of record for a self-hosted model with explicit costUsd, since the price book doesn't know it. Includes tags for feature and region. ```javascript import { record } from "@veqen/sdk"; // Self-hosted model with an explicit cost (price book doesn't know it) record("self-hosted", "my-vllm-70b", { inputTokens: 90_000, outputTokens: 4_000 }, { costUsd: 0.0042, tags: { feature: "rag", region: "us-east" } }); ``` -------------------------------- ### init with apiKey and flush in serverless handler Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Example showing init with an API key and custom flush interval, then flushing manually in a serverless handler. The flush returns true when the queue is empty. ```js import { init, flush } from "@veqen/sdk"; init({ apiKey: process.env.VEQEN_API_KEY, flushIntervalMs: 1000, budgetPollMs: 15_000 }); export async function handler() { // ... model calls ... const drained = await flush(); // true when the queue is empty return { drained }; } ``` -------------------------------- ### init(options?) Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Initializes the Veqen SDK with configuration options. Sets the API key, endpoint, environment, ledger file, and polling intervals. Starts a periodic flush timer when an API key is provided. ```APIDOC ## `init(options?)` ### Description Initializes the Veqen SDK with configuration options. Sets the API key, endpoint, environment, ledger file, and polling intervals. Starts a periodic flush timer when an API key is provided. ### Method Function call ### Signature ```ts export declare function init(options?: { apiKey?: string; endpoint?: string; environment?: string; ledgerFile?: string; flushIntervalMs?: number; budgetPollMs?: number; }): void; ``` ### Parameters #### Options Object - **apiKey** (string) - Optional - API key for authentication. Defaults to env `VEQEN_API_KEY` or `""`. When set, a `setInterval(flush, flushIntervalMs)` sender starts and `beforeExit` flushes. - **endpoint** (string) - Optional - Base URL for the API. Defaults to env `VEQEN_ENDPOINT` or `"https://veqen-app.com"`. Trailing `/` is stripped. - **environment** (string) - Optional - Default environment value on every event. Defaults to env `VEQEN_ENVIRONMENT`. - **ledgerFile** (string) - Optional - Path to a file for appending one JSON line per event. Parent directory is created (failure logs a warning). Defaults to env `VEQEN_LEDGER_FILE`. - **flushIntervalMs** (number) - Optional - Sender interval when an API key is set. Defaults to `2000`. - **budgetPollMs** (number) - Optional - Minimum delay between `GET /v1/budgets/status` polls. Defaults to `30000`. ### Returns `undefined`. Calling `init` again replaces the previous timer. ### Example ```js import { init } from "@veqen/sdk"; init({ ledgerFile: ".veqen/ledger.jsonl", environment: "production" }); ``` ```js import { init, flush } from "@veqen/sdk"; init({ apiKey: process.env.VEQEN_API_KEY, flushIntervalMs: 1000, budgetPollMs: 15_000 }); export async function handler() { // ... model calls ... const drained = await flush(); // true when the queue is empty return { drained }; } ``` ``` -------------------------------- ### cost usage example with valid model Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-pricing.md Example of calling cost with a known model and usage, showing the returned cost. The second call includes provider and variant options. ```javascript import { cost } from "@veqen/sdk"; cost("gpt-4o", { inputTokens: 1000, outputTokens: 500 }); // 0.0075 cost("veo-3.1-generate-001", { units: 8 }, { provider: "google", variant: "1080p" }); ``` -------------------------------- ### handleChatModelStart Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-wrap.md Callback invoked when a chat model starts. Stores metadata for the run and performs a budget check using the handler's tags merged with currentTags(). ```APIDOC ## handleChatModelStart ### Description Callback invoked when a chat model starts. Stores metadata for the run and performs a budget check using the handler's tags merged with currentTags(). ### Method `handleChatModelStart(_llm, _messages, runId, _parentRunId, _extra, _tags, metadata)` ### Parameters - `_llm` - The language model instance. - `_messages` - The messages sent to the model. - `runId` (string) - The run identifier. - `_parentRunId` - The parent run identifier. - `_extra` - Additional data. - `_tags` - Tags associated with the run. - `metadata` (object) - Metadata for the run, stored for later use. ### Behavior - Stores the metadata in the `runs` map keyed by `runId`. - Calls `check({ ...this.tags, ...currentTags() })` to enforce budget limits. ``` -------------------------------- ### Invalid budget usage example Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Demonstrates catching the error when multiple scopes are provided. ```js import { budget } from "@veqen/sdk"; try { budget(1, { customer: "acme", user: "u_1" }); } catch (error) { console.error(error.message); // Use one of customer/feature/user/project, ... } ``` -------------------------------- ### veqen CLI commands Source: https://github.com/keyveve/veqen-sdks/blob/main/js/README.md CLI commands for setup, scanning models, diffing cost impact, auditing, and reporting. Use --json, --fail-within 30, and --format markdown|json options as shown. ```bash npx @veqen/sdk init # the setup for this project ``` ```bash npx @veqen/sdk scan # models in your code: prices, retirement dates, cheaper options (--json, --fail-within 30) ``` ```bash npx @veqen/sdk diff origin/main # cost impact of model changes in this branch (--format markdown|json) ``` ```bash npx @veqen/sdk audit # last 30 days from your OpenAI or Anthropic admin key, locally ``` ```bash npx @veqen/sdk report # cost by customer, feature and model from a local ledger (init({ ledgerFile })) ``` -------------------------------- ### Usage example with veqen.cost Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-pricing.md Shows constructing a Usage object and accessing prompt_tokens and tokens properties. Also calls veqen.cost with input and output tokens. ```python import veqen usage = veqen.Usage(input_tokens=1000, output_tokens=500, cache_read_tokens=800) print(usage.prompt_tokens) # 1800 print(usage.tokens) # 2300 veqen.cost("gpt-4o", usage.input_tokens, usage.output_tokens) ``` -------------------------------- ### Install and configure OpenLLMetry environment variables Source: https://github.com/keyveve/veqen-sdks/blob/main/examples/openllmetry/README.md Install the traceloop-sdk and OpenAI packages, then set required environment variables for OpenLLMetry. On PowerShell, use $env:NAME = 'value' syntax for these variables. ```sh pip install traceloop-sdk==0.62.4 openai export TRACELOOP_BASE_URL=http://127.0.0.1:4318 export TRACELOOP_TRACE_CONTENT=false export TRACELOOP_TELEMETRY=false export TRACELOOP_METRICS_ENABLED=false export TRACELOOP_LOGGING_ENABLED=false ``` -------------------------------- ### init function implementation (js/src/core.js:49) Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Initializes the Veqen SDK state with options or environment variables. Creates the ledger directory if needed, starts a flush interval when an API key is set, and registers a beforeExit flush. Calling init again replaces the previous timer. ```js export function init(options = {}) { state.apiKey = options.apiKey ?? env("VEQEN_API_KEY") ?? ""; state.endpoint = (options.endpoint ?? env("VEQEN_ENDPOINT") ?? state.endpoint).replace(/\/$/, ""); state.environment = options.environment ?? env("VEQEN_ENVIRONMENT"); state.ledgerFile = options.ledgerFile ?? env("VEQEN_LEDGER_FILE"); if (state.ledgerFile) { try { mkdirSync(dirname(state.ledgerFile), { recursive: true }); } catch (error) { console.warn(`[veqen] can't create the ledger folder: ${error.message}`); // e.g. a read-only filesystem } } state.budgetPollMs = options.budgetPollMs ?? state.budgetPollMs; state.configured = true; clearInterval(state.timer); state.timer = null; if (state.apiKey) { state.timer = setInterval(() => void flush(), options.flushIntervalMs ?? 2000); state.timer.unref?.(); globalThis.process?.once?.("beforeExit", () => void flush()); } } ``` -------------------------------- ### VeqenTracingProcessor.on_trace_start Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-integrations.md Called when a trace starts. This implementation is a no-op. ```APIDOC ## `VeqenTracingProcessor.on_trace_start` ### Description Called when a trace starts. This implementation is a no-op. ### Method Method ### Signature ```python on_trace_start(self, trace: Any) -> None ``` ### Parameters - **trace** (Any) - Required - The trace object that started. ``` -------------------------------- ### Serverless init with API key and custom polling Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-core.md Initializes Veqen with an API key from environment variables, enabling event uploads and starting the background sender thread. Uses faster flush and budget polling intervals for serverless hot paths. ```python import os import veqen veqen.init( api_key=os.environ["VEQEN_API_KEY"], endpoint=os.environ.get("VEQEN_ENDPOINT", "https://veqen-app.com"), flush_interval=1.0, # batch faster in a serverless hot path budget_poll=15.0, # poll dashboard budgets more often ) ``` -------------------------------- ### Using priceBook to access version and model rates Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-pricing.md Example of importing priceBook and accessing the version and a model's standard input rate. ```javascript import { priceBook } from "@veqen/sdk"; console.log(priceBook.version); console.log(priceBook.models["openai/gpt-4o"].rates.standard.in); // 2.5 ``` -------------------------------- ### Wrap an OpenAI client and tag calls with veqen Source: https://github.com/keyveve/veqen-sdks/blob/main/python/README.md Wrap an OpenAI client with veqen.wrap() to track costs per feature. Use veqen.tags() to attribute calls to a customer and user. Every call is priced from provider-reported usage; prompts and responses are never read. ```python import veqen from openai import OpenAI client = veqen.wrap(OpenAI(), feature="support-bot") with veqen.tags(customer="acme", user="u_42"): client.responses.create(model="gpt-5-mini", input="Where is my order?") ``` -------------------------------- ### Python: veqen_pricebook.load — load price-book snapshot Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/pricebook-packages.md Loads the installed, dated price-book snapshot without network access. Returns an independent copy of the dict parsed from the bundled prices.json resource. Requires Python ≥ 3.10. ```python """Load the installed, dated price-book snapshot without network access.""" import json from importlib.resources import files def load() -> dict: """Return an independent copy. Token rates are USD per million tokens.""" return json.loads(files(__package__).joinpath("prices.json").read_text(encoding="utf-8")) ``` -------------------------------- ### veqen_pricebook.load Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/pricebook-packages.md Loads the installed, dated price-book snapshot without network access. Returns an independent copy of the bundled prices.json data. ```APIDOC ## veqen_pricebook.load ### Description Loads the installed, dated price-book snapshot without network access. Returns an independent copy of the bundled prices.json data. ### Method Function call ### Endpoint `veqen_pricebook.load()` ### Parameters None ### Returns - **dict** - A fresh dictionary (independent copy) parsed from the bundled `prices.json` resource. Token rates are USD per million tokens. ### Example ```python from veqen_pricebook import load book = load() print(book["version"], book["schema"]) # 2026-10-23 2 print(book["models"]["openai/gpt-4o"]["rates"]["standard"]) # {'in': 2.5, 'out': 10.0} ``` ``` -------------------------------- ### init function signature Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-core.md Configures Veqen. Without an API key, costs are computed locally and written to ledger_file if set; nothing is sent. Reads VEQEN_API_KEY, VEQEN_ENDPOINT, VEQEN_ENVIRONMENT, and VEQEN_LEDGER_FILE when arguments are omitted. Setting a non-empty api_key starts a daemon thread named veqen-sender and registers atexit.register(self.flush, 2.0). Calling init again re-configures the singleton. ```python def init( api_key: str | None = None, *, endpoint: str | None = None, environment: str | None = None, ledger_file: str | None = None, flush_interval: float = 2.0, budget_poll: float = 30.0, ) -> None: """Configure Veqen. Without an API key, costs are computed locally (and written to ``ledger_file`` if set) and nothing is sent anywhere. Reads VEQEN_API_KEY, VEQEN_ENDPOINT, VEQEN_ENVIRONMENT and VEQEN_LEDGER_FILE when arguments are omitted.""" ``` -------------------------------- ### veqen diff origin/main --format markdown Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-cli.md Compares the current branch against origin/main, reporting model changes in Markdown format. The output starts with for GitHub Action comment deduplication. ```bash npx @veqen/sdk@1 diff origin/main --format markdown ``` -------------------------------- ### withTags usage with wrap and OpenAI client Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-core.md Example showing how to use `withTags` with a wrapped OpenAI client. The tags `{ customer: "acme", user: "u_42" }` are applied to the `responses.create` call inside the function. ```js import { wrap, withTags } from "@veqen/sdk"; const client = wrap(new OpenAI(), { feature: "support-bot" }); await withTags({ customer: "acme", user: "u_42" }, () => client.responses.create({ model: "gpt-5-mini", input: "Where is my order?" })); ``` -------------------------------- ### Usage example with ChatOpenAI Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-integrations.md Shows how to attach VeqenCallbackHandler to a ChatOpenAI call, both at construction and via config callbacks. The handler merges tags with current_tags() and records usage after the call. ```python from veqen.integrations.langchain import VeqenCallbackHandler llm = ChatOpenAI(model="gpt-4o-mini", callbacks=[VeqenCallbackHandler(feature="research-agent")]) answer = llm.invoke("Summarize this document.", config={"callbacks": [VeqenCallbackHandler(customer="acme")]}) veqen.flush() ``` -------------------------------- ### Lookup and cost for video model with variant Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-pricing.md Looks up a price for 'veo-3.1-generate-001' from provider 'google', gets unit rate for '1080p', and computes cost for 8 units with residency multipliers. ```python import veqen price = veqen.lookup("veo-3.1-generate-001", "google") per_second = price.unit_rate("1080p") # resolution variant usd = price.cost(veqen.Usage(units=8), variant="1080p", multipliers=veqen.price_book().residency.get("google")) ``` -------------------------------- ### veqen CLI help text Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-cli.md Displays the full command list for the Veqen CLI, including init, scan, diff, audit, and report subcommands with their options and descriptions. ```text veqen — the cost ledger for AI inference veqen init How to add Veqen to this project veqen scan [dir] [--json] [--fail-within DAYS] Model IDs in your code: prices, retirement dates, cheaper options veqen diff [base-ref] [--format text|markdown|json] Cost impact of model changes (uses production volume with VEQEN_API_KEY) veqen audit [--provider openai|anthropic] Last 30 days of provider spend from an admin key, locally veqen report [ledger-file] Costs by customer, feature and model from a local ledger ``` -------------------------------- ### Install veqen Haystack integration and disable telemetry Source: https://github.com/keyveve/veqen-sdks/blob/main/examples/haystack/README.md Install the optional Haystack integration with pip and disable Haystack telemetry. Requires Python 3.11+ and Haystack 3.4+. ```shell pip install 'veqen[haystack]>=1.2,<2' export HAYSTACK_TELEMETRY_ENABLED=false ``` -------------------------------- ### init Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-core.md Configures the Veqen client. Without an API key, costs are computed locally and nothing is sent anywhere. Reads environment variables when arguments are omitted. ```APIDOC ## init ### Description Configures the Veqen client. Without an API key, costs are computed locally (and written to `ledger_file` if set) and nothing is sent anywhere. Reads `VEQEN_API_KEY`, `VEQEN_ENDPOINT`, `VEQEN_ENVIRONMENT` and `VEQEN_LEDGER_FILE` when arguments are omitted. ### Method Function call ### Signature ```python def init( api_key: str | None = None, *, endpoint: str | None = None, environment: str | None = None, ledger_file: str | None = None, flush_interval: float = 2.0, budget_poll: float = 30.0, ) -> None: ``` ### Parameters - `api_key` (str | None) - Optional - When set, events are uploaded to the ledger endpoint and the background sender thread starts. Defaults to env `VEQEN_API_KEY` or `""`. - `endpoint` (str | None) - Optional - Base URL, trailing `/` stripped. Defaults to env `VEQEN_ENDPOINT` or `"https://veqen-app.com"`. - `environment` (str | None) - Optional - Default environment tag, applied to every event. Defaults to env `VEQEN_ENVIRONMENT` or `None`. - `ledger_file` (str | None) - Optional - Append each event as one JSON line; parent folder is created (creation failure only logs a warning). Defaults to env `VEQEN_LEDGER_FILE` or `None`. - `flush_interval` (float) - Optional - Seconds between sender wake-ups / batch attempts. Defaults to `2.0`. - `budget_poll` (float) - Optional - Seconds between `GET /v1/budgets/status` polls. Defaults to `30.0`. ### Returns `None`. ### Notes Setting a non-empty `api_key` starts a daemon thread named `veqen-sender` and registers `atexit.register(self.flush, 2.0)`. Calling `init` again re-configures the singleton. ### Example ```python import veqen veqen.init(ledger_file=".veqen/ledger.jsonl", environment="production") ``` ```python import os import veqen veqen.init( api_key=os.environ["VEQEN_API_KEY"], endpoint=os.environ.get("VEQEN_ENDPOINT", "https://veqen-app.com"), flush_interval=1.0, # batch faster in a serverless hot path budget_poll=15.0, # poll dashboard budgets more often ) ``` ``` -------------------------------- ### cost usage example with unknown model Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-pricing.md Example of calling cost with an unknown model, which returns null. The code checks for null and logs a message suggesting to pass costUsd to record(). ```javascript import { cost } from "@veqen/sdk"; const price = cost("unknown-model", { inputTokens: 10 }); if (price == null) console.log("not in the price book — pass costUsd to record()"); ``` -------------------------------- ### priceCall function and usage example Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-pricing.md Calculates USD cost of a call, rounded to 10 decimals, or null when rates are missing. The TypeScript declaration and JavaScript usage example are shown together. ```javascript /** USD cost of a call to `price`, or null when the call used something the model has no rate for. */ export function priceCall(price, usage, { batch = false, serviceTier, residency, variant } = {}) { ... return Math.round(total * factor * 1e10) / 1e10; } ``` ```typescript export declare function priceCall(price: Price, usage: Usage, options?: CostOptions): number | null; ``` ```javascript import { lookup, priceCall } from "@veqen/sdk"; const price = lookup("gpt-4o"); const usd = priceCall(price, { inputTokens: 1000, outputTokens: 500 }); const batchUsd = priceCall(price, { inputTokens: 1000, outputTokens: 500 }, { batch: true }); ``` -------------------------------- ### VeqenTracingProcessor.on_span_start Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-integrations.md Called when a span starts. This implementation is a no-op. ```APIDOC ## `VeqenTracingProcessor.on_span_start` ### Description Called when a span starts. This implementation is a no-op. ### Method Method ### Signature ```python on_span_start(self, span: Any) -> None ``` ### Parameters - **span** (Any) - Required - The span object that started. ``` -------------------------------- ### main Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-cli.md Entry point for the veqen CLI. Parses command-line arguments and dispatches to subcommands (init, scan, diff, audit, report). Returns a Promise that resolves when the command completes. ```APIDOC ## main ### Description Entry point for the veqen CLI. Parses command-line arguments and dispatches to subcommands (init, scan, diff, audit, report). Returns a Promise that resolves when the command completes. ### Method CLI ### Endpoint `veqen` (bin) ### Parameters #### Positional Arguments - **command** (string) - Required - The subcommand to execute: `init`, `scan`, `diff`, `audit`, or `report`. - **arg** (string) - Optional - Argument for the subcommand (e.g., path, git ref, or ledger file). #### Options - **--json** (boolean) - Optional - Output in JSON format. - **--format** (string) - Optional - Output format. - **--provider** (string) - Optional - Provider name. - **--fail-within** (string) - Optional - Fail threshold. - **--help, -h** (boolean) - Optional - Show help. ### Returns `Promise` ### Errors - Any command error prints `veqen: ` to stderr and sets `process.exitCode = 1`. - Unknown/no command prints the help block. ``` -------------------------------- ### Price a call without recording with @veqen/sdk Source: https://github.com/keyveve/veqen-sdks/blob/main/js/README.md Get the price for a model without recording usage. The price book is @veqen/sdk/prices. ```ts cost("gpt-4o", { inputTokens: 1000, outputTokens: 500 }) ``` -------------------------------- ### main() CLI entry point Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-cli.md Parses CLI arguments and dispatches to subcommands (init, scan, diff, audit, report). On error, prints `veqen: ` to stderr and sets `process.exitCode = 1`; unknown/no command prints the help block. ```JavaScript export async function main(argv = process.argv.slice(2)) { const options = { json: { type: "boolean" }, format: { type: "string" }, provider: { type: "string" }, "fail-within": { type: "string" }, help: { type: "boolean", short: "h" } }; try { const { positionals, values } = parseArgs({ args: argv, options, allowPositionals: true }); const [command, arg] = values.help ? [] : positionals; if (command === "init") runInit(arg ?? "."); else if (command === "scan") runScan(arg ?? ".", values); else if (command === "diff") await runDiff(arg ?? "origin/main", values); else if (command === "audit") await runAudit(values); else if (command === "report") runReport(arg ?? process.env.VEQEN_LEDGER_FILE ?? ".veqen/ledger.jsonl"); else console.log(HELP); } catch (error) { console.error(`veqen: ${error.message}`); process.exitCode = 1; } } ``` -------------------------------- ### init(options) Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/types.md Initializes the Veqen SDK client with configuration options. Accepts an optional options object to set API key, endpoint, environment, ledger file, and polling intervals. ```APIDOC ## `init(options)` ### Description Initializes the Veqen SDK client with configuration options. Accepts an optional options object to set API key, endpoint, environment, ledger file, and polling intervals. ### Method `init` ### Parameters #### Options - **apiKey** (string) - Optional - API key for authentication. Defaults to env `VEQEN_API_KEY` or `""`. - **endpoint** (string) - Optional - Base endpoint URL. Defaults to env `VEQEN_ENDPOINT` or `"https://veqen-app.com"`. - **environment** (string) - Optional - Environment name. Defaults to env `VEQEN_ENVIRONMENT`. - **ledgerFile** (string) - Optional - Path to ledger file. Defaults to env `VEQEN_LEDGER_FILE`. - **flushIntervalMs** (number) - Optional - Flush interval in milliseconds. Defaults to `2000`. - **budgetPollMs** (number) - Optional - Budget polling interval in milliseconds. Defaults to `30000`. ### Request Example ```ts init({ apiKey: "your-api-key", endpoint: "https://veqen-app.com", environment: "production", ledgerFile: "./ledger.json", flushIntervalMs: 2000, budgetPollMs: 30000 }); ``` ### Response No return value. ``` -------------------------------- ### GET https://veqen-app.com/prices.json Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/endpoints.md Serves the deployed price book snapshot (schema 2). This is a public endpoint for retrieving the current price book data. ```APIDOC ## GET https://veqen-app.com/prices.json ### Description Serves the deployed price book snapshot (schema 2). This is a public endpoint for retrieving the current price book data. ### Method GET ### Endpoint https://veqen-app.com/prices.json ### Response #### Success Response (200) - **schema** (integer) - Schema version, set to 2. - **prices** (object) - Price book data. #### Response Example ```json { "schema": 2, "prices": {} } ``` ``` -------------------------------- ### Catching BudgetExceeded Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-core.md Example of catching BudgetExceeded when wrapping an OpenAI client with a budget. The exception provides scope, value, and limit_usd for handling. ```python import veqen veqen.budget(2.00, user="*") try: client = veqen.wrap(OpenAI(), feature="chat") client.chat.completions.create(model="gpt-4o-mini", messages=[...]) except veqen.BudgetExceeded as exc: return upgrade_prompt(exc.limit_usd) # exc.scope == "user", exc.value == "u_42" ``` -------------------------------- ### Budget enforcement example Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-integrations.md Sets a budget and catches BudgetExceeded to handle budget limits. The handler's raise_error attribute lets the exception propagate. ```python import veqen from veqen.integrations.langchain import VeqenCallbackHandler handler = VeqenCallbackHandler(feature="agent") veqen.budget(2.00, user="*") try: chain.invoke(inputs, config={"callbacks": [handler]}) except veqen.BudgetExceeded: print("budget reached for this user") ``` -------------------------------- ### veqen report .veqen/ledger.jsonl Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/js-cli.md Reads the JSONL ledger file and prints the top 15 rows per dimension (customer, feature, model) with calls and cost. Throws an error if the ledger file is missing. ```bash npx @veqen/sdk@1 report .veqen/ledger.jsonl ``` -------------------------------- ### GET https://api.anthropic.com/v1/organizations/cost_report Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/endpoints.md Retrieves cost report data from Anthropic's organization cost report endpoint. Used by the `veqen audit` command to fetch model-level costs. ```APIDOC ## GET https://api.anthropic.com/v1/organizations/cost_report ### Description Retrieves cost report data from Anthropic's organization cost report endpoint. Used by the `veqen audit` command to fetch model-level costs. ### Method GET ### Endpoint https://api.anthropic.com/v1/organizations/cost_report ### Parameters #### Query Parameters - **starting_at** (string) - Required - Start date in `YYYY-MM-DDT00:00:00Z` format. - **group_by[]** (string) - Required - Set to `description` to group by model description. - **limit** (integer) - Required - Maximum number of results, set to `31`. - **page** (integer) - Required - Page number for pagination. ### Response #### Success Response (200) - **data[].results[].model** (string) - Model identifier or description. - **data[].results[].description** (string) - Description of the cost item. - **data[].results[].amount** (number) - Cost amount in cents (convert to USD). - **has_more** (boolean) - Indicates if more pages are available. - **next_page** (string) - Token for the next page. #### Response Example ```json { "data": [ { "results": [ { "model": "claude-3-opus", "description": "Claude 3 Opus", "amount": 1234 } ] } ], "has_more": false, "next_page": null } ``` ``` -------------------------------- ### Local-only init with ledger file Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-core.md Initializes Veqen without an API key, so costs are computed locally and appended to the specified ledger file. Sets a default environment tag for all events. ```python import veqen veqen.init(ledger_file=".veqen/ledger.jsonl", environment="production") ``` -------------------------------- ### GET https://api.openai.com/v1/organization/costs Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/endpoints.md Retrieves cost data from OpenAI's organization costs endpoint. Used by the `veqen audit` command to fetch line-item costs for the last 30 days. ```APIDOC ## GET https://api.openai.com/v1/organization/costs ### Description Retrieves cost data from OpenAI's organization costs endpoint. Used by the `veqen audit` command to fetch line-item costs for the last 30 days. ### Method GET ### Endpoint https://api.openai.com/v1/organization/costs ### Parameters #### Query Parameters - **start_time** (unix timestamp) - Required - Start time for cost data, typically 30 days ago. - **bucket_width** (string) - Required - Set to `1d` for daily buckets. - **group_by** (string) - Required - Set to `line_item` to group costs by line item. - **limit** (integer) - Required - Maximum number of results, set to `31`. - **page** (integer) - Required - Page number for pagination. ### Response #### Success Response (200) - **data[].results[].line_item** (string) - Line item identifier, split on commas. - **data[].results[].amount.value** (number) - Cost amount value. - **has_more** (boolean) - Indicates if more pages are available. - **next_page** (string) - Token for the next page. #### Response Example ```json { "data": [ { "results": [ { "line_item": "item1,item2", "amount": { "value": 12.34 } } ] } ], "has_more": false, "next_page": null } ``` ``` -------------------------------- ### Using veqen.tags with a client call Source: https://github.com/keyveve/veqen-sdks/blob/main/_autodocs/api-reference/python-core.md Shows how to use the `tags` context manager to attribute a client call with tags like `customer` and `feature`. ```python import veqen with veqen.tags(customer="acme", feature="support-bot"): client.responses.create(model="gpt-5-mini", input="Where is my order?") ``` -------------------------------- ### Load price book in JavaScript Source: https://github.com/keyveve/veqen-sdks/blob/main/pricebook-packages/js/README.md Load the price book and log version, schema, and rates for a model. Token rates are USD per million tokens. ```javascript import book from '@veqen/pricebook'; console.log(book.version, book.schema); console.log(book.models['openai/gpt-4o'].rates); ```