langtrain 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-A7PMJDMV.mjs +3 -0
- package/dist/chunk-A7PMJDMV.mjs.map +1 -0
- package/dist/chunk-K5LXUJ4G.js +3 -0
- package/dist/chunk-K5LXUJ4G.js.map +1 -0
- package/dist/cli.js +10 -10
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/index.d.mts +30 -2
- package/dist/index.d.ts +30 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/src/lib/base.ts +162 -12
- package/dist/chunk-36QS5AXY.mjs +0 -3
- package/dist/chunk-36QS5AXY.mjs.map +0 -1
- package/dist/chunk-ZN3AO753.js +0 -3
- package/dist/chunk-ZN3AO753.js.map +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import P,{AxiosError}from'axios';import $ from'form-data';import x from'fs';import*as langvision from'langvision';export{langvision as o };export{Langvision as q}from'langvision';import*as langtune from'langtune';export{langtune as p };export{Langtune as r}from'langtune';var v=Object.defineProperty;var M=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var m=(n,e)=>{for(var t in e)v(n,t,{get:e[t],enumerable:true});};var k="https://api.langtrain.ai/api/v1",F=3e4,E=2,L=10,S=[408,429,500,502,503,504],u=class extends Error{constructor(e,t){super(e),this.name="LangtrainError",this.status=t?.status,this.code=t?.code,this.cause=t?.cause,this.retryAfter=t?.retryAfter;}get isTransient(){return this.code==="ECONNABORTED"||this.code==="NETWORK_ERROR"||this.status!==void 0&&S.includes(this.status)}get isAuthError(){return this.status===401||this.status===403}get isNotFound(){return this.status===404}get isRateLimited(){return this.status===429}},d=class{constructor(e,t){this.capacity=e;this.refillRate=t;this.tokens=e,this.lastRefill=Date.now();}async acquire(){if(this.refill(),this.tokens>=1){this.tokens-=1;return}let e=(1-this.tokens)/this.refillRate*1e3;await this.sleep(Math.ceil(e)),this.refill(),this.tokens-=1;}async waitFor(e){await this.sleep(e*1e3);}refill(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.capacity,this.tokens+t*this.refillRate),this.lastRefill=e;}sleep(e){return new Promise(t=>setTimeout(t,e))}},s=class{constructor(e){this.maxRetries=e.maxRetries??E,this.debug=e.debug??false,this.onRequest=e.onRequest;let t=e.maxRequestsPerSecond??L;this.rateLimiter=new d(t,t),this.http=P.create({baseURL:e.baseUrl||k,timeout:e.timeout??F,headers:{"X-API-Key":e.apiKey,"Content-Type":"application/json","User-Agent":"langtrain-sdk/0.2.x"}});}async request(e){let t;for(let r=0;r<=this.maxRetries;r++){await this.rateLimiter.acquire();let i=Date.now();try{let o=await e(),a=Date.now()-i;return this.log(`\u2713 request succeeded (${a}ms, attempt ${r+1})`),this.emitEvent({method:"",path:"",status:200,latencyMs:a,attempt:r}),o}catch(o){let a=Date.now()-i;if(t=this.wrapError(o),this.log(`\u2717 request failed: ${t.message} (${a}ms, attempt ${r+1})`),this.emitEvent({method:"",path:"",status:t.status,latencyMs:a,attempt:r,error:t,rateLimitRemaining:t.isRateLimited?0:void 0,rateLimitReset:t.retryAfter}),!t.isTransient||r===this.maxRetries)throw t;if(t.isRateLimited&&t.retryAfter)this.log(`\u23F3 rate limited, waiting ${t.retryAfter}s (Retry-After)`),await this.rateLimiter.waitFor(t.retryAfter);else {let c=Math.min(500*Math.pow(2,r),5e3);this.log(`\u21BB retrying in ${c}ms...`),await this.sleep(c);}}}throw t}wrapError(e){if(e instanceof u)return e;if(e instanceof AxiosError){let t=e.response?.status,r=e.response?.headers,i=e.response?.data,o=i?.detail??i?.message??i?.error,a,c=r?.["retry-after"];if(c){let _=Number(c);a=isNaN(_)?Math.max(0,Math.ceil((new Date(c).getTime()-Date.now())/1e3)):_;}let q=o?String(o):e.code==="ECONNABORTED"?"Request timed out":t===429?`Rate limited${a?` \u2014 retry in ${a}s`:""}`:t?`API request failed with status ${t}`:`Network error: ${e.message}`;return new u(q,{status:t,code:e.code,cause:e,retryAfter:a})}return e instanceof Error?new u(e.message,{cause:e}):new u(String(e))}log(e){this.debug&&process.stderr.write(`[langtrain] ${e}
|
|
2
|
+
`);}emitEvent(e){if(this.onRequest)try{this.onRequest(e);}catch{}}sleep(e){return new Promise(t=>setTimeout(t,e))}};var R={};m(R,{AgentClient:()=>g});var g=class extends s{constructor(e){super(e);}async list(e){return this.request(async()=>{let t={};return e&&(t.workspace_id=e),(await this.http.get("/agents",{params:t})).data.agents})}async get(e){return this.request(async()=>(await this.http.get(`/agents/${e}`)).data)}async create(e){return this.request(async()=>(await this.http.post("/agents/",e)).data)}async delete(e){return this.request(async()=>{await this.http.delete(`/agents/${e}`);})}async execute(e,t,r=[],i){return this.request(async()=>(await this.http.post(`/agents/${e}/execute`,{input:t,messages:r,conversation_id:i})).data)}async logs(e,t=100){return this.request(async()=>(await this.http.get(`/agents/${e}/logs`,{params:{limit:t}})).data.logs)}};var h=class extends s{constructor(e){super(e);}async upload(e,t,r="fine-tune"){if(!x.existsSync(e))throw new Error(`File not found: ${e}`);return this.request(async()=>{let i=new $;return i.append("file",x.createReadStream(e)),t&&i.append("workspace_id",t),i.append("purpose",r),(await this.http.post("/files",i,{headers:i.getHeaders(),maxContentLength:1/0,maxBodyLength:1/0})).data})}async list(e,t){return this.request(async()=>{let r={workspace_id:e};return t&&(r.purpose=t),(await this.http.get("/files",{params:r})).data.data})}async delete(e){return this.request(async()=>{await this.http.delete(`/files/${e}`);})}};var f=class extends s{constructor(e){super(e);}async createJob(e){return this.request(async()=>(await this.http.post("/finetune/jobs",e)).data)}async listJobs(e,t=10){return this.request(async()=>(await this.http.get("/finetune/jobs",{params:{workspace_id:e,limit:t}})).data)}async getJob(e){return this.request(async()=>(await this.http.get(`/finetune/jobs/${e}`)).data)}async cancelJob(e){return this.request(async()=>(await this.http.post(`/finetune/jobs/${e}/cancel`)).data)}};var y=class extends s{constructor(e){super(e);}async getStatus(){return this.request(async()=>(await this.http.get("/subscription/status")).data)}async checkFeature(e){return this.request(async()=>(await this.http.get(`/subscription/check/${e}`)).data)}async getLimits(){return this.request(async()=>(await this.http.get("/subscription/analytics")).data)}};var C={};m(C,{ModelClient:()=>l});var l=class extends s{constructor(e){super(e);}async list(e){return this.request(async()=>{let t={};return e&&(t.task=e),(await this.http.get("/models",{params:t})).data.data})}async get(e){return this.request(async()=>(await this.http.get(`/models/${e}`)).data)}};var A={};m(A,{SecretClient:()=>p});var p=class extends s{constructor(e){super(e);}async list(e){return this.request(async()=>{let t={};return e&&(t.workspace_id=e),(await this.http.get("/secrets",{params:t})).data.secrets})}async set(e,t,r){return this.request(async()=>(await this.http.post("/secrets",{key:e,value:t,workspace_id:r})).data)}async delete(e,t){return this.request(async()=>{let r={};t&&(r.workspace_id=t),await this.http.delete(`/secrets/${e}`,{params:r});})}};var b=class extends s{constructor(e){super(e);}async list(e){return this.request(async()=>{let t={};return e&&(t.workspace_id=e),(await this.http.get("/guardrails/",{params:t})).data})}async get(e){return this.request(async()=>(await this.http.get(`/guardrails/${e}`)).data)}async create(e){return this.request(async()=>(await this.http.post("/guardrails/",e)).data)}async delete(e){return this.request(async()=>{await this.http.delete(`/guardrails/${e}`);})}async apply(e,t){return this.request(async()=>(await this.http.post("/guardrails/apply",{dataset_id:e,guardrail_id:t})).data)}};var w=class extends s{constructor(e){super(e);}async getSummary(e){return this.request(async()=>(await this.http.get("/usage",{params:{workspace_id:e}})).data)}async getHistory(e,t=30){return this.request(async()=>(await this.http.get("/usage/history",{params:{workspace_id:e,days:t}})).data.history)}};export{M as a,u as b,s as c,g as d,R as e,h as f,f as g,y as h,l as i,C as j,p as k,A as l,b as m,w as n};//# sourceMappingURL=chunk-A7PMJDMV.mjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-A7PMJDMV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/base.ts","../src/lib/agent.ts","../src/lib/files.ts","../src/lib/training.ts","../src/lib/subscription.ts","../src/lib/models.ts","../src/lib/secrets.ts","../src/lib/guardrails.ts","../src/lib/usage.ts"],"names":["DEFAULT_BASE_URL","DEFAULT_TIMEOUT","DEFAULT_MAX_RETRIES","DEFAULT_MAX_RPS","RETRYABLE_STATUS_CODES","LangtrainError","message","options","RateLimiter","capacity","refillRate","waitMs","seconds","now","elapsed","ms","resolve","BaseClient","config","maxRps","axios","fn","lastError","attempt","start","result","latencyMs","error","delay","AxiosError","status","headers","data","serverMessage","retryAfter","retryHeader","parsed","msg","event","agent_exports","__export","AgentClient","workspaceId","params","agentId","agent","input","messages","conversationId","limit","FileClient","filePath","purpose","fs","form","FormData","fileId","TrainingClient","job","jobId","SubscriptionClient","feature","models_exports","ModelClient","task","modelId","secrets_exports","SecretClient","key","value","GuardrailClient","guardrailId","datasetId","UsageClient","days"],"mappings":"gRAAA,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,SAAA,CAAA,CAAA,CAAA,GAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,KAAA,CAAA,IAAA,CAAA,SAAA,CAAA,CAAA,MAAA,KAAA,CAAA,sBAAA,CAAA,CAAA,CAAA,oBAAA,CAAA,CAAA,EAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,C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IAAA,CAAK,IAAA,CAAgB,cAAA,CAAgBA,CAAI,CAAA,EACrD,IACd,CACL,CAGA,MAAM,MAAA,CAAOuC,CAAAA,CAAoC,CAC7C,OAAO,IAAA,CAAK,OAAA,CAAQ,SAAY,CAC5B,MAAM,IAAA,CAAK,IAAA,CAAK,OAAO,CAAA,YAAA,EAAeA,CAAW,CAAA,CAAE,EACvD,CAAC,CACL,CAGA,MAAM,KAAA,CAAMC,CAAAA,CAAmBD,CAAAA,CAAoD,CAC/E,OAAO,KAAK,OAAA,CAAQ,SAAA,CACJ,MAAM,IAAA,CAAK,IAAA,CAAK,IAAA,CAA2B,oBAAqB,CACxE,UAAA,CAAYC,CAAAA,CACZ,YAAA,CAAcD,CAClB,CAAC,GACU,IACd,CACL,CACJ,EClEO,IAAME,CAAAA,CAAN,cAA0BxD,CAAW,CACxC,WAAA,CAAYC,CAAAA,CAAsB,CAC9B,KAAA,CAAMA,CAAM,EAChB,CAGA,MAAM,UAAA,CAAWwB,CAAAA,CAA4C,CACzD,OAAO,IAAA,CAAK,OAAA,CAAQ,SAAA,CACJ,MAAM,IAAA,CAAK,IAAA,CAAK,IAAkB,QAAA,CAAU,CACpD,MAAA,CAAQ,CAAE,YAAA,CAAcA,CAAY,CACxC,CAAC,CAAA,EACU,IACd,CACL,CAGA,MAAM,WAAWA,CAAAA,CAAqBgC,CAAAA,CAAe,EAAA,CAAkC,CACnF,OAAO,IAAA,CAAK,QAAQ,SAAA,CACJ,MAAM,IAAA,CAAK,IAAA,CAAK,GAAA,CAAsC,gBAAA,CAAkB,CAChF,MAAA,CAAQ,CAAE,YAAA,CAAchC,CAAAA,CAAa,IAAA,CAAAgC,CAAK,CAC9C,CAAC,CAAA,EACU,IAAA,CAAK,OACnB,CACL,CACJ","file":"chunk-A7PMJDMV.mjs","sourcesContent":["import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';\n\n// ── Shared Configuration ───────────────────────────────────────────────────\n\n/** Configuration for all Langtrain SDK clients. */\nexport interface ClientConfig {\n /** Your Langtrain API key. */\n apiKey: string;\n /** Override the default API base URL. */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeout?: number;\n /** Maximum number of retries on transient errors (default: 2). */\n maxRetries?: number;\n /** Max requests per second (client-side rate limiting, default: 10). */\n maxRequestsPerSecond?: number;\n /** Enable debug logging to stderr (default: false). */\n debug?: boolean;\n /** Optional callback invoked on every request for observability. */\n onRequest?: (event: RequestEvent) => void;\n}\n\n/** Emitted for every API request (success or failure). */\nexport interface RequestEvent {\n method: string;\n path: string;\n status?: number;\n latencyMs: number;\n attempt: number;\n error?: LangtrainError;\n rateLimitRemaining?: number;\n rateLimitReset?: number;\n}\n\nconst DEFAULT_BASE_URL = 'https://api.langtrain.ai/api/v1';\nconst DEFAULT_TIMEOUT = 30_000;\nconst DEFAULT_MAX_RETRIES = 2;\nconst DEFAULT_MAX_RPS = 10;\nconst RETRYABLE_STATUS_CODES = [408, 429, 500, 502, 503, 504];\n\n// ── Custom Error ───────────────────────────────────────────────────────────\n\nexport class LangtrainError extends Error {\n /** HTTP status code, if available. */\n readonly status?: number;\n /** Raw error code from the API. */\n readonly code?: string;\n /** The original error, if any. */\n readonly cause?: Error;\n /** Seconds until rate limit resets (from Retry-After header). */\n readonly retryAfter?: number;\n\n constructor(message: string, options?: {\n status?: number;\n code?: string;\n cause?: Error;\n retryAfter?: number;\n }) {\n super(message);\n this.name = 'LangtrainError';\n this.status = options?.status;\n this.code = options?.code;\n this.cause = options?.cause;\n this.retryAfter = options?.retryAfter;\n }\n\n /** True if the error was a network/timeout issue (retryable). */\n get isTransient(): boolean {\n return this.code === 'ECONNABORTED' || this.code === 'NETWORK_ERROR' ||\n (this.status !== undefined && RETRYABLE_STATUS_CODES.includes(this.status));\n }\n\n /** True if the API key was invalid or expired. */\n get isAuthError(): boolean {\n return this.status === 401 || this.status === 403;\n }\n\n /** True if a resource was not found. */\n get isNotFound(): boolean {\n return this.status === 404;\n }\n\n /** True if rate-limited. */\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\n// ── Token Bucket Rate Limiter ──────────────────────────────────────────────\n\n/**\n * Simple token-bucket rate limiter.\n * Allows bursting up to `capacity` requests, refills at `refillRate` tokens/sec.\n */\nclass RateLimiter {\n private tokens: number;\n private lastRefill: number;\n\n constructor(\n private readonly capacity: number,\n private readonly refillRate: number,\n ) {\n this.tokens = capacity;\n this.lastRefill = Date.now();\n }\n\n /** Wait until a token is available, then consume it. */\n async acquire(): Promise<void> {\n this.refill();\n\n if (this.tokens >= 1) {\n this.tokens -= 1;\n return;\n }\n\n // Wait for next token\n const waitMs = ((1 - this.tokens) / this.refillRate) * 1000;\n await this.sleep(Math.ceil(waitMs));\n this.refill();\n this.tokens -= 1;\n }\n\n /** Pause for `seconds` (e.g. from Retry-After header). */\n async waitFor(seconds: number): Promise<void> {\n await this.sleep(seconds * 1000);\n }\n\n private refill(): void {\n const now = Date.now();\n const elapsed = (now - this.lastRefill) / 1000;\n this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillRate);\n this.lastRefill = now;\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}\n\n// ── Base Client ────────────────────────────────────────────────────────────\n\n/**\n * BaseClient — abstract foundation for all Langtrain SDK clients.\n *\n * Features:\n * - Shared axios instance with API key auth\n * - Configurable timeouts\n * - Automatic retry with exponential backoff on transient errors\n * - Client-side token-bucket rate limiting\n * - Retry-After header respect on 429s\n * - Structured error wrapping (LangtrainError)\n * - Debug logging and request event hooks\n */\nexport abstract class BaseClient {\n protected readonly http: AxiosInstance;\n protected readonly maxRetries: number;\n private readonly rateLimiter: RateLimiter;\n private readonly debug: boolean;\n private readonly onRequest?: (event: RequestEvent) => void;\n\n constructor(config: ClientConfig) {\n this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.debug = config.debug ?? false;\n this.onRequest = config.onRequest;\n\n const maxRps = config.maxRequestsPerSecond ?? DEFAULT_MAX_RPS;\n this.rateLimiter = new RateLimiter(maxRps, maxRps);\n\n this.http = axios.create({\n baseURL: config.baseUrl || DEFAULT_BASE_URL,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n headers: {\n 'X-API-Key': config.apiKey,\n 'Content-Type': 'application/json',\n 'User-Agent': 'langtrain-sdk/0.2.x',\n },\n });\n }\n\n /**\n * Execute a request with rate limiting, automatic retry, and error wrapping.\n */\n protected async request<T>(fn: () => Promise<T>): Promise<T> {\n let lastError: LangtrainError | undefined;\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n // Acquire a rate limiter token before each attempt\n await this.rateLimiter.acquire();\n\n const start = Date.now();\n\n try {\n const result = await fn();\n const latencyMs = Date.now() - start;\n\n this.log(`✓ request succeeded (${latencyMs}ms, attempt ${attempt + 1})`);\n this.emitEvent({ method: '', path: '', status: 200, latencyMs, attempt });\n\n return result;\n } catch (error) {\n const latencyMs = Date.now() - start;\n lastError = this.wrapError(error);\n\n this.log(`✗ request failed: ${lastError.message} (${latencyMs}ms, attempt ${attempt + 1})`);\n this.emitEvent({\n method: '', path: '',\n status: lastError.status,\n latencyMs,\n attempt,\n error: lastError,\n rateLimitRemaining: lastError.isRateLimited ? 0 : undefined,\n rateLimitReset: lastError.retryAfter,\n });\n\n // Don't retry non-transient errors or on last attempt\n if (!lastError.isTransient || attempt === this.maxRetries) {\n throw lastError;\n }\n\n // If rate-limited with Retry-After, respect it\n if (lastError.isRateLimited && lastError.retryAfter) {\n this.log(`⏳ rate limited, waiting ${lastError.retryAfter}s (Retry-After)`);\n await this.rateLimiter.waitFor(lastError.retryAfter);\n } else {\n // Exponential backoff: 500ms, 1000ms, 2000ms...\n const delay = Math.min(500 * Math.pow(2, attempt), 5000);\n this.log(`↻ retrying in ${delay}ms...`);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError!;\n }\n\n /**\n * Wrap any thrown error into a structured LangtrainError.\n */\n private wrapError(error: unknown): LangtrainError {\n if (error instanceof LangtrainError) return error;\n\n if (error instanceof AxiosError) {\n const status = error.response?.status;\n const headers = error.response?.headers;\n const data = error.response?.data as Record<string, unknown> | undefined;\n const serverMessage = data?.detail ?? data?.message ?? data?.error;\n\n // Parse Retry-After header (seconds or HTTP date)\n let retryAfter: number | undefined;\n const retryHeader = headers?.['retry-after'];\n if (retryHeader) {\n const parsed = Number(retryHeader);\n retryAfter = isNaN(parsed)\n ? Math.max(0, Math.ceil((new Date(retryHeader).getTime() - Date.now()) / 1000))\n : parsed;\n }\n\n const message = serverMessage\n ? String(serverMessage)\n : error.code === 'ECONNABORTED'\n ? `Request timed out`\n : status === 429\n ? `Rate limited${retryAfter ? ` — retry in ${retryAfter}s` : ''}`\n : status\n ? `API request failed with status ${status}`\n : `Network error: ${error.message}`;\n\n return new LangtrainError(message, {\n status,\n code: error.code,\n cause: error,\n retryAfter,\n });\n }\n\n if (error instanceof Error) {\n return new LangtrainError(error.message, { cause: error });\n }\n\n return new LangtrainError(String(error));\n }\n\n private log(msg: string): void {\n if (this.debug) {\n process.stderr.write(`[langtrain] ${msg}\\n`);\n }\n }\n\n private emitEvent(event: RequestEvent): void {\n if (this.onRequest) {\n try {\n this.onRequest(event);\n } catch {\n // Never let user callbacks crash the SDK\n }\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface Agent {\n id: string;\n workspace_id: string;\n name: string;\n description?: string;\n model_id?: string;\n config: AgentConfig;\n is_active: boolean;\n created_at: string;\n updated_at: string;\n}\n\nexport interface AgentConfig {\n system_prompt?: string;\n temperature?: number;\n max_tokens?: number;\n tools?: string[];\n [key: string]: unknown;\n}\n\nexport interface AgentCreate {\n workspace_id: string;\n name: string;\n description?: string;\n model_id?: string;\n config?: AgentConfig;\n}\n\nexport interface AgentRun {\n id: string;\n conversation_id: string;\n success: boolean;\n output?: unknown;\n error?: string;\n latency_ms: number;\n tokens_used: number;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing AI agents — create, execute, and monitor.\n *\n * @example\n * ```ts\n * const agents = new AgentClient({ apiKey: 'lt_...' });\n * const list = await agents.list();\n * const result = await agents.execute(list[0].id, 'Hello!');\n * ```\n */\nexport class AgentClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** List all agents, optionally filtered by workspace. */\n async list(workspaceId?: string): Promise<Agent[]> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (workspaceId) params.workspace_id = workspaceId;\n const res = await this.http.get<{ agents: Agent[] }>('/agents', { params });\n return res.data.agents;\n });\n }\n\n /** Get a single agent by ID. */\n async get(agentId: string): Promise<Agent> {\n return this.request(async () => {\n const res = await this.http.get<Agent>(`/agents/${agentId}`);\n return res.data;\n });\n }\n\n /** Create a new agent. */\n async create(agent: AgentCreate): Promise<Agent> {\n return this.request(async () => {\n const res = await this.http.post<Agent>('/agents/', agent);\n return res.data;\n });\n }\n\n /** Delete an agent by ID. */\n async delete(agentId: string): Promise<void> {\n return this.request(async () => {\n await this.http.delete(`/agents/${agentId}`);\n });\n }\n\n /** Execute an agent with input and optional conversation context. */\n async execute(agentId: string, input: string, messages: Array<{ role: string; content: string }> = [], conversationId?: string): Promise<AgentRun> {\n return this.request(async () => {\n const res = await this.http.post<AgentRun>(`/agents/${agentId}/execute`, {\n input,\n messages,\n conversation_id: conversationId,\n });\n return res.data;\n });\n }\n\n /** Fetch recent logs for an agent. */\n async logs(agentId: string, limit: number = 100): Promise<string[]> {\n return this.request(async () => {\n const res = await this.http.get<{ logs: string[] }>(`/agents/${agentId}/logs`, {\n params: { limit },\n });\n return res.data.logs;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\nimport FormData from 'form-data';\nimport fs from 'fs';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface FileResponse {\n id: string;\n filename: string;\n purpose: string;\n bytes: number;\n created_at: string;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing file uploads (datasets for fine-tuning).\n *\n * @example\n * ```ts\n * const files = new FileClient({ apiKey: 'lt_...' });\n * const uploaded = await files.upload('./data.jsonl');\n * ```\n */\nexport class FileClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** Upload a file from a local path. */\n async upload(filePath: string, workspaceId?: string, purpose: string = 'fine-tune'): Promise<FileResponse> {\n if (!fs.existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n\n return this.request(async () => {\n const form = new FormData();\n form.append('file', fs.createReadStream(filePath));\n if (workspaceId) form.append('workspace_id', workspaceId);\n form.append('purpose', purpose);\n\n const res = await this.http.post<FileResponse>('/files', form, {\n headers: form.getHeaders(),\n maxContentLength: Infinity,\n maxBodyLength: Infinity,\n });\n return res.data;\n });\n }\n\n /** List files in a workspace, optionally filtered by purpose. */\n async list(workspaceId: string, purpose?: string): Promise<FileResponse[]> {\n return this.request(async () => {\n const params: Record<string, string> = { workspace_id: workspaceId };\n if (purpose) params.purpose = purpose;\n const res = await this.http.get<{ data: FileResponse[] }>('/files', { params });\n return res.data.data;\n });\n }\n\n /** Delete a file by ID. */\n async delete(fileId: string): Promise<void> {\n return this.request(async () => {\n await this.http.delete(`/files/${fileId}`);\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface FineTuneHyperparameters {\n epochs?: number;\n learning_rate?: number;\n batch_size?: number;\n warmup_steps?: number;\n lora_rank?: number;\n lora_alpha?: number;\n weight_decay?: number;\n}\n\nexport interface FineTuneJobCreate {\n name?: string;\n base_model: string;\n model_id?: string;\n dataset_id: string;\n guardrail_id?: string;\n task?: 'text' | 'vision';\n training_method?: 'sft' | 'dpo' | 'rlhf' | 'lora' | 'qlora';\n hyperparameters?: FineTuneHyperparameters;\n}\n\nexport interface FineTuneJobResponse {\n id: string;\n name: string;\n status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';\n progress: number;\n error_message?: string;\n base_model?: string;\n training_method?: string;\n created_at: string;\n started_at?: string;\n completed_at?: string;\n}\n\nexport interface FineTuneJobList {\n data: FineTuneJobResponse[];\n has_more: boolean;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing fine-tuning training jobs.\n *\n * @example\n * ```ts\n * const training = new TrainingClient({ apiKey: 'lt_...' });\n * const job = await training.createJob({\n * base_model: 'meta-llama/Llama-3.1-8B',\n * dataset_id: 'file_abc123',\n * training_method: 'lora',\n * });\n * ```\n */\nexport class TrainingClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** Create a new fine-tuning job. */\n async createJob(job: FineTuneJobCreate): Promise<FineTuneJobResponse> {\n return this.request(async () => {\n const res = await this.http.post<FineTuneJobResponse>('/finetune/jobs', job);\n return res.data;\n });\n }\n\n /** List fine-tuning jobs for a workspace. */\n async listJobs(workspaceId: string, limit: number = 10): Promise<FineTuneJobList> {\n return this.request(async () => {\n const res = await this.http.get<FineTuneJobList>('/finetune/jobs', {\n params: { workspace_id: workspaceId, limit },\n });\n return res.data;\n });\n }\n\n /** Get a specific job by ID. */\n async getJob(jobId: string): Promise<FineTuneJobResponse> {\n return this.request(async () => {\n const res = await this.http.get<FineTuneJobResponse>(`/finetune/jobs/${jobId}`);\n return res.data;\n });\n }\n\n /** Cancel a running job. */\n async cancelJob(jobId: string): Promise<FineTuneJobResponse> {\n return this.request(async () => {\n const res = await this.http.post<FineTuneJobResponse>(`/finetune/jobs/${jobId}/cancel`);\n return res.data;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface SubscriptionInfo {\n is_active: boolean;\n plan: string;\n plan_name: string;\n expires_at?: string;\n features: string[];\n limits: Record<string, number>;\n usage?: {\n tokensUsedThisMonth?: number;\n tokenLimit?: number;\n apiCalls?: number;\n };\n}\n\nexport interface FeatureCheck {\n feature: string;\n allowed: boolean;\n limit?: number;\n used?: number;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for checking subscription status and feature access.\n *\n * @example\n * ```ts\n * const sub = new SubscriptionClient({ apiKey: 'lt_...' });\n * const status = await sub.getStatus();\n * console.log(status.plan); // 'pro'\n * ```\n */\nexport class SubscriptionClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** Get current subscription status. */\n async getStatus(): Promise<SubscriptionInfo> {\n return this.request(async () => {\n const res = await this.http.get<SubscriptionInfo>('/subscription/status');\n return res.data;\n });\n }\n\n /** Check if a specific feature is available on the current plan. */\n async checkFeature(feature: string): Promise<FeatureCheck> {\n return this.request(async () => {\n const res = await this.http.get<FeatureCheck>(`/subscription/check/${feature}`);\n return res.data;\n });\n }\n\n /** Get usage analytics for the current subscription. */\n async getLimits(): Promise<Record<string, unknown>> {\n return this.request(async () => {\n const res = await this.http.get('/subscription/analytics');\n return res.data;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface Permission {\n id: string;\n object: string;\n created: number;\n allow_create_engine: boolean;\n allow_sampling: boolean;\n allow_logprobs: boolean;\n allow_search_indices: boolean;\n allow_view: boolean;\n allow_fine_tuning: boolean;\n organization: string;\n group: string | null;\n is_blocking: boolean;\n}\n\nexport interface Model {\n id: string;\n object: string;\n created: number;\n owned_by: string;\n permission: Permission[];\n root: string;\n parent: string | null;\n task?: 'text' | 'vision' | 'agent';\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for browsing available base models.\n *\n * @example\n * ```ts\n * const models = new ModelClient({ apiKey: 'lt_...' });\n * const all = await models.list();\n * const textModels = await models.list('text');\n * ```\n */\nexport class ModelClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** List available models, optionally filtered by task type. */\n async list(task?: 'text' | 'vision' | 'agent'): Promise<Model[]> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (task) params.task = task;\n const res = await this.http.get<{ data: Model[] }>('/models', { params });\n return res.data.data;\n });\n }\n\n /** Get a specific model by ID. */\n async get(modelId: string): Promise<Model> {\n return this.request(async () => {\n const res = await this.http.get<Model>(`/models/${modelId}`);\n return res.data;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface Secret {\n key: string;\n created_at: string;\n updated_at: string;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing workspace secrets and environment variables.\n *\n * @example\n * ```ts\n * const secrets = new SecretClient({ apiKey: 'lt_...' });\n * await secrets.set('OPENAI_KEY', 'sk-...');\n * const all = await secrets.list();\n * ```\n */\nexport class SecretClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** List all secrets in a workspace. Values are redacted. */\n async list(workspaceId?: string): Promise<Secret[]> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (workspaceId) params.workspace_id = workspaceId;\n const res = await this.http.get<{ secrets: Secret[] }>('/secrets', { params });\n return res.data.secrets;\n });\n }\n\n /** Set (create or update) a secret. */\n async set(key: string, value: string, workspaceId?: string): Promise<Secret> {\n return this.request(async () => {\n const res = await this.http.post<Secret>('/secrets', { key, value, workspace_id: workspaceId });\n return res.data;\n });\n }\n\n /** Delete a secret by key. */\n async delete(key: string, workspaceId?: string): Promise<void> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (workspaceId) params.workspace_id = workspaceId;\n await this.http.delete(`/secrets/${key}`, { params });\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface GuardrailConfig {\n pii_enabled: boolean;\n pii_entities?: string[];\n profanity_enabled: boolean;\n profanity_threshold?: number;\n blocked_topics?: string[];\n regex_patterns?: string[];\n min_length?: number;\n max_length?: number;\n}\n\nexport interface Guardrail {\n id: string;\n workspace_id: string;\n name: string;\n description?: string;\n config: GuardrailConfig;\n is_active: boolean;\n created_at: string;\n updated_at: string;\n}\n\nexport interface GuardrailCreate {\n name: string;\n description?: string;\n config: GuardrailConfig;\n}\n\nexport interface GuardrailApplyResult {\n total_rows: number;\n passed: number;\n failed: number;\n violations: Array<{ row: number; rule: string; message: string }>;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing data guardrails (PII, profanity, length, regex).\n *\n * @example\n * ```ts\n * const guardrails = new GuardrailClient({ apiKey: 'lt_...' });\n * const rule = await guardrails.create({\n * name: 'PII Filter',\n * config: { pii_enabled: true, profanity_enabled: false },\n * });\n * ```\n */\nexport class GuardrailClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** List guardrails, optionally filtered by workspace. */\n async list(workspaceId?: string): Promise<Guardrail[]> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (workspaceId) params.workspace_id = workspaceId;\n const res = await this.http.get<Guardrail[]>('/guardrails/', { params });\n return res.data;\n });\n }\n\n /** Get a guardrail by ID. */\n async get(guardrailId: string): Promise<Guardrail> {\n return this.request(async () => {\n const res = await this.http.get<Guardrail>(`/guardrails/${guardrailId}`);\n return res.data;\n });\n }\n\n /** Create a new guardrail. */\n async create(data: GuardrailCreate): Promise<Guardrail> {\n return this.request(async () => {\n const res = await this.http.post<Guardrail>('/guardrails/', data);\n return res.data;\n });\n }\n\n /** Delete a guardrail by ID. */\n async delete(guardrailId: string): Promise<void> {\n return this.request(async () => {\n await this.http.delete(`/guardrails/${guardrailId}`);\n });\n }\n\n /** Apply a guardrail to a dataset for validation. */\n async apply(datasetId: string, guardrailId: string): Promise<GuardrailApplyResult> {\n return this.request(async () => {\n const res = await this.http.post<GuardrailApplyResult>('/guardrails/apply', {\n dataset_id: datasetId,\n guardrail_id: guardrailId,\n });\n return res.data;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface UsageSummary {\n workspace_id: string;\n plan: string;\n quotas: Record<string, number>;\n billing?: {\n plan_id: string;\n tokens_used: number;\n tokens_limit: number;\n period_end: string;\n };\n}\n\nexport interface UsageHistoryPoint {\n date: string;\n tokens: number;\n agent_runs: number;\n cost: number;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for querying usage metrics and billing data.\n *\n * @example\n * ```ts\n * const usage = new UsageClient({ apiKey: 'lt_...' });\n * const summary = await usage.getSummary('ws_abc123');\n * console.log(summary.billing?.tokens_used);\n * ```\n */\nexport class UsageClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** Get current usage summary for a workspace. */\n async getSummary(workspaceId: string): Promise<UsageSummary> {\n return this.request(async () => {\n const res = await this.http.get<UsageSummary>('/usage', {\n params: { workspace_id: workspaceId },\n });\n return res.data;\n });\n }\n\n /** Get historical usage data for charts. */\n async getHistory(workspaceId: string, days: number = 30): Promise<UsageHistoryPoint[]> {\n return this.request(async () => {\n const res = await this.http.get<{ history: UsageHistoryPoint[] }>('/usage/history', {\n params: { workspace_id: workspaceId, days },\n });\n return res.data.history;\n });\n }\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var P=require('axios'),$=require('form-data'),x=require('fs'),langvision=require('langvision'),langtune=require('langtune');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var P__default=/*#__PURE__*/_interopDefault(P);var $__default=/*#__PURE__*/_interopDefault($);var x__default=/*#__PURE__*/_interopDefault(x);var langvision__namespace=/*#__PURE__*/_interopNamespace(langvision);var langtune__namespace=/*#__PURE__*/_interopNamespace(langtune);var v=Object.defineProperty;var M=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var m=(n,e)=>{for(var t in e)v(n,t,{get:e[t],enumerable:true});};var k="https://api.langtrain.ai/api/v1",F=3e4,E=2,L=10,S=[408,429,500,502,503,504],u=class extends Error{constructor(e,t){super(e),this.name="LangtrainError",this.status=t?.status,this.code=t?.code,this.cause=t?.cause,this.retryAfter=t?.retryAfter;}get isTransient(){return this.code==="ECONNABORTED"||this.code==="NETWORK_ERROR"||this.status!==void 0&&S.includes(this.status)}get isAuthError(){return this.status===401||this.status===403}get isNotFound(){return this.status===404}get isRateLimited(){return this.status===429}},d=class{constructor(e,t){this.capacity=e;this.refillRate=t;this.tokens=e,this.lastRefill=Date.now();}async acquire(){if(this.refill(),this.tokens>=1){this.tokens-=1;return}let e=(1-this.tokens)/this.refillRate*1e3;await this.sleep(Math.ceil(e)),this.refill(),this.tokens-=1;}async waitFor(e){await this.sleep(e*1e3);}refill(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.capacity,this.tokens+t*this.refillRate),this.lastRefill=e;}sleep(e){return new Promise(t=>setTimeout(t,e))}},s=class{constructor(e){this.maxRetries=e.maxRetries??E,this.debug=e.debug??false,this.onRequest=e.onRequest;let t=e.maxRequestsPerSecond??L;this.rateLimiter=new d(t,t),this.http=P__default.default.create({baseURL:e.baseUrl||k,timeout:e.timeout??F,headers:{"X-API-Key":e.apiKey,"Content-Type":"application/json","User-Agent":"langtrain-sdk/0.2.x"}});}async request(e){let t;for(let r=0;r<=this.maxRetries;r++){await this.rateLimiter.acquire();let i=Date.now();try{let o=await e(),a=Date.now()-i;return this.log(`\u2713 request succeeded (${a}ms, attempt ${r+1})`),this.emitEvent({method:"",path:"",status:200,latencyMs:a,attempt:r}),o}catch(o){let a=Date.now()-i;if(t=this.wrapError(o),this.log(`\u2717 request failed: ${t.message} (${a}ms, attempt ${r+1})`),this.emitEvent({method:"",path:"",status:t.status,latencyMs:a,attempt:r,error:t,rateLimitRemaining:t.isRateLimited?0:void 0,rateLimitReset:t.retryAfter}),!t.isTransient||r===this.maxRetries)throw t;if(t.isRateLimited&&t.retryAfter)this.log(`\u23F3 rate limited, waiting ${t.retryAfter}s (Retry-After)`),await this.rateLimiter.waitFor(t.retryAfter);else {let c=Math.min(500*Math.pow(2,r),5e3);this.log(`\u21BB retrying in ${c}ms...`),await this.sleep(c);}}}throw t}wrapError(e){if(e instanceof u)return e;if(e instanceof P.AxiosError){let t=e.response?.status,r=e.response?.headers,i=e.response?.data,o=i?.detail??i?.message??i?.error,a,c=r?.["retry-after"];if(c){let _=Number(c);a=isNaN(_)?Math.max(0,Math.ceil((new Date(c).getTime()-Date.now())/1e3)):_;}let q=o?String(o):e.code==="ECONNABORTED"?"Request timed out":t===429?`Rate limited${a?` \u2014 retry in ${a}s`:""}`:t?`API request failed with status ${t}`:`Network error: ${e.message}`;return new u(q,{status:t,code:e.code,cause:e,retryAfter:a})}return e instanceof Error?new u(e.message,{cause:e}):new u(String(e))}log(e){this.debug&&process.stderr.write(`[langtrain] ${e}
|
|
2
|
+
`);}emitEvent(e){if(this.onRequest)try{this.onRequest(e);}catch{}}sleep(e){return new Promise(t=>setTimeout(t,e))}};var R={};m(R,{AgentClient:()=>g});var g=class extends s{constructor(e){super(e);}async list(e){return this.request(async()=>{let t={};return e&&(t.workspace_id=e),(await this.http.get("/agents",{params:t})).data.agents})}async get(e){return this.request(async()=>(await this.http.get(`/agents/${e}`)).data)}async create(e){return this.request(async()=>(await this.http.post("/agents/",e)).data)}async delete(e){return this.request(async()=>{await this.http.delete(`/agents/${e}`);})}async execute(e,t,r=[],i){return this.request(async()=>(await this.http.post(`/agents/${e}/execute`,{input:t,messages:r,conversation_id:i})).data)}async logs(e,t=100){return this.request(async()=>(await this.http.get(`/agents/${e}/logs`,{params:{limit:t}})).data.logs)}};var h=class extends s{constructor(e){super(e);}async upload(e,t,r="fine-tune"){if(!x__default.default.existsSync(e))throw new Error(`File not found: ${e}`);return this.request(async()=>{let i=new $__default.default;return i.append("file",x__default.default.createReadStream(e)),t&&i.append("workspace_id",t),i.append("purpose",r),(await this.http.post("/files",i,{headers:i.getHeaders(),maxContentLength:1/0,maxBodyLength:1/0})).data})}async list(e,t){return this.request(async()=>{let r={workspace_id:e};return t&&(r.purpose=t),(await this.http.get("/files",{params:r})).data.data})}async delete(e){return this.request(async()=>{await this.http.delete(`/files/${e}`);})}};var f=class extends s{constructor(e){super(e);}async createJob(e){return this.request(async()=>(await this.http.post("/finetune/jobs",e)).data)}async listJobs(e,t=10){return this.request(async()=>(await this.http.get("/finetune/jobs",{params:{workspace_id:e,limit:t}})).data)}async getJob(e){return this.request(async()=>(await this.http.get(`/finetune/jobs/${e}`)).data)}async cancelJob(e){return this.request(async()=>(await this.http.post(`/finetune/jobs/${e}/cancel`)).data)}};var y=class extends s{constructor(e){super(e);}async getStatus(){return this.request(async()=>(await this.http.get("/subscription/status")).data)}async checkFeature(e){return this.request(async()=>(await this.http.get(`/subscription/check/${e}`)).data)}async getLimits(){return this.request(async()=>(await this.http.get("/subscription/analytics")).data)}};var C={};m(C,{ModelClient:()=>l});var l=class extends s{constructor(e){super(e);}async list(e){return this.request(async()=>{let t={};return e&&(t.task=e),(await this.http.get("/models",{params:t})).data.data})}async get(e){return this.request(async()=>(await this.http.get(`/models/${e}`)).data)}};var A={};m(A,{SecretClient:()=>p});var p=class extends s{constructor(e){super(e);}async list(e){return this.request(async()=>{let t={};return e&&(t.workspace_id=e),(await this.http.get("/secrets",{params:t})).data.secrets})}async set(e,t,r){return this.request(async()=>(await this.http.post("/secrets",{key:e,value:t,workspace_id:r})).data)}async delete(e,t){return this.request(async()=>{let r={};t&&(r.workspace_id=t),await this.http.delete(`/secrets/${e}`,{params:r});})}};var b=class extends s{constructor(e){super(e);}async list(e){return this.request(async()=>{let t={};return e&&(t.workspace_id=e),(await this.http.get("/guardrails/",{params:t})).data})}async get(e){return this.request(async()=>(await this.http.get(`/guardrails/${e}`)).data)}async create(e){return this.request(async()=>(await this.http.post("/guardrails/",e)).data)}async delete(e){return this.request(async()=>{await this.http.delete(`/guardrails/${e}`);})}async apply(e,t){return this.request(async()=>(await this.http.post("/guardrails/apply",{dataset_id:e,guardrail_id:t})).data)}};var w=class extends s{constructor(e){super(e);}async getSummary(e){return this.request(async()=>(await this.http.get("/usage",{params:{workspace_id:e}})).data)}async getHistory(e,t=30){return this.request(async()=>(await this.http.get("/usage/history",{params:{workspace_id:e,days:t}})).data.history)}};exports.o=langvision__namespace;Object.defineProperty(exports,"q",{enumerable:true,get:function(){return langvision.Langvision}});exports.p=langtune__namespace;Object.defineProperty(exports,"r",{enumerable:true,get:function(){return langtune.Langtune}});exports.a=M;exports.b=u;exports.c=s;exports.d=g;exports.e=R;exports.f=h;exports.g=f;exports.h=y;exports.i=l;exports.j=C;exports.k=p;exports.l=A;exports.m=b;exports.n=w;//# sourceMappingURL=chunk-K5LXUJ4G.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-K5LXUJ4G.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/base.ts","../src/lib/agent.ts","../src/lib/files.ts","../src/lib/training.ts","../src/lib/subscription.ts","../src/lib/models.ts","../src/lib/secrets.ts","../src/lib/guardrails.ts","../src/lib/usage.ts"],"names":["DEFAULT_BASE_URL","DEFAULT_TIMEOUT","DEFAULT_MAX_RETRIES","DEFAULT_MAX_RPS","RETRYABLE_STATUS_CODES","LangtrainError","message","options","RateLimiter","capacity","refillRate","waitMs","seconds","now","elapsed","ms","resolve","BaseClient","config","maxRps","axios","fn","lastError","attempt","start","result","latencyMs","error","delay","AxiosError","status","headers","data","serverMessage","retryAfter","retryHeader","parsed","msg","event","agent_exports","__export","AgentClient","workspaceId","params","agentId","agent","input","messages","conversationId","limit","FileClient","filePath","purpose","fs","form","FormData","fileId","TrainingClient","job","jobId","SubscriptionClient","feature","models_exports","ModelClient","task","modelId","secrets_exports","SecretClient","key","value","GuardrailClient","guardrailId","datasetId","UsageClient","days"],"mappings":"gxBAAA,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,SAAA,CAAA,CAAA,CAAA,GAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,KAAA,CAAA,IAAA,CAAA,SAAA,CAAA,CAAA,MAAA,KAAA,CAAA,sBAAA,CAAA,CAAA,CAAA,oBAAA,CAAA,CAAA,EAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,IAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,EAAA,CAAA,KAkCMA,CAAAA,CAAmB,iCAAA,CACnBC,CAAAA,CAAkB,GAAA,CAClBC,CAAAA,CAAsB,CAAA,CACtBC,CAAAA,CAAkB,EAAA,CAClBC,EAAyB,CAAC,GAAA,CAAK,GAAA,CAAK,GAAA,CAAK,GAAA,CAAK,GAAA,CAAK,GAAG,CAAA,CAI/CC,EAAN,cAA6B,KAAM,CAUtC,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAK1B,CACC,KAAA,CAAMD,CAAO,CAAA,CACb,IAAA,CAAK,IAAA,CAAO,gBAAA,CACZ,IAAA,CAAK,MAAA,CAASC,CAAAA,EAAS,MAA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A,CAAMA,CAAM,EAChB,CAGA,MAAM,UAAA,CAAWwB,CAAAA,CAA4C,CACzD,OAAO,IAAA,CAAK,OAAA,CAAQ,SAAA,CACJ,MAAM,IAAA,CAAK,IAAA,CAAK,IAAkB,QAAA,CAAU,CACpD,MAAA,CAAQ,CAAE,YAAA,CAAcA,CAAY,CACxC,CAAC,CAAA,EACU,IACd,CACL,CAGA,MAAM,WAAWA,CAAAA,CAAqBgC,CAAAA,CAAe,EAAA,CAAkC,CACnF,OAAO,IAAA,CAAK,QAAQ,SAAA,CACJ,MAAM,IAAA,CAAK,IAAA,CAAK,GAAA,CAAsC,gBAAA,CAAkB,CAChF,MAAA,CAAQ,CAAE,YAAA,CAAchC,CAAAA,CAAa,IAAA,CAAAgC,CAAK,CAC9C,CAAC,CAAA,EACU,IAAA,CAAK,OACnB,CACL,CACJ","file":"chunk-K5LXUJ4G.js","sourcesContent":["import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';\n\n// ── Shared Configuration ───────────────────────────────────────────────────\n\n/** Configuration for all Langtrain SDK clients. */\nexport interface ClientConfig {\n /** Your Langtrain API key. */\n apiKey: string;\n /** Override the default API base URL. */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeout?: number;\n /** Maximum number of retries on transient errors (default: 2). */\n maxRetries?: number;\n /** Max requests per second (client-side rate limiting, default: 10). */\n maxRequestsPerSecond?: number;\n /** Enable debug logging to stderr (default: false). */\n debug?: boolean;\n /** Optional callback invoked on every request for observability. */\n onRequest?: (event: RequestEvent) => void;\n}\n\n/** Emitted for every API request (success or failure). */\nexport interface RequestEvent {\n method: string;\n path: string;\n status?: number;\n latencyMs: number;\n attempt: number;\n error?: LangtrainError;\n rateLimitRemaining?: number;\n rateLimitReset?: number;\n}\n\nconst DEFAULT_BASE_URL = 'https://api.langtrain.ai/api/v1';\nconst DEFAULT_TIMEOUT = 30_000;\nconst DEFAULT_MAX_RETRIES = 2;\nconst DEFAULT_MAX_RPS = 10;\nconst RETRYABLE_STATUS_CODES = [408, 429, 500, 502, 503, 504];\n\n// ── Custom Error ───────────────────────────────────────────────────────────\n\nexport class LangtrainError extends Error {\n /** HTTP status code, if available. */\n readonly status?: number;\n /** Raw error code from the API. */\n readonly code?: string;\n /** The original error, if any. */\n readonly cause?: Error;\n /** Seconds until rate limit resets (from Retry-After header). */\n readonly retryAfter?: number;\n\n constructor(message: string, options?: {\n status?: number;\n code?: string;\n cause?: Error;\n retryAfter?: number;\n }) {\n super(message);\n this.name = 'LangtrainError';\n this.status = options?.status;\n this.code = options?.code;\n this.cause = options?.cause;\n this.retryAfter = options?.retryAfter;\n }\n\n /** True if the error was a network/timeout issue (retryable). */\n get isTransient(): boolean {\n return this.code === 'ECONNABORTED' || this.code === 'NETWORK_ERROR' ||\n (this.status !== undefined && RETRYABLE_STATUS_CODES.includes(this.status));\n }\n\n /** True if the API key was invalid or expired. */\n get isAuthError(): boolean {\n return this.status === 401 || this.status === 403;\n }\n\n /** True if a resource was not found. */\n get isNotFound(): boolean {\n return this.status === 404;\n }\n\n /** True if rate-limited. */\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\n// ── Token Bucket Rate Limiter ──────────────────────────────────────────────\n\n/**\n * Simple token-bucket rate limiter.\n * Allows bursting up to `capacity` requests, refills at `refillRate` tokens/sec.\n */\nclass RateLimiter {\n private tokens: number;\n private lastRefill: number;\n\n constructor(\n private readonly capacity: number,\n private readonly refillRate: number,\n ) {\n this.tokens = capacity;\n this.lastRefill = Date.now();\n }\n\n /** Wait until a token is available, then consume it. */\n async acquire(): Promise<void> {\n this.refill();\n\n if (this.tokens >= 1) {\n this.tokens -= 1;\n return;\n }\n\n // Wait for next token\n const waitMs = ((1 - this.tokens) / this.refillRate) * 1000;\n await this.sleep(Math.ceil(waitMs));\n this.refill();\n this.tokens -= 1;\n }\n\n /** Pause for `seconds` (e.g. from Retry-After header). */\n async waitFor(seconds: number): Promise<void> {\n await this.sleep(seconds * 1000);\n }\n\n private refill(): void {\n const now = Date.now();\n const elapsed = (now - this.lastRefill) / 1000;\n this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillRate);\n this.lastRefill = now;\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}\n\n// ── Base Client ────────────────────────────────────────────────────────────\n\n/**\n * BaseClient — abstract foundation for all Langtrain SDK clients.\n *\n * Features:\n * - Shared axios instance with API key auth\n * - Configurable timeouts\n * - Automatic retry with exponential backoff on transient errors\n * - Client-side token-bucket rate limiting\n * - Retry-After header respect on 429s\n * - Structured error wrapping (LangtrainError)\n * - Debug logging and request event hooks\n */\nexport abstract class BaseClient {\n protected readonly http: AxiosInstance;\n protected readonly maxRetries: number;\n private readonly rateLimiter: RateLimiter;\n private readonly debug: boolean;\n private readonly onRequest?: (event: RequestEvent) => void;\n\n constructor(config: ClientConfig) {\n this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.debug = config.debug ?? false;\n this.onRequest = config.onRequest;\n\n const maxRps = config.maxRequestsPerSecond ?? DEFAULT_MAX_RPS;\n this.rateLimiter = new RateLimiter(maxRps, maxRps);\n\n this.http = axios.create({\n baseURL: config.baseUrl || DEFAULT_BASE_URL,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n headers: {\n 'X-API-Key': config.apiKey,\n 'Content-Type': 'application/json',\n 'User-Agent': 'langtrain-sdk/0.2.x',\n },\n });\n }\n\n /**\n * Execute a request with rate limiting, automatic retry, and error wrapping.\n */\n protected async request<T>(fn: () => Promise<T>): Promise<T> {\n let lastError: LangtrainError | undefined;\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n // Acquire a rate limiter token before each attempt\n await this.rateLimiter.acquire();\n\n const start = Date.now();\n\n try {\n const result = await fn();\n const latencyMs = Date.now() - start;\n\n this.log(`✓ request succeeded (${latencyMs}ms, attempt ${attempt + 1})`);\n this.emitEvent({ method: '', path: '', status: 200, latencyMs, attempt });\n\n return result;\n } catch (error) {\n const latencyMs = Date.now() - start;\n lastError = this.wrapError(error);\n\n this.log(`✗ request failed: ${lastError.message} (${latencyMs}ms, attempt ${attempt + 1})`);\n this.emitEvent({\n method: '', path: '',\n status: lastError.status,\n latencyMs,\n attempt,\n error: lastError,\n rateLimitRemaining: lastError.isRateLimited ? 0 : undefined,\n rateLimitReset: lastError.retryAfter,\n });\n\n // Don't retry non-transient errors or on last attempt\n if (!lastError.isTransient || attempt === this.maxRetries) {\n throw lastError;\n }\n\n // If rate-limited with Retry-After, respect it\n if (lastError.isRateLimited && lastError.retryAfter) {\n this.log(`⏳ rate limited, waiting ${lastError.retryAfter}s (Retry-After)`);\n await this.rateLimiter.waitFor(lastError.retryAfter);\n } else {\n // Exponential backoff: 500ms, 1000ms, 2000ms...\n const delay = Math.min(500 * Math.pow(2, attempt), 5000);\n this.log(`↻ retrying in ${delay}ms...`);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError!;\n }\n\n /**\n * Wrap any thrown error into a structured LangtrainError.\n */\n private wrapError(error: unknown): LangtrainError {\n if (error instanceof LangtrainError) return error;\n\n if (error instanceof AxiosError) {\n const status = error.response?.status;\n const headers = error.response?.headers;\n const data = error.response?.data as Record<string, unknown> | undefined;\n const serverMessage = data?.detail ?? data?.message ?? data?.error;\n\n // Parse Retry-After header (seconds or HTTP date)\n let retryAfter: number | undefined;\n const retryHeader = headers?.['retry-after'];\n if (retryHeader) {\n const parsed = Number(retryHeader);\n retryAfter = isNaN(parsed)\n ? Math.max(0, Math.ceil((new Date(retryHeader).getTime() - Date.now()) / 1000))\n : parsed;\n }\n\n const message = serverMessage\n ? String(serverMessage)\n : error.code === 'ECONNABORTED'\n ? `Request timed out`\n : status === 429\n ? `Rate limited${retryAfter ? ` — retry in ${retryAfter}s` : ''}`\n : status\n ? `API request failed with status ${status}`\n : `Network error: ${error.message}`;\n\n return new LangtrainError(message, {\n status,\n code: error.code,\n cause: error,\n retryAfter,\n });\n }\n\n if (error instanceof Error) {\n return new LangtrainError(error.message, { cause: error });\n }\n\n return new LangtrainError(String(error));\n }\n\n private log(msg: string): void {\n if (this.debug) {\n process.stderr.write(`[langtrain] ${msg}\\n`);\n }\n }\n\n private emitEvent(event: RequestEvent): void {\n if (this.onRequest) {\n try {\n this.onRequest(event);\n } catch {\n // Never let user callbacks crash the SDK\n }\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface Agent {\n id: string;\n workspace_id: string;\n name: string;\n description?: string;\n model_id?: string;\n config: AgentConfig;\n is_active: boolean;\n created_at: string;\n updated_at: string;\n}\n\nexport interface AgentConfig {\n system_prompt?: string;\n temperature?: number;\n max_tokens?: number;\n tools?: string[];\n [key: string]: unknown;\n}\n\nexport interface AgentCreate {\n workspace_id: string;\n name: string;\n description?: string;\n model_id?: string;\n config?: AgentConfig;\n}\n\nexport interface AgentRun {\n id: string;\n conversation_id: string;\n success: boolean;\n output?: unknown;\n error?: string;\n latency_ms: number;\n tokens_used: number;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing AI agents — create, execute, and monitor.\n *\n * @example\n * ```ts\n * const agents = new AgentClient({ apiKey: 'lt_...' });\n * const list = await agents.list();\n * const result = await agents.execute(list[0].id, 'Hello!');\n * ```\n */\nexport class AgentClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** List all agents, optionally filtered by workspace. */\n async list(workspaceId?: string): Promise<Agent[]> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (workspaceId) params.workspace_id = workspaceId;\n const res = await this.http.get<{ agents: Agent[] }>('/agents', { params });\n return res.data.agents;\n });\n }\n\n /** Get a single agent by ID. */\n async get(agentId: string): Promise<Agent> {\n return this.request(async () => {\n const res = await this.http.get<Agent>(`/agents/${agentId}`);\n return res.data;\n });\n }\n\n /** Create a new agent. */\n async create(agent: AgentCreate): Promise<Agent> {\n return this.request(async () => {\n const res = await this.http.post<Agent>('/agents/', agent);\n return res.data;\n });\n }\n\n /** Delete an agent by ID. */\n async delete(agentId: string): Promise<void> {\n return this.request(async () => {\n await this.http.delete(`/agents/${agentId}`);\n });\n }\n\n /** Execute an agent with input and optional conversation context. */\n async execute(agentId: string, input: string, messages: Array<{ role: string; content: string }> = [], conversationId?: string): Promise<AgentRun> {\n return this.request(async () => {\n const res = await this.http.post<AgentRun>(`/agents/${agentId}/execute`, {\n input,\n messages,\n conversation_id: conversationId,\n });\n return res.data;\n });\n }\n\n /** Fetch recent logs for an agent. */\n async logs(agentId: string, limit: number = 100): Promise<string[]> {\n return this.request(async () => {\n const res = await this.http.get<{ logs: string[] }>(`/agents/${agentId}/logs`, {\n params: { limit },\n });\n return res.data.logs;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\nimport FormData from 'form-data';\nimport fs from 'fs';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface FileResponse {\n id: string;\n filename: string;\n purpose: string;\n bytes: number;\n created_at: string;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing file uploads (datasets for fine-tuning).\n *\n * @example\n * ```ts\n * const files = new FileClient({ apiKey: 'lt_...' });\n * const uploaded = await files.upload('./data.jsonl');\n * ```\n */\nexport class FileClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** Upload a file from a local path. */\n async upload(filePath: string, workspaceId?: string, purpose: string = 'fine-tune'): Promise<FileResponse> {\n if (!fs.existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n\n return this.request(async () => {\n const form = new FormData();\n form.append('file', fs.createReadStream(filePath));\n if (workspaceId) form.append('workspace_id', workspaceId);\n form.append('purpose', purpose);\n\n const res = await this.http.post<FileResponse>('/files', form, {\n headers: form.getHeaders(),\n maxContentLength: Infinity,\n maxBodyLength: Infinity,\n });\n return res.data;\n });\n }\n\n /** List files in a workspace, optionally filtered by purpose. */\n async list(workspaceId: string, purpose?: string): Promise<FileResponse[]> {\n return this.request(async () => {\n const params: Record<string, string> = { workspace_id: workspaceId };\n if (purpose) params.purpose = purpose;\n const res = await this.http.get<{ data: FileResponse[] }>('/files', { params });\n return res.data.data;\n });\n }\n\n /** Delete a file by ID. */\n async delete(fileId: string): Promise<void> {\n return this.request(async () => {\n await this.http.delete(`/files/${fileId}`);\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface FineTuneHyperparameters {\n epochs?: number;\n learning_rate?: number;\n batch_size?: number;\n warmup_steps?: number;\n lora_rank?: number;\n lora_alpha?: number;\n weight_decay?: number;\n}\n\nexport interface FineTuneJobCreate {\n name?: string;\n base_model: string;\n model_id?: string;\n dataset_id: string;\n guardrail_id?: string;\n task?: 'text' | 'vision';\n training_method?: 'sft' | 'dpo' | 'rlhf' | 'lora' | 'qlora';\n hyperparameters?: FineTuneHyperparameters;\n}\n\nexport interface FineTuneJobResponse {\n id: string;\n name: string;\n status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';\n progress: number;\n error_message?: string;\n base_model?: string;\n training_method?: string;\n created_at: string;\n started_at?: string;\n completed_at?: string;\n}\n\nexport interface FineTuneJobList {\n data: FineTuneJobResponse[];\n has_more: boolean;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing fine-tuning training jobs.\n *\n * @example\n * ```ts\n * const training = new TrainingClient({ apiKey: 'lt_...' });\n * const job = await training.createJob({\n * base_model: 'meta-llama/Llama-3.1-8B',\n * dataset_id: 'file_abc123',\n * training_method: 'lora',\n * });\n * ```\n */\nexport class TrainingClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** Create a new fine-tuning job. */\n async createJob(job: FineTuneJobCreate): Promise<FineTuneJobResponse> {\n return this.request(async () => {\n const res = await this.http.post<FineTuneJobResponse>('/finetune/jobs', job);\n return res.data;\n });\n }\n\n /** List fine-tuning jobs for a workspace. */\n async listJobs(workspaceId: string, limit: number = 10): Promise<FineTuneJobList> {\n return this.request(async () => {\n const res = await this.http.get<FineTuneJobList>('/finetune/jobs', {\n params: { workspace_id: workspaceId, limit },\n });\n return res.data;\n });\n }\n\n /** Get a specific job by ID. */\n async getJob(jobId: string): Promise<FineTuneJobResponse> {\n return this.request(async () => {\n const res = await this.http.get<FineTuneJobResponse>(`/finetune/jobs/${jobId}`);\n return res.data;\n });\n }\n\n /** Cancel a running job. */\n async cancelJob(jobId: string): Promise<FineTuneJobResponse> {\n return this.request(async () => {\n const res = await this.http.post<FineTuneJobResponse>(`/finetune/jobs/${jobId}/cancel`);\n return res.data;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface SubscriptionInfo {\n is_active: boolean;\n plan: string;\n plan_name: string;\n expires_at?: string;\n features: string[];\n limits: Record<string, number>;\n usage?: {\n tokensUsedThisMonth?: number;\n tokenLimit?: number;\n apiCalls?: number;\n };\n}\n\nexport interface FeatureCheck {\n feature: string;\n allowed: boolean;\n limit?: number;\n used?: number;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for checking subscription status and feature access.\n *\n * @example\n * ```ts\n * const sub = new SubscriptionClient({ apiKey: 'lt_...' });\n * const status = await sub.getStatus();\n * console.log(status.plan); // 'pro'\n * ```\n */\nexport class SubscriptionClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** Get current subscription status. */\n async getStatus(): Promise<SubscriptionInfo> {\n return this.request(async () => {\n const res = await this.http.get<SubscriptionInfo>('/subscription/status');\n return res.data;\n });\n }\n\n /** Check if a specific feature is available on the current plan. */\n async checkFeature(feature: string): Promise<FeatureCheck> {\n return this.request(async () => {\n const res = await this.http.get<FeatureCheck>(`/subscription/check/${feature}`);\n return res.data;\n });\n }\n\n /** Get usage analytics for the current subscription. */\n async getLimits(): Promise<Record<string, unknown>> {\n return this.request(async () => {\n const res = await this.http.get('/subscription/analytics');\n return res.data;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface Permission {\n id: string;\n object: string;\n created: number;\n allow_create_engine: boolean;\n allow_sampling: boolean;\n allow_logprobs: boolean;\n allow_search_indices: boolean;\n allow_view: boolean;\n allow_fine_tuning: boolean;\n organization: string;\n group: string | null;\n is_blocking: boolean;\n}\n\nexport interface Model {\n id: string;\n object: string;\n created: number;\n owned_by: string;\n permission: Permission[];\n root: string;\n parent: string | null;\n task?: 'text' | 'vision' | 'agent';\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for browsing available base models.\n *\n * @example\n * ```ts\n * const models = new ModelClient({ apiKey: 'lt_...' });\n * const all = await models.list();\n * const textModels = await models.list('text');\n * ```\n */\nexport class ModelClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** List available models, optionally filtered by task type. */\n async list(task?: 'text' | 'vision' | 'agent'): Promise<Model[]> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (task) params.task = task;\n const res = await this.http.get<{ data: Model[] }>('/models', { params });\n return res.data.data;\n });\n }\n\n /** Get a specific model by ID. */\n async get(modelId: string): Promise<Model> {\n return this.request(async () => {\n const res = await this.http.get<Model>(`/models/${modelId}`);\n return res.data;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface Secret {\n key: string;\n created_at: string;\n updated_at: string;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing workspace secrets and environment variables.\n *\n * @example\n * ```ts\n * const secrets = new SecretClient({ apiKey: 'lt_...' });\n * await secrets.set('OPENAI_KEY', 'sk-...');\n * const all = await secrets.list();\n * ```\n */\nexport class SecretClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** List all secrets in a workspace. Values are redacted. */\n async list(workspaceId?: string): Promise<Secret[]> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (workspaceId) params.workspace_id = workspaceId;\n const res = await this.http.get<{ secrets: Secret[] }>('/secrets', { params });\n return res.data.secrets;\n });\n }\n\n /** Set (create or update) a secret. */\n async set(key: string, value: string, workspaceId?: string): Promise<Secret> {\n return this.request(async () => {\n const res = await this.http.post<Secret>('/secrets', { key, value, workspace_id: workspaceId });\n return res.data;\n });\n }\n\n /** Delete a secret by key. */\n async delete(key: string, workspaceId?: string): Promise<void> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (workspaceId) params.workspace_id = workspaceId;\n await this.http.delete(`/secrets/${key}`, { params });\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface GuardrailConfig {\n pii_enabled: boolean;\n pii_entities?: string[];\n profanity_enabled: boolean;\n profanity_threshold?: number;\n blocked_topics?: string[];\n regex_patterns?: string[];\n min_length?: number;\n max_length?: number;\n}\n\nexport interface Guardrail {\n id: string;\n workspace_id: string;\n name: string;\n description?: string;\n config: GuardrailConfig;\n is_active: boolean;\n created_at: string;\n updated_at: string;\n}\n\nexport interface GuardrailCreate {\n name: string;\n description?: string;\n config: GuardrailConfig;\n}\n\nexport interface GuardrailApplyResult {\n total_rows: number;\n passed: number;\n failed: number;\n violations: Array<{ row: number; rule: string; message: string }>;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for managing data guardrails (PII, profanity, length, regex).\n *\n * @example\n * ```ts\n * const guardrails = new GuardrailClient({ apiKey: 'lt_...' });\n * const rule = await guardrails.create({\n * name: 'PII Filter',\n * config: { pii_enabled: true, profanity_enabled: false },\n * });\n * ```\n */\nexport class GuardrailClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** List guardrails, optionally filtered by workspace. */\n async list(workspaceId?: string): Promise<Guardrail[]> {\n return this.request(async () => {\n const params: Record<string, string> = {};\n if (workspaceId) params.workspace_id = workspaceId;\n const res = await this.http.get<Guardrail[]>('/guardrails/', { params });\n return res.data;\n });\n }\n\n /** Get a guardrail by ID. */\n async get(guardrailId: string): Promise<Guardrail> {\n return this.request(async () => {\n const res = await this.http.get<Guardrail>(`/guardrails/${guardrailId}`);\n return res.data;\n });\n }\n\n /** Create a new guardrail. */\n async create(data: GuardrailCreate): Promise<Guardrail> {\n return this.request(async () => {\n const res = await this.http.post<Guardrail>('/guardrails/', data);\n return res.data;\n });\n }\n\n /** Delete a guardrail by ID. */\n async delete(guardrailId: string): Promise<void> {\n return this.request(async () => {\n await this.http.delete(`/guardrails/${guardrailId}`);\n });\n }\n\n /** Apply a guardrail to a dataset for validation. */\n async apply(datasetId: string, guardrailId: string): Promise<GuardrailApplyResult> {\n return this.request(async () => {\n const res = await this.http.post<GuardrailApplyResult>('/guardrails/apply', {\n dataset_id: datasetId,\n guardrail_id: guardrailId,\n });\n return res.data;\n });\n }\n}\n","import { BaseClient, ClientConfig } from './base';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface UsageSummary {\n workspace_id: string;\n plan: string;\n quotas: Record<string, number>;\n billing?: {\n plan_id: string;\n tokens_used: number;\n tokens_limit: number;\n period_end: string;\n };\n}\n\nexport interface UsageHistoryPoint {\n date: string;\n tokens: number;\n agent_runs: number;\n cost: number;\n}\n\n// ── Client ─────────────────────────────────────────────────────────────────\n\n/**\n * Client for querying usage metrics and billing data.\n *\n * @example\n * ```ts\n * const usage = new UsageClient({ apiKey: 'lt_...' });\n * const summary = await usage.getSummary('ws_abc123');\n * console.log(summary.billing?.tokens_used);\n * ```\n */\nexport class UsageClient extends BaseClient {\n constructor(config: ClientConfig) {\n super(config);\n }\n\n /** Get current usage summary for a workspace. */\n async getSummary(workspaceId: string): Promise<UsageSummary> {\n return this.request(async () => {\n const res = await this.http.get<UsageSummary>('/usage', {\n params: { workspace_id: workspaceId },\n });\n return res.data;\n });\n }\n\n /** Get historical usage data for charts. */\n async getHistory(workspaceId: string, days: number = 30): Promise<UsageHistoryPoint[]> {\n return this.request(async () => {\n const res = await this.http.get<{ history: UsageHistoryPoint[] }>('/usage/history', {\n params: { workspace_id: workspaceId, days },\n });\n return res.data.history;\n });\n }\n}\n"]}
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var
|
|
2
|
+
'use strict';var chunkK5LXUJ4G_js=require('./chunk-K5LXUJ4G.js'),commander=require('commander'),prompts=require('@clack/prompts'),colors=require('kleur/colors'),D=require('gradient-string'),Ge=require('cli-table3'),B=require('fs'),ae=require('path'),_e=require('os');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var D__default=/*#__PURE__*/_interopDefault(D);var Ge__default=/*#__PURE__*/_interopDefault(Ge);var B__default=/*#__PURE__*/_interopDefault(B);var ae__default=/*#__PURE__*/_interopDefault(ae);var _e__default=/*#__PURE__*/_interopDefault(_e);function q(e){return new Ge__default.default({head:e.map(o=>x.magenta(x.bold(o))),chars:{top:"\u2500","top-mid":"\u252C","top-left":"\u250C","top-right":"\u2510",bottom:"\u2500","bottom-mid":"\u2534","bottom-left":"\u2514","bottom-right":"\u2518",left:"\u2502","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u253C",right:"\u2502","right-mid":"\u2524",middle:"\u2502"},style:{"padding-left":1,"padding-right":1,head:[],border:["gray"]}})}function W(e){console.clear(),console.log(D__default.default(["#A855F7","#EC4899","#3B82F6"])(`
|
|
3
3
|
\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557
|
|
4
4
|
\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551
|
|
5
5
|
\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551
|
|
@@ -8,18 +8,18 @@
|
|
|
8
8
|
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D
|
|
9
9
|
`)),console.log(`${colors.bgMagenta(colors.black(` Langtrain SDK v${e} `))}
|
|
10
10
|
`);}function v(e){console.log(colors.magenta(`\u25C6 ${e}`));}function K(e){console.log(colors.gray(`\u2514 ${e}`));}function p(){return {start:e=>process.stdout.write(`${colors.magenta("\u25CF")} ${e}\r`),stop:e=>{console.log(e?`${colors.green("\u2714")} ${e}`:"");},message:e=>process.stdout.write(`${colors.magenta("\u25CF")} ${e}\r`)}}function _(e){console.log(colors.green(`\u2714 ${e}`));}function be(e){console.log(colors.yellow(`\u26A0 Warning: ${e}`));}function ve(e){console.log(colors.blue(`\u2139 ${e}`));}var x={bgMagenta:colors.bgMagenta,black:colors.black,red:colors.red,green:colors.green,yellow:colors.yellow,gray:colors.gray,cyan:colors.cyan,bold:colors.bold,dim:colors.dim,blue:colors.blue,magenta:colors.magenta,white:colors.white};var Q=ae__default.default.join(_e__default.default.homedir(),".langtrain"),X=ae__default.default.join(Q,"config.json");function f(){if(!B__default.default.existsSync(X))return {};try{return JSON.parse(B__default.default.readFileSync(X,"utf-8"))}catch{return {}}}function ee(e){B__default.default.existsSync(Q)||B__default.default.mkdirSync(Q,{recursive:true}),B__default.default.writeFileSync(X,JSON.stringify(e,null,2));}function te(){return !!f().apiKey}async function N(){for(;;){console.log(colors.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(colors.gray(" Get your API Key at: ")+colors.cyan("https://app.langtrain.xyz/home/api")),console.log(colors.dim(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11
|
-
`));let e=await prompts.password({message:"Enter your Langtrain API Key:",validate(a){if(!a||a.length===0)return "API Key is required";if(a.length<10)return "Invalid key format"}});prompts.isCancel(e)&&(prompts.cancel("Operation cancelled"),process.exit(0));let o=p();o.start("Verifying API Key...");try{let t=await new
|
|
11
|
+
`));let e=await prompts.password({message:"Enter your Langtrain API Key:",validate(a){if(!a||a.length===0)return "API Key is required";if(a.length<10)return "Invalid key format"}});prompts.isCancel(e)&&(prompts.cancel("Operation cancelled"),process.exit(0));let o=p();o.start("Verifying API Key...");try{let t=await new chunkK5LXUJ4G_js.h({apiKey:e}).getStatus(),n=t.plan==="pro"?colors.bgMagenta(colors.black(" PRO ")):t.plan==="enterprise"?colors.bgMagenta(colors.black(" ENTERPRISE ")):" FREE ";if(o.stop(colors.green(`Authenticated ${n}`)),t.usage){let s=t.usage.tokensUsedThisMonth||0,r=t.usage.tokenLimit||1e4,c=Math.round(s/r*100);console.log(colors.dim(` Tokens: ${s.toLocaleString()} / ${r.toLocaleString()} (${c}% used)`));}let i=f();ee({...i,apiKey:e}),console.log(colors.green(` \u2714 Credentials saved to ~/.langtrain/config.json
|
|
12
12
|
`));return}catch{o.stop(colors.red("Invalid API Key. Please try again."));}}}async function ne(){let e=f();delete e.apiKey,ee(e),console.log(colors.green(`
|
|
13
13
|
\u2714 Logged out. Credentials cleared.
|
|
14
|
-
`));}async function J(e){let o=new
|
|
15
|
-
`)),t}catch(t){return a.stop(colors.red("Failed to verify subscription.")),t.response&&t.response.status===401&&console.log(colors.red(" API Key expired. Please login again.")),null}}function Ce(e,o,a){if(!a)return [{value:"login",label:"\u2192 Login",hint:"Authenticate with your API key"},{value:"docs",label:" Documentation",hint:"https://docs.langtrain.ai"},{value:"exit",label:" Exit"}];let t=o?.plan==="pro"?"PRO":o?.plan==="enterprise"?"ENTERPRISE":"FREE";switch(e){case "main":return [{value:"nav-agents",label:" Agents",hint:"Manage & deploy AI agents"},{value:"nav-text",label:" Langtune",hint:"Text fine-tuning & generation"},{value:"nav-vision",label:" Langvision",hint:"Vision fine-tuning & analysis"},{value:"nav-guard",label:" Guardrails",hint:"Data quality & safety rules"},{value:"init",label:" Init Project",hint:"Scaffold new Langtrain app"},{value:"deploy",label:" Deploy",hint:"Push to Langtrain Cloud"},{value:"dev",label:" Dev Server",hint:"Local watch mode"},{value:"env",label:" Secrets",hint:"Manage environment variables"},{value:"logs",label:" Logs",hint:"Stream agent logs"},{value:"tokens",label:" Token Usage",hint:"View consumption this period"},{value:"telemetry",label:" Telemetry",hint:"Session stats & API health"},{value:"doctor",label:" Doctor",hint:"Check environment health"},{value:"nav-settings",label:" Settings",hint:`Plan: ${t}`},{value:"exit",label:" Exit"}];case "agents":return [{value:"agent-list",label:"List & Run Agents",hint:"Chat with active agents"},{value:"agent-create",label:"Create New Agent",hint:"Deploy a new agent"},{value:"agent-delete",label:"Delete Agent",hint:"Remove an agent"},{value:"back",label:"\u2190 Back"}];case "text":return [{value:"tune-finetune",label:"Fine-tune Text Model",hint:"Create custom LLM"},{value:"tune-list",label:"List Jobs",hint:"Check training status"},{value:"tune-generate",label:"Generate Text",hint:"Test your models"},{value:"data-upload",label:"Upload Dataset",hint:"Upload JSONL for training"},{value:"back",label:"\u2190 Back"}];case "guard":return [{value:"guard-list",label:"List Guardrails",hint:"View active rules"},{value:"guard-create",label:"Create Guardrail",hint:"Define new rules"},{value:"data-refine",label:"Refine Dataset",hint:"Apply guardrail to data"},{value:"back",label:"\u2190 Back"}];case "vision":return [{value:"vision-finetune",label:"Fine-tune Vision Model",hint:"Create custom VLM"},{value:"vision-generate",label:"Generate Vision Response",hint:"Test vision models"},{value:"back",label:"\u2190 Back"}];case "settings":return [{value:"status",label:`Subscription (${t})`,hint:"View plan details"},{value:"tokens",label:"Token Usage",hint:"View consumption"},{value:"telemetry",label:"Telemetry",hint:"Session & API health"},{value:"login",label:"Update API Key",hint:"Change credentials"},{value:"logout",label:"Logout",hint:"Clear stored credentials"},{value:"back",label:"\u2190 Back"}];default:return []}}async function ke(){let e=f();if(!e.apiKey){v(colors.red('Not logged in. Run "login" first.'));return}let o=new
|
|
16
|
-
Limits:`)),console.log(` Models: ${t.limits.max_models===-1?"Unlimited":t.limits.max_models}`),console.log(` Training Jobs: ${t.limits.max_training_jobs}`);}catch(t){a.stop(colors.red("Failed to fetch status.")),console.error(t.message);}}async function Se(e,o){let a="",t=p();t.start("Fetching available text models...");try{let c=await o.list("text");t.stop(`Found ${c.length} text models`),c.length>0&&(a=await prompts.select({message:"Select base model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}));}catch{t.stop(colors.yellow("Failed to fetch models. Using manual input.")),a=await prompts.text({message:"Enter base model (e.g., gpt-3.5-turbo):",placeholder:"gpt-3.5-turbo",validate(l){if(!l||l.length===0)return "Value is required!"}});}prompts.isCancel(a)&&(prompts.cancel("Operation cancelled."),process.exit(0));let n=await prompts.text({message:"Enter path to training file:",placeholder:"./data.jsonl",validate(c){if(!c||c.length===0)return "Value is required!"}});prompts.isCancel(n)&&prompts.cancel("Operation cancelled.");let i=await prompts.text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});prompts.isCancel(i)&&prompts.cancel("Operation cancelled.");let s=await prompts.select({message:"Track this job on Langtrain Cloud?",options:[{value:"yes",label:"Yes",hint:"Upload dataset and log job"},{value:"no",label:"No",hint:"Local only"}]});if(prompts.isCancel(s)&&prompts.cancel("Operation cancelled."),s==="yes"){let c=p();c.start("Connecting to Cloud...");try{let l=f();if(!l.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new chunkZN3AO753_js.h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(colors.red('Feature "cloud_finetuning" is not available on your plan.'));let V=await prompts.confirm({message:"Upgrade to Pro for cloud tracking?"});V&&!prompts.isCancel(V)&&console.log(colors.bgMagenta(colors.black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let S=new chunkZN3AO753_js.f({apiKey:l.apiKey}),M=new chunkZN3AO753_js.g({apiKey:l.apiKey});c.message("Uploading dataset...");let O=await S.upload(n);c.message("Creating Job...");let Y=await M.createJob({name:`cli-sft-${Date.now()}`,base_model:a,dataset_id:O.id,task:"text",hyperparameters:{n_epochs:parseInt(i)}});c.stop(colors.green(`Job tracked: ${Y.id}`));}catch(l){c.stop(colors.red(`Tracking failed: ${l.message}`));let w=await prompts.confirm({message:"Continue with local training anyway?"});if(!w||prompts.isCancel(w))return}}let r=p();r.start("Starting local fine-tuning...");try{let c={model:a,trainFile:n,preset:"default",epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./output"};await e.finetune(c),r.stop(colors.green("Fine-tuning job started successfully!"));}catch(c){throw r.stop(colors.red("Failed to start job.")),c}}async function xe(e){let o=await prompts.text({message:"Enter model path:",placeholder:"./output/model",initialValue:"./output/model"});prompts.isCancel(o)&&prompts.cancel("Operation cancelled");let a=await prompts.text({message:"Enter prompt:",placeholder:"Hello world"});prompts.isCancel(a)&&prompts.cancel("Operation cancelled");let t=p();t.start("Connecting to Langtrain Inference API...");try{let n=await e.generate(o,{prompt:a});t.stop("Generation complete"),v("Response:"),console.log(D__default.default.pastel(n));}catch(n){throw t.stop(colors.red("Generation failed.")),n}}async function Le(e){let o=p();o.start("Fetching fine-tuning jobs...");let t=f().workspace_id;if(!(!t&&(o.stop(colors.yellow("Workspace ID required to list jobs.")),t=await prompts.text({message:"Enter Workspace ID:"}),prompts.isCancel(t))))try{let n=await e.listJobs(t);if(o.stop(`Found ${n.data.length} jobs`),n.data.length===0){console.log(colors.yellow("No jobs found."));return}let i=q(["ID","Status","Model","Progress","Created"]);n.data.forEach(r=>{let c=r.status==="succeeded"?colors.green:r.status==="failed"?colors.red:colors.yellow;i.push([r.id.substring(0,8)+"...",c(r.status),r.base_model,(r.progress||0)+"%",new Date(r.created_at).toLocaleDateString()]);}),console.log(i.toString()),console.log("");let s=await prompts.select({message:"Select a job to view details:",options:n.data.map(r=>({value:r.id,label:`${r.name||r.id} (${r.status})`,hint:`Created: ${new Date(r.created_at).toLocaleDateString()}`}))});if(prompts.isCancel(s))return;await Ae(e,s);}catch(n){o.stop(colors.red(`Failed to list jobs: ${n.message}`));}}async function Ae(e,o){let a=o;if(!a&&(a=await prompts.text({message:"Enter Job ID:"}),prompts.isCancel(a)))return;let t=p();t.start(`Fetching status for ${a}...`);try{let n=await e.getJob(a);if(t.stop(`Job Status: ${n.status.toUpperCase()}`),console.log(colors.gray("------------------------------------------------")),console.log(`${colors.bgMagenta(colors.black(" Job Details "))}`),console.log(`ID: ${n.id}`),console.log(`Name: ${n.name}`),console.log(`Status: ${n.status==="succeeded"?colors.green(n.status):n.status}`),console.log(`Model: ${n.base_model}`),console.log(`Progress: ${n.progress||0}%`),n.error_message&&console.log(colors.red(`Error: ${n.error_message}`)),console.log(colors.gray("------------------------------------------------")),n.status==="running"||n.status==="queued"){let i=await prompts.select({message:"Action:",options:[{value:"refresh",label:"Refresh Status"},{value:"cancel",label:"Cancel Job"},{value:"back",label:"Back"}]});i==="refresh"&&await Ae(e,a),i==="cancel"&&await qe(e,a);}}catch(n){t.stop(colors.red(`Failed to get job status: ${n.message}`));}}async function qe(e,o){let a=await prompts.confirm({message:"Are you sure you want to cancel this job?"});if(!a||prompts.isCancel(a))return;let t=p();t.start("Canceling job...");try{await e.cancelJob(o),t.stop(colors.green("Job canceled successfully."));}catch(n){t.stop(colors.red(`Failed to cancel job: ${n.message}`));}}async function Fe(e,o){let a="",t=p();t.start("Fetching available vision models...");try{let c=await o.list("vision");t.stop(`Found ${c.length} vision models`),c.length>0?a=await prompts.select({message:"Select base vision model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}):a=await prompts.text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}catch{t.stop(colors.yellow("Failed to fetch models. Using manual input.")),a=await prompts.text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}prompts.isCancel(a)&&(prompts.cancel("Operation cancelled"),process.exit(0));let n=await prompts.text({message:"Enter dataset path:",placeholder:"./dataset"});prompts.isCancel(n)&&prompts.cancel("Operation cancelled");let i=await prompts.text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});prompts.isCancel(i)&&prompts.cancel("Operation cancelled");let s=await prompts.select({message:"Track this job on Langtrain Cloud?",options:[{value:"yes",label:"Yes",hint:"Upload dataset and log job"},{value:"no",label:"No",hint:"Local only"}]});if(prompts.isCancel(s)&&prompts.cancel("Operation cancelled"),s==="yes"){let c=p();c.start("Connecting to Cloud...");try{let l=f();if(!l.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new chunkZN3AO753_js.h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(colors.red('Feature "cloud_finetuning" is not available on your plan.'));let V=await prompts.confirm({message:"Upgrade to Pro for cloud tracking?"});V&&!prompts.isCancel(V)&&console.log(colors.bgMagenta(colors.black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let S=new chunkZN3AO753_js.f({apiKey:l.apiKey}),M=new chunkZN3AO753_js.g({apiKey:l.apiKey});c.message("Uploading dataset...");let O=await S.upload(n,void 0,"fine-tune-vision");c.message("Creating Job...");let Y=await M.createJob({name:`cli-vision-${Date.now()}`,base_model:a,dataset_id:O.id,task:"vision",training_method:"lora",hyperparameters:{n_epochs:parseInt(i)}});c.stop(colors.green(`Job tracked: ${Y.id}`));}catch(l){c.stop(colors.red(`Tracking failed: ${l.message}`));let w=await prompts.confirm({message:"Continue with local training anyway?"});if(!w||prompts.isCancel(w))return}}let r=p();r.start("Analyzing dataset structure..."),await new Promise(c=>setTimeout(c,800)),r.message("Starting vision fine-tuning on Langtrain Cloud...");try{let c={model:a,dataset:n,epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./vision-output"};await e.finetune(c),r.stop(colors.green("Vision fine-tuning started successfully!"));}catch(c){throw r.stop(colors.red("Failed to start vision job.")),c}}async function Ie(e){let o=await prompts.text({message:"Enter model path:",placeholder:"./vision-output/model",initialValue:"./vision-output/model"});prompts.isCancel(o)&&prompts.cancel("Operation cancelled");let a=await prompts.text({message:"Enter prompt/image path:",placeholder:"Describe this image..."});prompts.isCancel(a)&&prompts.cancel("Operation cancelled");let t=p();t.start("Uploading image and context..."),await new Promise(n=>setTimeout(n,600)),t.message("Generating vision response...");try{let n=await e.generate(o,{prompt:a});t.stop("Generation complete"),v("Response:"),console.log(D__default.default.pastel(n));}catch(n){throw t.stop(colors.red("Generation failed.")),n}}async function De(e,o){let a=await prompts.text({message:"Agent Name:",placeholder:"e.g. Support Bot",validate(c){if(!c||c.length===0)return "API Key is required"}});if(prompts.isCancel(a)){prompts.cancel("Operation cancelled");return}let t=await prompts.text({message:"Description:",placeholder:"e.g. A helpful support assistant"});if(prompts.isCancel(t))return;let n=await prompts.text({message:"System Prompt:",placeholder:"e.g. You are a helpful assistant.",initialValue:"You are a helpful assistant."});if(prompts.isCancel(n))return;let i="gpt-4o",s=p();s.start("Fetching agent models...");try{let c=await o.list("agent");s.stop(`Found ${c.length} models`),c.length>0&&(i=await prompts.select({message:"Select Agent Model:",options:c.map(l=>({value:l.id,label:l.id}))}));}catch{s.stop(colors.yellow("Could not fetch models, using default."));}if(prompts.isCancel(i))return;let r=p();r.start("Creating agent...");try{let c=await e.list(),l="";if(c.length>0)l=c[0].workspace_id;else {r.stop(colors.yellow("Workspace ID needed (no existing agents found)."));let k=await prompts.text({message:"Enter Workspace ID (UUID):",validate(S){if(!S||S.length===0)return "Required"}});if(prompts.isCancel(k))return;l=k,r.start("Creating agent...");}let w=await e.create({workspace_id:l,name:a,description:t,config:{system_prompt:n,model:i}});r.stop(colors.green(`Agent "${w.name}" created successfully! ID: ${w.id}`));}catch(c){throw r.stop(colors.red("Failed to create agent.")),c}}async function Ee(e){let o=p();o.start("Fetching agents...");let a=await e.list();if(o.stop(`Found ${a.length} agents`),a.length===0){v(colors.yellow("No agents to delete."));return}let t=await prompts.select({message:"Select an agent to DELETE:",options:a.map(s=>({value:s.id,label:s.name,hint:s.description||"No description"}))});if(prompts.isCancel(t))return;if(await prompts.select({message:"Are you sure you want to delete this agent?",options:[{value:"yes",label:"Yes, delete it",hint:"Cannot be undone"},{value:"no",label:"No, keep it"}]})!=="yes"){v(colors.gray("Deletion cancelled."));return}let i=p();i.start("Deleting agent...");try{await e.delete(t),i.stop(colors.green("Agent deleted successfully."));}catch(s){throw i.stop(colors.red("Failed to delete agent.")),s}}async function Pe(e){let o=p();o.start("Fetching agents...");let a=await e.list();if(o.stop(`Found ${a.length} agents`),a.length===0){v(colors.yellow("No agents found in your workspace."));return}let t=q(["ID","Name","Model","Created"]);a.forEach(i=>{t.push([i.id.substring(0,8)+"...",i.name,i.config?.model||"default",new Date(i.created_at).toLocaleDateString()]);}),console.log(t.toString()),console.log("");let n=await prompts.select({message:"Select an agent to run:",options:a.map(i=>({value:i.id,label:i.name,hint:i.description||"No description"}))});prompts.isCancel(n)||await Ke(e,n,a.find(i=>i.id===n)?.name||"Agent");}async function Ke(e,o,a,t){v(colors.bgMagenta(colors.black(` Chatting with ${a} `))),console.log(colors.gray('Type "exit" to quit conversation.'));let n;for(;;){let i=await prompts.text({message:"You:",placeholder:"Type a message..."});if(prompts.isCancel(i)||i==="exit")break;let s=p();s.start("Agent is thinking...");try{let r=await e.execute(o,{prompt:i},[],n);s.stop(),r.output?.response?console.log(D__default.default.pastel(`Agent: ${r.output.response}`)):console.log(D__default.default.pastel(`Agent: ${JSON.stringify(r.output)}`)),n=r.conversation_id;}catch(r){s.stop(colors.red("Error running agent.")),console.error(r);}}}async function oe(){v("Initializing new Langtrain project...");let e=process.cwd();if(B__default.default.existsSync(ae__default.default.join(e,"langtrain.config.json"))){ve("langtrain.config.json already exists in this directory.");let s=await prompts.confirm({message:"Do you want to re-initialize and overwrite the config?",initialValue:false});if(prompts.isCancel(s)||!s){K("Initialization cancelled.");return}}let o=await prompts.text({message:"What is the name of your project?",placeholder:"my-ai-app",initialValue:ae__default.default.basename(e),validate(s){if(!s||s.length===0)return "Project name is required!"}});if(prompts.isCancel(o)){prompts.cancel("Operation cancelled.");return}let a=f(),t=a.apiKey;if(t)_("Found existing Langtrain credentials.");else {let s=await prompts.confirm({message:"You are not logged in. Do you want to log in now?",initialValue:true});if(prompts.isCancel(s)){prompts.cancel("Operation cancelled.");return}if(s)await N(),a=f(),t=a.apiKey;else if(t=await prompts.text({message:"Enter your Langtrain API Key (optional for local dev):",placeholder:"lt_sk_...",initialValue:""}),prompts.isCancel(t)){prompts.cancel("Operation cancelled.");return}}p().start("Creating configuration...");let i={name:o,apiKey:t||void 0,environment:"development",agents:[{name:"support-bot",description:"A helpful customer support assistant",config:{model:"llama-3-8b",system_prompt:"You are a helpful customer support assistant.",temperature:.7}}]};B__default.default.writeFileSync(ae__default.default.join(e,"langtrain.config.json"),JSON.stringify(i,null,2)),_("Project initialized successfully!"),console.log(x.dim(`
|
|
17
|
-
Next steps:`)),console.log(` 1. Run ${x.cyan("lt deploy")} to push your agent to the cloud.`),console.log(` 2. Run ${x.cyan("lt dev")} to start the local development loop.`),K("Happy coding!");}async function Te(){v("Running Langtrain Doctor...");let e=p(),o=0;e.start("Checking Node.js environment...");let a=process.version,t=_e__default.default.platform(),n=_e__default.default.arch();parseInt(a.replace("v","").split(".")[0])<18?(e.stop(x.red(`Node.js version ${a} is outdated. Please upgrade to v18+.`)),o++):e.stop(`Node.js ${a} (${t} ${n})`),e.start("Checking configuration...");let i=f();if(!i.apiKey)e.stop(x.yellow("API Key is missing. Run `langtrain login` or set LANGTRAIN_API_KEY.")),o++;else {e.stop("Configuration found."),e.start("Checking API connectivity...");try{let s=await J(i.apiKey);e.stop(`Connected to Langtrain Cloud (Plan: ${x.green(s?.plan||"unknown")})`);}catch(s){e.stop(x.red(`Failed to connect to Langtrain Cloud: ${s.message}`)),o++;}}console.log(""),o===0?_("Your Langtrain environment is healthy! Ready to build."):be(`Found ${o} issue(s). Please resolve them for the best experience.`),K("Doctor check complete.");}async function ie(e){let a=f().workspace_id,t=await prompts.text({message:"Path to file:",placeholder:"./dataset.jsonl",validate(s){if(!s)return "Required";if(!B__default.default.existsSync(s))return "File not found"}});if(prompts.isCancel(t))return;let n=await prompts.select({message:"File Purpose:",options:[{value:"fine-tune",label:"Fine-tuning (JSONL)"},{value:"vision-tune",label:"Vision Tuning (Image/Zip)"},{value:"agent-knowledge",label:"Agent Knowledge"}]});if(prompts.isCancel(n))return;let i=p();i.start("Uploading file...");try{let s=await e.upload(t,a,n);i.stop(colors.green("File uploaded successfully!")),console.log(colors.gray(`ID: ${s.id}`)),console.log(colors.gray(`Name: ${s.filename}`)),console.log(colors.gray(`Bytes: ${s.bytes}`));}catch(s){i.stop(colors.red(`Upload failed: ${s.message}`));}}async function se(e,o){let a=f(),t=new chunkZN3AO753_js.m({apiKey:a.apiKey||"",baseUrl:a.baseUrl});if(!o){let r=p();r.start("Fetching files...");try{let c=a.workspace_id||"",l=await e.list(c);if(r.stop(`Found ${l.length} files`),l.length===0){console.log(colors.yellow("No files found. Upload one first."));return}let w=await prompts.select({message:"Select file to refine:",options:l.map(k=>({value:k.id,label:`${k.filename} (${We(k.bytes)})`}))});if(prompts.isCancel(w))return;o=w;}catch(c){r.stop(colors.red(`Failed to fetch files: ${c.message}`));return}}let n=p();n.start("Fetching guardrails...");let i="";try{let r=await t.list();if(n.stop(`Found ${r.length} guardrails`),r.length===0){console.log(colors.yellow('No guardrails found. Please create one first using "lt guardrails create".'));return}let c=await prompts.select({message:"Select a Guardrail to apply:",options:r.map(l=>({value:l.id,label:l.name,hint:l.description}))});if(prompts.isCancel(c))return;i=c;}catch(r){n.stop(colors.red(`Failed to fetch guardrails: ${r.message}`));return}let s=p();s.start("Applying guardrail (filtering dataset)...");try{let r=await t.apply(o,i);s.stop(colors.green("Dataset refined successfully!")),console.log(colors.gray("Stats:")),console.log(`Original Rows: ${r.original_rows}`),console.log(`Filtered Rows: ${r.filtered_rows}`),console.log(colors.red(`Removed: ${r.removed_rows} rows`)),console.log(colors.green(`New Dataset ID: ${r.new_dataset_id}`));}catch(r){s.stop(colors.red(`Failed to refine dataset: ${r.message}`));}}function We(e,o=2){if(!+e)return "0 Bytes";let a=1024,t=o<0?0:o,n=["Bytes","KB","MB","GB","TB"],i=Math.floor(Math.log(e)/Math.log(a));return `${parseFloat((e/Math.pow(a,i)).toFixed(t))} ${n[i]}`}async function j(e){v("Deploying configuration to Langtrain Cloud...");let o=f(),a=o.agents||[];if(a.length===0){v(colors.yellow("No agents found in langtrain.config.json"));return}for(let t of a){let n=p();n.start(`Deploying agent: ${t.name}...`);try{let i=await e.list(),s=i.find(r=>r.name===t.name);if(s)n.stop(colors.yellow(`Agent ${t.name} already exists (ID: ${s.id}). Skipping update (not supported yet).`));else {let r={workspace_id:o.workspace_id||i[0]?.workspace_id||"",name:t.name,description:t.description,config:t.config};if(!r.workspace_id){n.stop(colors.red(`Failed: Workspace ID missing in config for ${t.name}`));continue}await e.create(r),n.stop(colors.green(`Agent ${t.name} deployed successfully!`));}}catch(i){n.stop(colors.red(`Failed to deploy ${t.name}: ${i.message}`));}}_("Deployment complete.");}async function re(e){v("Starting Langtrain Development Server...");let o=ae__default.default.join(process.cwd(),"langtrain.config.json");if(!B__default.default.existsSync(o)){v(colors.red('langtrain.config.json not found. Run "lt init" first.'));return}console.log(colors.gray(`Watching ${o} for changes...`));let a=false;await j(e),B__default.default.watch(o,async t=>{if(t==="change"&&!a){a=true,console.log(colors.yellow("Configuration changed. Redeploying...")),await new Promise(n=>setTimeout(n,500));try{await j(e);}catch(n){console.error(colors.red(`Deploy failed: ${n.message}`));}finally{a=false,console.log(colors.gray(`Watching ${o}...`));}}}),await new Promise(()=>{});}async function le(e){let o=f(),a=new chunkZN3AO753_js.m({apiKey:o.apiKey||"",baseUrl:o.baseUrl}),t=p();t.start("Fetching guardrails...");try{let n=await a.list();if(t.stop(`Found ${n.length} guardrails`),n.length===0){console.log(colors.yellow('No guardrails found. Create one with "lt guardrails create".'));return}n.forEach(i=>{console.log(colors.green(`\u2022 ${i.name}`)+colors.gray(` (ID: ${i.id})`)),i.description&&console.log(colors.gray(` ${i.description}`)),console.log(colors.gray(` Config: PII=${i.config.pii_enabled}, MinLen=${i.config.min_length}`)),console.log("");});}catch(n){t.stop(colors.red(`Failed to list guardrails: ${n.message}`));}}async function ce(e){let o=f(),a=new chunkZN3AO753_js.m({apiKey:o.apiKey||"",baseUrl:o.baseUrl});v("Create a new Data Guardrail");let t=await prompts.text({message:"Guardrail Name:",placeholder:"e.g. Strict Safety Policy",validate(l){if(!l)return "Name is required"}});if(prompts.isCancel(t))return;let n=await prompts.text({message:"Description (optional):",placeholder:"Filters PII and short text"});if(prompts.isCancel(n))return;let i=await prompts.text({message:"Minimum Text Length (0 for no limit):",initialValue:"0",validate(l){if(isNaN(Number(l)))return "Must be a number"}});if(prompts.isCancel(i))return;let s=await prompts.confirm({message:"Enable PII Filtering (Email/Phone)?",initialValue:false});if(prompts.isCancel(s))return;let r=await prompts.text({message:"Regex Patterns to Block (comma separated, optional):",placeholder:"e.g. bad_word, another_one"});if(prompts.isCancel(r))return;let c=p();c.start("Creating guardrail...");try{let l=r.split(",").map(S=>S.trim()).filter(S=>S.length>0),w={name:t,description:n,config:{min_length:Number(i),pii_enabled:s,regex_patterns:l,profanity_enabled:!1}},k=await a.create(w);c.stop(colors.green(`Guardrail "${k.name}" created successfully!`)),console.log(colors.gray(`ID: ${k.id}`));}catch(l){c.stop(colors.red(`Failed to create guardrail: ${l.message}`));}}async function He(e){let o=p();o.start("Fetching secrets...");let a=f();try{let t=await e.list(a.workspace_id);if(o.stop(`Found ${t.length} secrets`),t.length===0){console.log(colors.gray('No secrets found. Use "lt env set" to add one.'));return}console.log(colors.gray("------------------------------------------------")),t.forEach(n=>{console.log(`${n.key.padEnd(30)} ${colors.gray("******")}`);}),console.log(colors.gray("------------------------------------------------"));}catch(t){o.stop(colors.red(`Failed to list secrets: ${t.message}`));}}async function Ze(e,o){let a="",t="";if(a=await prompts.text({message:"Secret Key:",placeholder:"OPENAI_API_KEY"}),prompts.isCancel(a)||(t=await prompts.text({message:"Secret Value:",placeholder:"sk-..."}),prompts.isCancel(t)))return;let n=p();n.start(`Setting ${a}...`);let i=f();try{await e.set(a,t,i.workspace_id),n.stop(colors.green(`Secret ${a} set successfully.`));}catch(s){n.stop(colors.red(`Failed to set secret: ${s.message}`));}}async function ge(e){let o=await prompts.select({message:"Manage Secrets",options:[{value:"list",label:"List Secrets"},{value:"set",label:"Set Secret"},{value:"remove",label:"Remove Secret"},{value:"back",label:"Back"}]});if(!(prompts.isCancel(o)||o==="back")&&(o==="list"&&await He(e),o==="set"&&await Ze(e),o==="remove")){let a=await prompts.text({message:"Key to remove:"});if(!prompts.isCancel(a)){let t=p();t.start("Removing...");try{let n=f();await e.delete(a,n.workspace_id),t.stop(colors.green("Removed."));}catch(n){t.stop(colors.red(`Failed: ${n.message}`));}}}}async function ue(e,o){let a=p(),t="";if(o){a.start("Finding agent...");try{let s=(await e.list()).find(r=>r.name===o||r.id===o);if(s)t=s.id;else {a.stop(colors.red(`Agent "${o}" not found.`));return}a.stop(colors.green(`Found agent: ${s.name}`));}catch(i){a.stop(colors.red(`Failed to list agents: ${i.message}`));return}}else {a.start("Fetching agents...");try{let i=await e.list();if(a.stop(`Found ${i.length} agents`),i.length===0){console.log(colors.yellow("No agents found."));return}let s=await prompts.select({message:"Select agent to view logs:",options:i.map(r=>({value:r.id,label:r.name}))});if(prompts.isCancel(s))return;t=s;}catch(i){a.stop(colors.red(`Failed to list agents: ${i.message}`));return}}let n=p();n.start("Fetching logs...");try{let i=await e.logs(t);n.stop("Logs fetched."),console.log(colors.gray("------------------------------------------------")),console.log(`${colors.bgMagenta(colors.black(" Recent Logs "))}`),i.logs&&i.logs.length>0?i.logs.forEach(s=>console.log(s)):console.log(colors.gray("(No logs found)")),console.log(colors.gray("------------------------------------------------"));}catch(i){n.stop(colors.red(`Failed to fetch logs: ${i.message}`));}}var Qe=Date.now(),T=0,Ue=0;async function pe(){let e=f(),o=e.apiKey;if(console.log(""),console.log(colors.bold(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(colors.bold(" \u2551 TOKEN USAGE \u2551")),console.log(colors.bold(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),!o){console.log(colors.yellow(` Login required to view token usage.
|
|
18
|
-
`));return}let a=p();a.start("Fetching token usage...");try{let t=
|
|
19
|
-
`)),console.log(` ${colors.dim("Session calls:")} ${T}`),console.log(` ${colors.dim("Est. tokens:")} ~${T*150}`),console.log("");}}async function Ne(){let e=Date.now()-Qe,o=Math.round(e/1e3),a=Math.floor(o/60),t=a>0?`${a}m ${o%60}s`:`${o}s`,n=0,i=0;console.log(""),console.log(colors.bold(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(colors.bold(" \u2551 SESSION TELEMETRY \u2551")),console.log(colors.bold(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(` ${colors.dim("Session:")} ${t}`),console.log(` ${colors.dim("API calls:")} ${T}`),console.log(` ${colors.dim("Avg latency:")} ${n}ms`),console.log(` ${colors.dim("Errors:")} ${Ue} (${i}%)`),console.log(""),console.log(colors.dim(" \u2500\u2500 Environment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(` ${colors.dim("Node:")} ${process.version}`),console.log(` ${colors.dim("Platform:")} ${process.platform} ${process.arch}`),console.log(` ${colors.dim("Memory:")} ${Math.round(process.memoryUsage().heapUsed/1024/1024)}MB heap`),console.log(` ${colors.dim("Config:")} ~/.langtrain/config.json`),console.log("");let s=f();if(s.apiKey){let r=p();r.start("Pinging API...");try{let c=
|
|
20
|
-
`));}function Ve(e,o){return {vision:new
|
|
14
|
+
`));}async function J(e){let o=new chunkK5LXUJ4G_js.h({apiKey:e}),a=p();a.start("Checking subscription...");try{let t=await o.getStatus(),n=t.plan==="pro"?colors.bgMagenta(colors.black(" PRO ")):t.plan==="enterprise"?colors.bgMagenta(colors.black(" ENTERPRISE ")):colors.bold(" FREE ");return a.stop(colors.green(`Plan: ${n}`)),t.is_active===!1&&console.log(colors.yellow(` \u26A0 Subscription inactive. Some features may be limited.
|
|
15
|
+
`)),t}catch(t){return a.stop(colors.red("Failed to verify subscription.")),t.response&&t.response.status===401&&console.log(colors.red(" API Key expired. Please login again.")),null}}function Ce(e,o,a){if(!a)return [{value:"login",label:"\u2192 Login",hint:"Authenticate with your API key"},{value:"docs",label:" Documentation",hint:"https://docs.langtrain.ai"},{value:"exit",label:" Exit"}];let t=o?.plan==="pro"?"PRO":o?.plan==="enterprise"?"ENTERPRISE":"FREE";switch(e){case "main":return [{value:"nav-agents",label:" Agents",hint:"Manage & deploy AI agents"},{value:"nav-text",label:" Langtune",hint:"Text fine-tuning & generation"},{value:"nav-vision",label:" Langvision",hint:"Vision fine-tuning & analysis"},{value:"nav-guard",label:" Guardrails",hint:"Data quality & safety rules"},{value:"init",label:" Init Project",hint:"Scaffold new Langtrain app"},{value:"deploy",label:" Deploy",hint:"Push to Langtrain Cloud"},{value:"dev",label:" Dev Server",hint:"Local watch mode"},{value:"env",label:" Secrets",hint:"Manage environment variables"},{value:"logs",label:" Logs",hint:"Stream agent logs"},{value:"tokens",label:" Token Usage",hint:"View consumption this period"},{value:"telemetry",label:" Telemetry",hint:"Session stats & API health"},{value:"doctor",label:" Doctor",hint:"Check environment health"},{value:"nav-settings",label:" Settings",hint:`Plan: ${t}`},{value:"exit",label:" Exit"}];case "agents":return [{value:"agent-list",label:"List & Run Agents",hint:"Chat with active agents"},{value:"agent-create",label:"Create New Agent",hint:"Deploy a new agent"},{value:"agent-delete",label:"Delete Agent",hint:"Remove an agent"},{value:"back",label:"\u2190 Back"}];case "text":return [{value:"tune-finetune",label:"Fine-tune Text Model",hint:"Create custom LLM"},{value:"tune-list",label:"List Jobs",hint:"Check training status"},{value:"tune-generate",label:"Generate Text",hint:"Test your models"},{value:"data-upload",label:"Upload Dataset",hint:"Upload JSONL for training"},{value:"back",label:"\u2190 Back"}];case "guard":return [{value:"guard-list",label:"List Guardrails",hint:"View active rules"},{value:"guard-create",label:"Create Guardrail",hint:"Define new rules"},{value:"data-refine",label:"Refine Dataset",hint:"Apply guardrail to data"},{value:"back",label:"\u2190 Back"}];case "vision":return [{value:"vision-finetune",label:"Fine-tune Vision Model",hint:"Create custom VLM"},{value:"vision-generate",label:"Generate Vision Response",hint:"Test vision models"},{value:"back",label:"\u2190 Back"}];case "settings":return [{value:"status",label:`Subscription (${t})`,hint:"View plan details"},{value:"tokens",label:"Token Usage",hint:"View consumption"},{value:"telemetry",label:"Telemetry",hint:"Session & API health"},{value:"login",label:"Update API Key",hint:"Change credentials"},{value:"logout",label:"Logout",hint:"Clear stored credentials"},{value:"back",label:"\u2190 Back"}];default:return []}}async function ke(){let e=f();if(!e.apiKey){v(colors.red('Not logged in. Run "login" first.'));return}let o=new chunkK5LXUJ4G_js.h({apiKey:e.apiKey}),a=p();a.start("Fetching subscription status...");try{let t=await o.getStatus();a.stop(colors.green("Subscription Status:")),console.log(colors.gray("Plan: ")+(t.plan==="pro"?colors.bgMagenta(" PRO "):t.plan.toUpperCase())),console.log(colors.gray("Active: ")+(t.is_active?colors.green("Yes"):colors.red("No"))),t.expires_at&&console.log(colors.gray("Expires: ")+new Date(t.expires_at).toLocaleDateString()),console.log(colors.gray(`
|
|
16
|
+
Limits:`)),console.log(` Models: ${t.limits.max_models===-1?"Unlimited":t.limits.max_models}`),console.log(` Training Jobs: ${t.limits.max_training_jobs}`);}catch(t){a.stop(colors.red("Failed to fetch status.")),console.error(t.message);}}async function Se(e,o){let a="",t=p();t.start("Fetching available text models...");try{let c=await o.list("text");t.stop(`Found ${c.length} text models`),c.length>0&&(a=await prompts.select({message:"Select base model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}));}catch{t.stop(colors.yellow("Failed to fetch models. Using manual input.")),a=await prompts.text({message:"Enter base model (e.g., gpt-3.5-turbo):",placeholder:"gpt-3.5-turbo",validate(l){if(!l||l.length===0)return "Value is required!"}});}prompts.isCancel(a)&&(prompts.cancel("Operation cancelled."),process.exit(0));let n=await prompts.text({message:"Enter path to training file:",placeholder:"./data.jsonl",validate(c){if(!c||c.length===0)return "Value is required!"}});prompts.isCancel(n)&&prompts.cancel("Operation cancelled.");let i=await prompts.text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});prompts.isCancel(i)&&prompts.cancel("Operation cancelled.");let s=await prompts.select({message:"Track this job on Langtrain Cloud?",options:[{value:"yes",label:"Yes",hint:"Upload dataset and log job"},{value:"no",label:"No",hint:"Local only"}]});if(prompts.isCancel(s)&&prompts.cancel("Operation cancelled."),s==="yes"){let c=p();c.start("Connecting to Cloud...");try{let l=f();if(!l.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new chunkK5LXUJ4G_js.h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(colors.red('Feature "cloud_finetuning" is not available on your plan.'));let V=await prompts.confirm({message:"Upgrade to Pro for cloud tracking?"});V&&!prompts.isCancel(V)&&console.log(colors.bgMagenta(colors.black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let S=new chunkK5LXUJ4G_js.f({apiKey:l.apiKey}),M=new chunkK5LXUJ4G_js.g({apiKey:l.apiKey});c.message("Uploading dataset...");let O=await S.upload(n);c.message("Creating Job...");let Y=await M.createJob({name:`cli-sft-${Date.now()}`,base_model:a,dataset_id:O.id,task:"text",hyperparameters:{n_epochs:parseInt(i)}});c.stop(colors.green(`Job tracked: ${Y.id}`));}catch(l){c.stop(colors.red(`Tracking failed: ${l.message}`));let w=await prompts.confirm({message:"Continue with local training anyway?"});if(!w||prompts.isCancel(w))return}}let r=p();r.start("Starting local fine-tuning...");try{let c={model:a,trainFile:n,preset:"default",epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./output"};await e.finetune(c),r.stop(colors.green("Fine-tuning job started successfully!"));}catch(c){throw r.stop(colors.red("Failed to start job.")),c}}async function xe(e){let o=await prompts.text({message:"Enter model path:",placeholder:"./output/model",initialValue:"./output/model"});prompts.isCancel(o)&&prompts.cancel("Operation cancelled");let a=await prompts.text({message:"Enter prompt:",placeholder:"Hello world"});prompts.isCancel(a)&&prompts.cancel("Operation cancelled");let t=p();t.start("Connecting to Langtrain Inference API...");try{let n=await e.generate(o,{prompt:a});t.stop("Generation complete"),v("Response:"),console.log(D__default.default.pastel(n));}catch(n){throw t.stop(colors.red("Generation failed.")),n}}async function Le(e){let o=p();o.start("Fetching fine-tuning jobs...");let t=f().workspace_id;if(!(!t&&(o.stop(colors.yellow("Workspace ID required to list jobs.")),t=await prompts.text({message:"Enter Workspace ID:"}),prompts.isCancel(t))))try{let n=await e.listJobs(t);if(o.stop(`Found ${n.data.length} jobs`),n.data.length===0){console.log(colors.yellow("No jobs found."));return}let i=q(["ID","Status","Model","Progress","Created"]);n.data.forEach(r=>{let c=r.status==="succeeded"?colors.green:r.status==="failed"?colors.red:colors.yellow;i.push([r.id.substring(0,8)+"...",c(r.status),r.base_model,(r.progress||0)+"%",new Date(r.created_at).toLocaleDateString()]);}),console.log(i.toString()),console.log("");let s=await prompts.select({message:"Select a job to view details:",options:n.data.map(r=>({value:r.id,label:`${r.name||r.id} (${r.status})`,hint:`Created: ${new Date(r.created_at).toLocaleDateString()}`}))});if(prompts.isCancel(s))return;await Ae(e,s);}catch(n){o.stop(colors.red(`Failed to list jobs: ${n.message}`));}}async function Ae(e,o){let a=o;if(!a&&(a=await prompts.text({message:"Enter Job ID:"}),prompts.isCancel(a)))return;let t=p();t.start(`Fetching status for ${a}...`);try{let n=await e.getJob(a);if(t.stop(`Job Status: ${n.status.toUpperCase()}`),console.log(colors.gray("------------------------------------------------")),console.log(`${colors.bgMagenta(colors.black(" Job Details "))}`),console.log(`ID: ${n.id}`),console.log(`Name: ${n.name}`),console.log(`Status: ${n.status==="succeeded"?colors.green(n.status):n.status}`),console.log(`Model: ${n.base_model}`),console.log(`Progress: ${n.progress||0}%`),n.error_message&&console.log(colors.red(`Error: ${n.error_message}`)),console.log(colors.gray("------------------------------------------------")),n.status==="running"||n.status==="queued"){let i=await prompts.select({message:"Action:",options:[{value:"refresh",label:"Refresh Status"},{value:"cancel",label:"Cancel Job"},{value:"back",label:"Back"}]});i==="refresh"&&await Ae(e,a),i==="cancel"&&await qe(e,a);}}catch(n){t.stop(colors.red(`Failed to get job status: ${n.message}`));}}async function qe(e,o){let a=await prompts.confirm({message:"Are you sure you want to cancel this job?"});if(!a||prompts.isCancel(a))return;let t=p();t.start("Canceling job...");try{await e.cancelJob(o),t.stop(colors.green("Job canceled successfully."));}catch(n){t.stop(colors.red(`Failed to cancel job: ${n.message}`));}}async function Fe(e,o){let a="",t=p();t.start("Fetching available vision models...");try{let c=await o.list("vision");t.stop(`Found ${c.length} vision models`),c.length>0?a=await prompts.select({message:"Select base vision model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}):a=await prompts.text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}catch{t.stop(colors.yellow("Failed to fetch models. Using manual input.")),a=await prompts.text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}prompts.isCancel(a)&&(prompts.cancel("Operation cancelled"),process.exit(0));let n=await prompts.text({message:"Enter dataset path:",placeholder:"./dataset"});prompts.isCancel(n)&&prompts.cancel("Operation cancelled");let i=await prompts.text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});prompts.isCancel(i)&&prompts.cancel("Operation cancelled");let s=await prompts.select({message:"Track this job on Langtrain Cloud?",options:[{value:"yes",label:"Yes",hint:"Upload dataset and log job"},{value:"no",label:"No",hint:"Local only"}]});if(prompts.isCancel(s)&&prompts.cancel("Operation cancelled"),s==="yes"){let c=p();c.start("Connecting to Cloud...");try{let l=f();if(!l.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new chunkK5LXUJ4G_js.h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(colors.red('Feature "cloud_finetuning" is not available on your plan.'));let V=await prompts.confirm({message:"Upgrade to Pro for cloud tracking?"});V&&!prompts.isCancel(V)&&console.log(colors.bgMagenta(colors.black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let S=new chunkK5LXUJ4G_js.f({apiKey:l.apiKey}),M=new chunkK5LXUJ4G_js.g({apiKey:l.apiKey});c.message("Uploading dataset...");let O=await S.upload(n,void 0,"fine-tune-vision");c.message("Creating Job...");let Y=await M.createJob({name:`cli-vision-${Date.now()}`,base_model:a,dataset_id:O.id,task:"vision",training_method:"lora",hyperparameters:{n_epochs:parseInt(i)}});c.stop(colors.green(`Job tracked: ${Y.id}`));}catch(l){c.stop(colors.red(`Tracking failed: ${l.message}`));let w=await prompts.confirm({message:"Continue with local training anyway?"});if(!w||prompts.isCancel(w))return}}let r=p();r.start("Analyzing dataset structure..."),await new Promise(c=>setTimeout(c,800)),r.message("Starting vision fine-tuning on Langtrain Cloud...");try{let c={model:a,dataset:n,epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./vision-output"};await e.finetune(c),r.stop(colors.green("Vision fine-tuning started successfully!"));}catch(c){throw r.stop(colors.red("Failed to start vision job.")),c}}async function Ie(e){let o=await prompts.text({message:"Enter model path:",placeholder:"./vision-output/model",initialValue:"./vision-output/model"});prompts.isCancel(o)&&prompts.cancel("Operation cancelled");let a=await prompts.text({message:"Enter prompt/image path:",placeholder:"Describe this image..."});prompts.isCancel(a)&&prompts.cancel("Operation cancelled");let t=p();t.start("Uploading image and context..."),await new Promise(n=>setTimeout(n,600)),t.message("Generating vision response...");try{let n=await e.generate(o,{prompt:a});t.stop("Generation complete"),v("Response:"),console.log(D__default.default.pastel(n));}catch(n){throw t.stop(colors.red("Generation failed.")),n}}async function De(e,o){let a=await prompts.text({message:"Agent Name:",placeholder:"e.g. Support Bot",validate(c){if(!c||c.length===0)return "API Key is required"}});if(prompts.isCancel(a)){prompts.cancel("Operation cancelled");return}let t=await prompts.text({message:"Description:",placeholder:"e.g. A helpful support assistant"});if(prompts.isCancel(t))return;let n=await prompts.text({message:"System Prompt:",placeholder:"e.g. You are a helpful assistant.",initialValue:"You are a helpful assistant."});if(prompts.isCancel(n))return;let i="gpt-4o",s=p();s.start("Fetching agent models...");try{let c=await o.list("agent");s.stop(`Found ${c.length} models`),c.length>0&&(i=await prompts.select({message:"Select Agent Model:",options:c.map(l=>({value:l.id,label:l.id}))}));}catch{s.stop(colors.yellow("Could not fetch models, using default."));}if(prompts.isCancel(i))return;let r=p();r.start("Creating agent...");try{let c=await e.list(),l="";if(c.length>0)l=c[0].workspace_id;else {r.stop(colors.yellow("Workspace ID needed (no existing agents found)."));let k=await prompts.text({message:"Enter Workspace ID (UUID):",validate(S){if(!S||S.length===0)return "Required"}});if(prompts.isCancel(k))return;l=k,r.start("Creating agent...");}let w=await e.create({workspace_id:l,name:a,description:t,config:{system_prompt:n,model:i}});r.stop(colors.green(`Agent "${w.name}" created successfully! ID: ${w.id}`));}catch(c){throw r.stop(colors.red("Failed to create agent.")),c}}async function Ee(e){let o=p();o.start("Fetching agents...");let a=await e.list();if(o.stop(`Found ${a.length} agents`),a.length===0){v(colors.yellow("No agents to delete."));return}let t=await prompts.select({message:"Select an agent to DELETE:",options:a.map(s=>({value:s.id,label:s.name,hint:s.description||"No description"}))});if(prompts.isCancel(t))return;if(await prompts.select({message:"Are you sure you want to delete this agent?",options:[{value:"yes",label:"Yes, delete it",hint:"Cannot be undone"},{value:"no",label:"No, keep it"}]})!=="yes"){v(colors.gray("Deletion cancelled."));return}let i=p();i.start("Deleting agent...");try{await e.delete(t),i.stop(colors.green("Agent deleted successfully."));}catch(s){throw i.stop(colors.red("Failed to delete agent.")),s}}async function Pe(e){let o=p();o.start("Fetching agents...");let a=await e.list();if(o.stop(`Found ${a.length} agents`),a.length===0){v(colors.yellow("No agents found in your workspace."));return}let t=q(["ID","Name","Model","Created"]);a.forEach(i=>{t.push([i.id.substring(0,8)+"...",i.name,i.config?.model||"default",new Date(i.created_at).toLocaleDateString()]);}),console.log(t.toString()),console.log("");let n=await prompts.select({message:"Select an agent to run:",options:a.map(i=>({value:i.id,label:i.name,hint:i.description||"No description"}))});prompts.isCancel(n)||await Ke(e,n,a.find(i=>i.id===n)?.name||"Agent");}async function Ke(e,o,a,t){v(colors.bgMagenta(colors.black(` Chatting with ${a} `))),console.log(colors.gray('Type "exit" to quit conversation.'));let n;for(;;){let i=await prompts.text({message:"You:",placeholder:"Type a message..."});if(prompts.isCancel(i)||i==="exit")break;let s=p();s.start("Agent is thinking...");try{let r=await e.execute(o,{prompt:i},[],n);s.stop(),r.output?.response?console.log(D__default.default.pastel(`Agent: ${r.output.response}`)):console.log(D__default.default.pastel(`Agent: ${JSON.stringify(r.output)}`)),n=r.conversation_id;}catch(r){s.stop(colors.red("Error running agent.")),console.error(r);}}}async function oe(){v("Initializing new Langtrain project...");let e=process.cwd();if(B__default.default.existsSync(ae__default.default.join(e,"langtrain.config.json"))){ve("langtrain.config.json already exists in this directory.");let s=await prompts.confirm({message:"Do you want to re-initialize and overwrite the config?",initialValue:false});if(prompts.isCancel(s)||!s){K("Initialization cancelled.");return}}let o=await prompts.text({message:"What is the name of your project?",placeholder:"my-ai-app",initialValue:ae__default.default.basename(e),validate(s){if(!s||s.length===0)return "Project name is required!"}});if(prompts.isCancel(o)){prompts.cancel("Operation cancelled.");return}let a=f(),t=a.apiKey;if(t)_("Found existing Langtrain credentials.");else {let s=await prompts.confirm({message:"You are not logged in. Do you want to log in now?",initialValue:true});if(prompts.isCancel(s)){prompts.cancel("Operation cancelled.");return}if(s)await N(),a=f(),t=a.apiKey;else if(t=await prompts.text({message:"Enter your Langtrain API Key (optional for local dev):",placeholder:"lt_sk_...",initialValue:""}),prompts.isCancel(t)){prompts.cancel("Operation cancelled.");return}}p().start("Creating configuration...");let i={name:o,apiKey:t||void 0,environment:"development",agents:[{name:"support-bot",description:"A helpful customer support assistant",config:{model:"llama-3-8b",system_prompt:"You are a helpful customer support assistant.",temperature:.7}}]};B__default.default.writeFileSync(ae__default.default.join(e,"langtrain.config.json"),JSON.stringify(i,null,2)),_("Project initialized successfully!"),console.log(x.dim(`
|
|
17
|
+
Next steps:`)),console.log(` 1. Run ${x.cyan("lt deploy")} to push your agent to the cloud.`),console.log(` 2. Run ${x.cyan("lt dev")} to start the local development loop.`),K("Happy coding!");}async function Te(){v("Running Langtrain Doctor...");let e=p(),o=0;e.start("Checking Node.js environment...");let a=process.version,t=_e__default.default.platform(),n=_e__default.default.arch();parseInt(a.replace("v","").split(".")[0])<18?(e.stop(x.red(`Node.js version ${a} is outdated. Please upgrade to v18+.`)),o++):e.stop(`Node.js ${a} (${t} ${n})`),e.start("Checking configuration...");let i=f();if(!i.apiKey)e.stop(x.yellow("API Key is missing. Run `langtrain login` or set LANGTRAIN_API_KEY.")),o++;else {e.stop("Configuration found."),e.start("Checking API connectivity...");try{let s=await J(i.apiKey);e.stop(`Connected to Langtrain Cloud (Plan: ${x.green(s?.plan||"unknown")})`);}catch(s){e.stop(x.red(`Failed to connect to Langtrain Cloud: ${s.message}`)),o++;}}console.log(""),o===0?_("Your Langtrain environment is healthy! Ready to build."):be(`Found ${o} issue(s). Please resolve them for the best experience.`),K("Doctor check complete.");}async function ie(e){let a=f().workspace_id,t=await prompts.text({message:"Path to file:",placeholder:"./dataset.jsonl",validate(s){if(!s)return "Required";if(!B__default.default.existsSync(s))return "File not found"}});if(prompts.isCancel(t))return;let n=await prompts.select({message:"File Purpose:",options:[{value:"fine-tune",label:"Fine-tuning (JSONL)"},{value:"vision-tune",label:"Vision Tuning (Image/Zip)"},{value:"agent-knowledge",label:"Agent Knowledge"}]});if(prompts.isCancel(n))return;let i=p();i.start("Uploading file...");try{let s=await e.upload(t,a,n);i.stop(colors.green("File uploaded successfully!")),console.log(colors.gray(`ID: ${s.id}`)),console.log(colors.gray(`Name: ${s.filename}`)),console.log(colors.gray(`Bytes: ${s.bytes}`));}catch(s){i.stop(colors.red(`Upload failed: ${s.message}`));}}async function se(e,o){let a=f(),t=new chunkK5LXUJ4G_js.m({apiKey:a.apiKey||"",baseUrl:a.baseUrl});if(!o){let r=p();r.start("Fetching files...");try{let c=a.workspace_id||"",l=await e.list(c);if(r.stop(`Found ${l.length} files`),l.length===0){console.log(colors.yellow("No files found. Upload one first."));return}let w=await prompts.select({message:"Select file to refine:",options:l.map(k=>({value:k.id,label:`${k.filename} (${We(k.bytes)})`}))});if(prompts.isCancel(w))return;o=w;}catch(c){r.stop(colors.red(`Failed to fetch files: ${c.message}`));return}}let n=p();n.start("Fetching guardrails...");let i="";try{let r=await t.list();if(n.stop(`Found ${r.length} guardrails`),r.length===0){console.log(colors.yellow('No guardrails found. Please create one first using "lt guardrails create".'));return}let c=await prompts.select({message:"Select a Guardrail to apply:",options:r.map(l=>({value:l.id,label:l.name,hint:l.description}))});if(prompts.isCancel(c))return;i=c;}catch(r){n.stop(colors.red(`Failed to fetch guardrails: ${r.message}`));return}let s=p();s.start("Applying guardrail (filtering dataset)...");try{let r=await t.apply(o,i);s.stop(colors.green("Dataset refined successfully!")),console.log(colors.gray("Stats:")),console.log(`Original Rows: ${r.original_rows}`),console.log(`Filtered Rows: ${r.filtered_rows}`),console.log(colors.red(`Removed: ${r.removed_rows} rows`)),console.log(colors.green(`New Dataset ID: ${r.new_dataset_id}`));}catch(r){s.stop(colors.red(`Failed to refine dataset: ${r.message}`));}}function We(e,o=2){if(!+e)return "0 Bytes";let a=1024,t=o<0?0:o,n=["Bytes","KB","MB","GB","TB"],i=Math.floor(Math.log(e)/Math.log(a));return `${parseFloat((e/Math.pow(a,i)).toFixed(t))} ${n[i]}`}async function j(e){v("Deploying configuration to Langtrain Cloud...");let o=f(),a=o.agents||[];if(a.length===0){v(colors.yellow("No agents found in langtrain.config.json"));return}for(let t of a){let n=p();n.start(`Deploying agent: ${t.name}...`);try{let i=await e.list(),s=i.find(r=>r.name===t.name);if(s)n.stop(colors.yellow(`Agent ${t.name} already exists (ID: ${s.id}). Skipping update (not supported yet).`));else {let r={workspace_id:o.workspace_id||i[0]?.workspace_id||"",name:t.name,description:t.description,config:t.config};if(!r.workspace_id){n.stop(colors.red(`Failed: Workspace ID missing in config for ${t.name}`));continue}await e.create(r),n.stop(colors.green(`Agent ${t.name} deployed successfully!`));}}catch(i){n.stop(colors.red(`Failed to deploy ${t.name}: ${i.message}`));}}_("Deployment complete.");}async function re(e){v("Starting Langtrain Development Server...");let o=ae__default.default.join(process.cwd(),"langtrain.config.json");if(!B__default.default.existsSync(o)){v(colors.red('langtrain.config.json not found. Run "lt init" first.'));return}console.log(colors.gray(`Watching ${o} for changes...`));let a=false;await j(e),B__default.default.watch(o,async t=>{if(t==="change"&&!a){a=true,console.log(colors.yellow("Configuration changed. Redeploying...")),await new Promise(n=>setTimeout(n,500));try{await j(e);}catch(n){console.error(colors.red(`Deploy failed: ${n.message}`));}finally{a=false,console.log(colors.gray(`Watching ${o}...`));}}}),await new Promise(()=>{});}async function le(e){let o=f(),a=new chunkK5LXUJ4G_js.m({apiKey:o.apiKey||"",baseUrl:o.baseUrl}),t=p();t.start("Fetching guardrails...");try{let n=await a.list();if(t.stop(`Found ${n.length} guardrails`),n.length===0){console.log(colors.yellow('No guardrails found. Create one with "lt guardrails create".'));return}n.forEach(i=>{console.log(colors.green(`\u2022 ${i.name}`)+colors.gray(` (ID: ${i.id})`)),i.description&&console.log(colors.gray(` ${i.description}`)),console.log(colors.gray(` Config: PII=${i.config.pii_enabled}, MinLen=${i.config.min_length}`)),console.log("");});}catch(n){t.stop(colors.red(`Failed to list guardrails: ${n.message}`));}}async function ce(e){let o=f(),a=new chunkK5LXUJ4G_js.m({apiKey:o.apiKey||"",baseUrl:o.baseUrl});v("Create a new Data Guardrail");let t=await prompts.text({message:"Guardrail Name:",placeholder:"e.g. Strict Safety Policy",validate(l){if(!l)return "Name is required"}});if(prompts.isCancel(t))return;let n=await prompts.text({message:"Description (optional):",placeholder:"Filters PII and short text"});if(prompts.isCancel(n))return;let i=await prompts.text({message:"Minimum Text Length (0 for no limit):",initialValue:"0",validate(l){if(isNaN(Number(l)))return "Must be a number"}});if(prompts.isCancel(i))return;let s=await prompts.confirm({message:"Enable PII Filtering (Email/Phone)?",initialValue:false});if(prompts.isCancel(s))return;let r=await prompts.text({message:"Regex Patterns to Block (comma separated, optional):",placeholder:"e.g. bad_word, another_one"});if(prompts.isCancel(r))return;let c=p();c.start("Creating guardrail...");try{let l=r.split(",").map(S=>S.trim()).filter(S=>S.length>0),w={name:t,description:n,config:{min_length:Number(i),pii_enabled:s,regex_patterns:l,profanity_enabled:!1}},k=await a.create(w);c.stop(colors.green(`Guardrail "${k.name}" created successfully!`)),console.log(colors.gray(`ID: ${k.id}`));}catch(l){c.stop(colors.red(`Failed to create guardrail: ${l.message}`));}}async function He(e){let o=p();o.start("Fetching secrets...");let a=f();try{let t=await e.list(a.workspace_id);if(o.stop(`Found ${t.length} secrets`),t.length===0){console.log(colors.gray('No secrets found. Use "lt env set" to add one.'));return}console.log(colors.gray("------------------------------------------------")),t.forEach(n=>{console.log(`${n.key.padEnd(30)} ${colors.gray("******")}`);}),console.log(colors.gray("------------------------------------------------"));}catch(t){o.stop(colors.red(`Failed to list secrets: ${t.message}`));}}async function Ze(e,o){let a="",t="";if(a=await prompts.text({message:"Secret Key:",placeholder:"OPENAI_API_KEY"}),prompts.isCancel(a)||(t=await prompts.text({message:"Secret Value:",placeholder:"sk-..."}),prompts.isCancel(t)))return;let n=p();n.start(`Setting ${a}...`);let i=f();try{await e.set(a,t,i.workspace_id),n.stop(colors.green(`Secret ${a} set successfully.`));}catch(s){n.stop(colors.red(`Failed to set secret: ${s.message}`));}}async function ge(e){let o=await prompts.select({message:"Manage Secrets",options:[{value:"list",label:"List Secrets"},{value:"set",label:"Set Secret"},{value:"remove",label:"Remove Secret"},{value:"back",label:"Back"}]});if(!(prompts.isCancel(o)||o==="back")&&(o==="list"&&await He(e),o==="set"&&await Ze(e),o==="remove")){let a=await prompts.text({message:"Key to remove:"});if(!prompts.isCancel(a)){let t=p();t.start("Removing...");try{let n=f();await e.delete(a,n.workspace_id),t.stop(colors.green("Removed."));}catch(n){t.stop(colors.red(`Failed: ${n.message}`));}}}}async function ue(e,o){let a=p(),t="";if(o){a.start("Finding agent...");try{let s=(await e.list()).find(r=>r.name===o||r.id===o);if(s)t=s.id;else {a.stop(colors.red(`Agent "${o}" not found.`));return}a.stop(colors.green(`Found agent: ${s.name}`));}catch(i){a.stop(colors.red(`Failed to list agents: ${i.message}`));return}}else {a.start("Fetching agents...");try{let i=await e.list();if(a.stop(`Found ${i.length} agents`),i.length===0){console.log(colors.yellow("No agents found."));return}let s=await prompts.select({message:"Select agent to view logs:",options:i.map(r=>({value:r.id,label:r.name}))});if(prompts.isCancel(s))return;t=s;}catch(i){a.stop(colors.red(`Failed to list agents: ${i.message}`));return}}let n=p();n.start("Fetching logs...");try{let i=await e.logs(t);n.stop("Logs fetched."),console.log(colors.gray("------------------------------------------------")),console.log(`${colors.bgMagenta(colors.black(" Recent Logs "))}`),i.logs&&i.logs.length>0?i.logs.forEach(s=>console.log(s)):console.log(colors.gray("(No logs found)")),console.log(colors.gray("------------------------------------------------"));}catch(i){n.stop(colors.red(`Failed to fetch logs: ${i.message}`));}}var Qe=Date.now(),T=0,Ue=0;async function pe(){let e=f(),o=e.apiKey;if(console.log(""),console.log(colors.bold(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(colors.bold(" \u2551 TOKEN USAGE \u2551")),console.log(colors.bold(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),!o){console.log(colors.yellow(` Login required to view token usage.
|
|
18
|
+
`));return}let a=p();a.start("Fetching token usage...");try{let t=chunkK5LXUJ4G_js.a("axios"),n=e.baseUrl||"https://api.langtrain.xyz",s=(await t.get(`${n}/v1/usage/tokens`,{headers:{Authorization:`Bearer ${o}`}})).data;a.stop(colors.green("Token usage retrieved")),console.log("");let r=s.tokens_used||0,c=s.token_limit||1e4,l=Math.round(r/c*100),w=Math.max(0,c-r),k=30,S=Math.round(l/100*k),M="\u2588".repeat(S)+"\u2591".repeat(k-S),O=l>90?"\x1B[31m":l>70?"\x1B[33m":"\x1B[32m";console.log(` ${colors.dim("Period:")} ${s.period||"Current Month"}`),console.log(` ${colors.dim("Used:")} ${r.toLocaleString()} tokens`),console.log(` ${colors.dim("Limit:")} ${c.toLocaleString()} tokens`),console.log(` ${colors.dim("Remaining:")} ${w.toLocaleString()} tokens`),console.log(` ${colors.dim("Usage:")} ${O}${M}\x1B[0m ${l}%`),console.log(""),s.breakdown&&(console.log(colors.dim(" \u2500\u2500 Breakdown \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(` ${colors.dim("Training:")} ${(s.breakdown.training||0).toLocaleString()}`),console.log(` ${colors.dim("Inference:")} ${(s.breakdown.inference||0).toLocaleString()}`),console.log(` ${colors.dim("Agents:")} ${(s.breakdown.agents||0).toLocaleString()}`),console.log(""));}catch{a.stop(""),console.log(colors.dim(" Token data not available from server.")),console.log(colors.dim(` Showing session estimates:
|
|
19
|
+
`)),console.log(` ${colors.dim("Session calls:")} ${T}`),console.log(` ${colors.dim("Est. tokens:")} ~${T*150}`),console.log("");}}async function Ne(){let e=Date.now()-Qe,o=Math.round(e/1e3),a=Math.floor(o/60),t=a>0?`${a}m ${o%60}s`:`${o}s`,n=0,i=0;console.log(""),console.log(colors.bold(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(colors.bold(" \u2551 SESSION TELEMETRY \u2551")),console.log(colors.bold(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(` ${colors.dim("Session:")} ${t}`),console.log(` ${colors.dim("API calls:")} ${T}`),console.log(` ${colors.dim("Avg latency:")} ${n}ms`),console.log(` ${colors.dim("Errors:")} ${Ue} (${i}%)`),console.log(""),console.log(colors.dim(" \u2500\u2500 Environment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(` ${colors.dim("Node:")} ${process.version}`),console.log(` ${colors.dim("Platform:")} ${process.platform} ${process.arch}`),console.log(` ${colors.dim("Memory:")} ${Math.round(process.memoryUsage().heapUsed/1024/1024)}MB heap`),console.log(` ${colors.dim("Config:")} ~/.langtrain/config.json`),console.log("");let s=f();if(s.apiKey){let r=p();r.start("Pinging API...");try{let c=chunkK5LXUJ4G_js.a("axios"),l=s.baseUrl||"https://api.langtrain.xyz",w=Date.now();await c.get(`${l}/health`,{timeout:5e3});let k=Date.now()-w;r.stop(colors.green(`API healthy (${k}ms)`));}catch{r.stop(colors.yellow("API unreachable"));}}console.log("");}var je={version:"0.2.1"};function Oe(e){let{dim:o,green:a,yellow:t,cyan:n,bold:i,gray:s}=x,r=e?.plan==="pro"?i(a("PRO")):e?.plan==="enterprise"?i(a("ENTERPRISE")):o("FREE"),c=e?.usage?.tokensUsedThisMonth||0,l=e?.usage?.tokenLimit||1e4,w=Math.round(c/l*100),k=w>80?t(`${w}%`):a(`${w}%`);console.log(o(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(` ${o("Plan:")} ${r} ${o("\u2502")} ${o("Tokens:")} ${c.toLocaleString()}/${l.toLocaleString()} ${k}`),console.log(o(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
20
|
+
`));}function Ve(e,o){return {vision:new chunkK5LXUJ4G_js.q({apiKey:e}),tune:new chunkK5LXUJ4G_js.r({apiKey:e}),agent:new chunkK5LXUJ4G_js.d({apiKey:e,baseUrl:o}),model:new chunkK5LXUJ4G_js.i({apiKey:e,baseUrl:o}),train:new chunkK5LXUJ4G_js.g({apiKey:e,baseUrl:o}),secret:new chunkK5LXUJ4G_js.k({apiKey:e,baseUrl:o})}}function nt(e){switch(e){case "main":return "What would you like to do?";case "agents":return "Agents:";case "text":return "Langtune (Text):";case "vision":return "Langvision (Vision):";case "guard":return "Guardrails:";case "settings":return "Settings:";default:return "Select an option:"}}async function at(){let e=new commander.Command,o=je.version;e.name("langtrain").description("Langtrain CLI \u2014 Fine-tuning, Agents, and AI Ops").version(o),e.command("init").description("Initialize a new Langtrain project").action(oe),e.command("deploy").description("Deploy configuration to Langtrain Cloud").action(async()=>{let n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.d({apiKey:i,baseUrl:n.baseUrl});await j(s);}),e.command("dev").description("Start local development server").action(async()=>{let n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.d({apiKey:i,baseUrl:n.baseUrl});await re(s);}),e.command("env").description("Manage secrets and environment variables").action(async()=>{let n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.k({apiKey:i,baseUrl:n.baseUrl});await ge(s);}),e.command("logs [agent]").description("Stream logs from a deployed agent").action(async n=>{let i=f(),s=i.apiKey||"",r=new chunkK5LXUJ4G_js.d({apiKey:s,baseUrl:i.baseUrl});await ue(r,n);}),e.command("login").description("Authenticate with your API key").action(async()=>{await N();}),e.command("logout").description("Clear stored credentials").action(async()=>{await ne();}),e.command("tokens").description("View token usage for current period").action(pe);let a=e.command("data").description("Manage datasets");a.command("upload [file]").description("Upload a dataset").action(async()=>{let n=f(),i=new chunkK5LXUJ4G_js.f({apiKey:n.apiKey||"",baseUrl:n.baseUrl});await ie(i);}),a.command("refine [fileId]").description("Refine a dataset using guardrails").action(async n=>{let i=f(),s=new chunkK5LXUJ4G_js.f({apiKey:i.apiKey||"",baseUrl:i.baseUrl});await se(s,n);});let t=e.command("guardrails").description("Manage data guardrails");t.command("list").description("List available guardrails").action(async()=>await le()),t.command("create").description("Create a new guardrail").action(async()=>await ce()),e.action(async()=>{W(o),process.argv.includes("--first-run")&&(process.stdin.isTTY?(v("Welcome to Langtrain! Let's get you set up."),await N()):(console.log('Langtrain installed! Run "npx langtrain login" to authenticate.'),process.exit(0)));let i=f(),s=i.apiKey||"",r=te(),c=null;if(r&&s){try{c=await J(s);}catch{}Oe(c);}else console.log(x.dim(` Not logged in. Only basic options available.
|
|
21
21
|
`));let l=r?Ve(s,i.baseUrl):null,w="main";for(;;){let k=await prompts.select({message:nt(w),options:Ce(w,c,r)});if(prompts.isCancel(k))if(w==="main")K("Goodbye!"),process.exit(0);else {w="main";continue}let S=k;if(S==="exit"&&(K("Goodbye!"),process.exit(0)),S==="back"){w="main";continue}if(S.startsWith("nav-")){w=S.replace("nav-","");continue}try{switch(S){case "login":if(await N(),i=f(),s=i.apiKey||"",r=te(),r){try{c=await J(s);}catch{}l=Ve(s,i.baseUrl),console.clear(),W(o),Oe(c);}break;case "logout":await ne(),s="",r=!1,c=null,l=null,console.clear(),W(o),console.log(x.dim(` Logged out. Only basic options available.
|
|
22
22
|
`));break;case "docs":console.log(x.cyan(`
|
|
23
23
|
\u{1F4D6} https://docs.langtrain.ai
|
|
24
|
-
`));break;case "status":await ke();break;case "tokens":await pe();break;case "telemetry":await Ne();break;case "doctor":await Te();break;case "init":await oe();break;case "deploy":l&&await j(l.agent);break;case "dev":l&&await re(l.agent);break;case "env":l&&await ge(l.secret);break;case "logs":l&&await ue(l.agent);break;case "tune-finetune":l&&await Se(l.tune,l.model);break;case "tune-list":l&&await Le(l.train);break;case "tune-generate":l&&await xe(l.tune);break;case "vision-finetune":l&&await Fe(l.vision,l.model);break;case "vision-generate":l&&await Ie(l.vision);break;case "agent-list":l&&await Pe(l.agent);break;case "agent-create":l&&await De(l.agent,l.model);break;case "agent-delete":l&&await Ee(l.agent);break;case "data-upload":s&&await ie(new
|
|
24
|
+
`));break;case "status":await ke();break;case "tokens":await pe();break;case "telemetry":await Ne();break;case "doctor":await Te();break;case "init":await oe();break;case "deploy":l&&await j(l.agent);break;case "dev":l&&await re(l.agent);break;case "env":l&&await ge(l.secret);break;case "logs":l&&await ue(l.agent);break;case "tune-finetune":l&&await Se(l.tune,l.model);break;case "tune-list":l&&await Le(l.train);break;case "tune-generate":l&&await xe(l.tune);break;case "vision-finetune":l&&await Fe(l.vision,l.model);break;case "vision-generate":l&&await Ie(l.vision);break;case "agent-list":l&&await Pe(l.agent);break;case "agent-create":l&&await De(l.agent,l.model);break;case "agent-delete":l&&await Ee(l.agent);break;case "data-upload":s&&await ie(new chunkK5LXUJ4G_js.f({apiKey:s}));break;case "data-refine":s&&await se(new chunkK5LXUJ4G_js.f({apiKey:s}));break;case "guard-list":await le(null);break;case "guard-create":await ce(null);break}}catch(M){K(x.red(`Error: ${M.message}`));}}}),at().catch(console.error);}exports.main=at;//# sourceMappingURL=cli.js.map
|
|
25
25
|
//# sourceMappingURL=cli.js.map
|