Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 9x 9x 26x 26x 26x 26x 26x 26x 26x 26x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 26x 26x 26x 26x 26x 14x 14x 14x 11x 11x 11x 14x 14x 14x 14x 26x 26x 26x 26x 26x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 26x 26x 26x 26x 26x 26x 26x 26x 26x 4x 4x 4x 4x 4x 26x 26x 26x 26x 26x 26x 26x 26x 2x 2x 26x 26x 26x 26x 26x 26x 26x 26x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 2x 2x 2x 2x 2x 2x 18x 18x 18x 18x 18x 18x 18x 18x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 26x 26x 26x 26x 26x 26x 26x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 26x 26x 26x 26x 26x 27x 27x 26x | /**
* RelayPlane Main Class
*
* The main entry point for the agent optimization layer.
*
* @packageDocumentation
*/
import { Store, getDefaultDbPath } from './storage/index.js';
import { RoutingEngine } from './routing/index.js';
import { OutcomeRecorder } from './learning/outcomes.js';
import { PatternDetector } from './learning/patterns.js';
import type {
RelayPlaneConfig,
RunInput,
RunResult,
OutcomeInput,
Outcome,
Stats,
Suggestion,
TaskType,
Provider,
ProviderConfig,
} from './types.js';
// Type-only import for adapters to avoid runtime dependency if not used
type ModelAdapter = {
execute(args: {
model: string;
input: any;
apiKey: string;
baseUrl?: string;
}): Promise<{
success: boolean;
output?: any;
error?: { message: string };
durationMs: number;
tokensIn?: number;
tokensOut?: number;
}>;
};
/**
* RelayPlane - Agent Optimization Layer
*
* Provides intelligent routing, outcome tracking, and learning for AI model selection.
*
* @example Basic usage
* ```typescript
* import { RelayPlane } from '@relayplane/core';
*
* const relay = new RelayPlane();
*
* // Run a task - automatically infers type and routes to best model
* const result = await relay.run({
* prompt: 'Review this code for bugs...',
* });
*
* // Record the outcome for learning
* await relay.recordOutcome(result.runId, { success: true, quality: 'good' });
*
* // Get suggestions for routing improvements
* const suggestions = await relay.getSuggestions();
* ```
*/
export class RelayPlane {
private store: Store;
private _routing: RoutingEngine;
private outcomeRecorder: OutcomeRecorder;
private patternDetector: PatternDetector;
private config: RelayPlaneConfig;
private adapterRegistry: any | null = null;
/**
* Creates a new RelayPlane instance.
*
* @param config - Configuration options
*/
constructor(config: RelayPlaneConfig = {}) {
this.config = {
dbPath: config.dbPath ?? getDefaultDbPath(),
defaultProvider: config.defaultProvider ?? 'local',
defaultModel: config.defaultModel ?? 'llama3.2',
providers: config.providers ?? {},
};
// Initialize storage
this.store = new Store(this.config.dbPath);
// Initialize components
this._routing = new RoutingEngine(this.store);
this.outcomeRecorder = new OutcomeRecorder(this.store);
this.patternDetector = new PatternDetector(this.store);
}
/**
* Gets the routing engine for direct access.
*/
get routing(): RoutingEngine {
return this._routing;
}
/**
* Runs a prompt through the appropriate model.
*
* @param input - The run input
* @returns The run result
*/
async run(input: RunInput): Promise<RunResult> {
const startTime = Date.now();
// Resolve routing
const resolved = this._routing.resolve(input.prompt, input.taskType, input.model);
// Get the adapter
const adapter = await this.getAdapter(resolved.provider as Provider);
if (!adapter) {
// No adapter available - record and return error
const runId = this.store.recordRun({
prompt: input.prompt,
systemPrompt: input.systemPrompt ?? null,
taskType: resolved.taskType,
model: resolved.model,
success: false,
output: null,
error: `No adapter configured for provider: ${resolved.provider}`,
durationMs: Date.now() - startTime,
tokensIn: null,
tokensOut: null,
metadata: input.metadata ? JSON.stringify(input.metadata) : null,
});
return {
runId,
success: false,
error: `No adapter configured for provider: ${resolved.provider}`,
taskType: resolved.taskType,
model: resolved.model,
durationMs: Date.now() - startTime,
timestamp: new Date().toISOString(),
};
}
// Get API key for the provider
const providerConfig = this.config.providers?.[resolved.provider as Provider];
const apiKey = providerConfig?.apiKey ?? this.getEnvApiKey(resolved.provider as Provider);
// Build the full prompt
const fullInput = input.systemPrompt
? `${input.systemPrompt}\n\n${input.prompt}`
: input.prompt;
// Execute the adapter
const result = await adapter.execute({
model: resolved.modelName,
input: fullInput,
apiKey: apiKey ?? '',
baseUrl: providerConfig?.baseUrl,
});
const durationMs = Date.now() - startTime;
// Record the run
const runId = this.store.recordRun({
prompt: input.prompt,
systemPrompt: input.systemPrompt ?? null,
taskType: resolved.taskType,
model: resolved.model,
success: result.success,
output: result.output ?? null,
error: result.error?.message ?? null,
durationMs,
tokensIn: result.tokensIn ?? null,
tokensOut: result.tokensOut ?? null,
metadata: input.metadata ? JSON.stringify(input.metadata) : null,
});
return {
runId,
success: result.success,
output: result.output,
error: result.error?.message,
taskType: resolved.taskType,
model: resolved.model,
durationMs,
tokensIn: result.tokensIn,
tokensOut: result.tokensOut,
timestamp: new Date().toISOString(),
};
}
/**
* Gets an adapter for a provider.
*/
private async getAdapter(provider: Provider): Promise<ModelAdapter | null> {
try {
// Lazy load the adapter registry
if (!this.adapterRegistry) {
const adapters = await import('@relayplane/adapters');
this.adapterRegistry = adapters.defaultAdapterRegistry;
}
return await this.adapterRegistry.get(provider);
} catch {
// Adapter not available
return null;
}
}
/**
* Gets an API key from environment variables.
*/
private getEnvApiKey(provider: Provider): string | undefined {
const envVars: Record<Provider, string> = {
openai: 'OPENAI_API_KEY',
anthropic: 'ANTHROPIC_API_KEY',
google: 'GOOGLE_API_KEY',
xai: 'XAI_API_KEY',
local: '',
};
const envVar = envVars[provider];
return envVar ? process.env[envVar] : undefined;
}
/**
* Records an outcome for a run.
*
* @param runId - The run ID
* @param outcome - The outcome details
* @returns The recorded outcome
*/
recordOutcome(runId: string, outcome: Omit<OutcomeInput, 'runId'>): Outcome {
return this.outcomeRecorder.record({
runId,
...outcome,
});
}
/**
* Gets an outcome for a run.
*
* @param runId - The run ID
* @returns The outcome, or null if not found
*/
getOutcome(runId: string): Outcome | null {
return this.outcomeRecorder.get(runId);
}
/**
* Gets statistics for runs.
*
* @param options - Optional filters
* @returns Statistics object
*/
stats(options?: { from?: string; to?: string }): Stats {
const raw = this.store.getStats(options);
// Build stats by task type
const byTaskType: Stats['byTaskType'] = {} as Stats['byTaskType'];
const taskTypes: TaskType[] = [
'code_generation',
'code_review',
'summarization',
'analysis',
'creative_writing',
'data_extraction',
'translation',
'question_answering',
'general',
];
for (const taskType of taskTypes) {
const taskStats = raw.byTaskType[taskType];
byTaskType[taskType] = {
taskType,
totalRuns: taskStats?.runs ?? 0,
successfulRuns: Math.round((taskStats?.runs ?? 0) * (taskStats?.successRate ?? 0)),
successRate: taskStats?.successRate ?? 0,
avgDurationMs: taskStats?.avgDurationMs ?? 0,
byModel: {},
};
}
// Add model breakdown
for (const [model, modelStats] of Object.entries(raw.byModel)) {
// Find which task type this model belongs to (simplified - assumes model is used for one task type)
// In a real implementation, we'd query runs grouped by task type AND model
for (const taskType of taskTypes) {
if (!byTaskType[taskType].byModel[model]) {
byTaskType[taskType].byModel[model] = {
runs: 0,
successRate: 0,
avgDurationMs: 0,
};
}
}
}
return {
totalRuns: raw.totalRuns,
overallSuccessRate: raw.totalRuns > 0 ? raw.successfulRuns / raw.totalRuns : 0,
byTaskType,
period: {
from: options?.from ?? '',
to: options?.to ?? new Date().toISOString(),
},
};
}
/**
* Gets routing improvement suggestions.
*
* @returns Array of suggestions
*/
getSuggestions(): Suggestion[] {
// Get pending suggestions from the database
const pending = this.store.getPendingSuggestions();
return pending.map((record) => ({
id: record.id,
taskType: record.taskType,
currentModel: record.currentModel,
suggestedModel: record.suggestedModel,
reason: record.reason,
confidence: record.confidence,
expectedImprovement: JSON.parse(record.expectedImprovement),
sampleCount: record.sampleCount,
createdAt: record.createdAt,
accepted: record.accepted ?? undefined,
acceptedAt: record.acceptedAt ?? undefined,
}));
}
/**
* Generates new suggestions based on current data.
*
* @returns Array of newly generated suggestions
*/
generateSuggestions(): Suggestion[] {
return this.patternDetector.generateSuggestions();
}
/**
* Accepts a suggestion and updates routing.
*
* @param suggestionId - The suggestion ID to accept
* @returns True if successful
*/
acceptSuggestion(suggestionId: string): boolean {
return this.store.acceptSuggestion(suggestionId);
}
/**
* Rejects a suggestion.
*
* @param suggestionId - The suggestion ID to reject
* @returns True if successful
*/
rejectSuggestion(suggestionId: string): boolean {
return this.store.rejectSuggestion(suggestionId);
}
/**
* Closes the RelayPlane instance and releases resources.
*/
close(): void {
this.store.close();
}
}
|