File size: 1,621 Bytes
68d7816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { z } from 'zod';

import {
  type ConfigSchema,
  type EnvBindings,
  envBindings,
  stripEnvBoundFields,
} from '#/app/config/config';
import { registerConfigSection } from '#/app/config/configSectionContributions';
import type { TokenCountingStrategy } from './tokenCounting';

export const TOKEN_COUNTING_SECTION = 'tokenCounting';

export const TOKEN_COUNTING_STRATEGY_ENV = 'KIMI_TOKEN_COUNTING_STRATEGY';

export const TOKEN_COUNTING_STRATEGIES = ['measured+estimated', 'measured', 'estimated'] as const;

export const TokenCountingConfigSchema: ConfigSchema<TokenCountingConfig> = z.object({
  strategy: z.enum(TOKEN_COUNTING_STRATEGIES),
});

export type TokenCountingConfig = {
  readonly strategy: TokenCountingStrategy;
};

function parseStrategy(raw: string): TokenCountingStrategy | undefined {
  const value = raw.trim().toLowerCase();
  return (TOKEN_COUNTING_STRATEGIES as readonly string[]).includes(value)
    ? (value as TokenCountingStrategy)
    : undefined;
}

export const tokenCountingEnvBindings: EnvBindings<TokenCountingConfig> =
  envBindings<TokenCountingConfig>(TokenCountingConfigSchema, {
    strategy: { env: TOKEN_COUNTING_STRATEGY_ENV, parse: parseStrategy },
  });

export const stripTokenCountingEnv = stripEnvBoundFields<TokenCountingConfig>(
  tokenCountingEnvBindings,
);

export const DEFAULT_TOKEN_COUNTING_CONFIG: TokenCountingConfig = {
  strategy: 'measured+estimated',
};

registerConfigSection(TOKEN_COUNTING_SECTION, TokenCountingConfigSchema, {
  defaultValue: DEFAULT_TOKEN_COUNTING_CONFIG,
  env: tokenCountingEnvBindings,
  stripEnv: stripTokenCountingEnv,
});