@cogitator-ai/config

中文文档
0.36.5发布于 2026/10/29MITTypeScriptES Module近 30 天下载 1万

Cogitator (YAML, env) 的配置加载

中文使用文档
文档目录33 节
  1. 安装
  2. 快速启动
  3. YAML 配置
  4. 装入配置
  5. 配置参考
  6. LLM 配置
  7. 内存配置
  8. 沙盒配置
  9. 反射配置
  10. 护栏配置
  11. 成本运行配置
  12. 安全配置
  13. 背景配置
  14. 部署配置
  15. 限制配置
  16. 触发配置( 实验)
  17. 日志配置
  18. 环境变量
  19. ${VAR} YAML 参考文献
  20. 优先权顺序
  21. Schema 验证
  22. 可用的外观
  23. 实例
  24. 开发配置
  25. 生产配置
  26. API 参考
  27. 加载Config( 选项)
  28. 定义 Config( 配置)
  29. 装入 YamlConfig( 路径 )
  30. 装入 EnvConfig ()
  31. interpolateEnv( 值, env?) / interpolateEnvString( 值, env?)
  32. parseDotenv( 内容) / 加载DotenvFile( 路径)
  33. 许可证

@cogitator-ai/ 配置

Cogitator 的配置加载 。 支持YAML文件,环境变量,以及全Zod验证的程序覆盖.

安装

pnpm add @cogitator-ai/config

另见 配置 在网站上.

快速启动

YAML 配置

创建 cogitator.yml 在您的项目根中。 没有明确的 configPath, (中文(简体) ), loadConfig() 在当前目录中查看 cogitator.yaml, (中文(简体) ), cogitator.yml, (中文(简体) ), .cogitator.yaml 财务报告和审定财务报表 .cogitator.yml,顺序为:

llm:
  defaultProvider: openai
  defaultModel: gpt-6.1-sol
  providers:
    openai:
      apiKey: sk-xxx
    ollama:
      baseUrl: http://localhost:11434
      headers: # optional, sent with every chat request
        X-Gateway-Key: xxx

memory:
  adapter: redis
  redis:
    url: redis://localhost:6379

logging:
  level: info
  format: pretty

装入配置

import { loadConfig, defineConfig } from '@cogitator-ai/config';

// Load from file with env vars and overrides
const config = loadConfig({
  configPath: './cogitator.yml',
  overrides: {
    logging: { level: 'debug' },
  },
});

// The same config as another environment sees it, such as a deployed app's
const deployed = loadConfig({
  configPath: './cogitator.yml',
  env: { COGITATOR_LLM_DEFAULT_MODEL: 'ollama/llama3.2', OLLAMA_HOST: 'ollama' },
});

// Or define config programmatically with type safety
const programmatic = defineConfig({
  llm: {
    defaultProvider: 'openai',
    providers: {
      openai: { apiKey: process.env.OPENAI_API_KEY! },
    },
  },
});

既验证结果又抛出 Invalid configuration: … 与每个 与计划不符的Zod问题 结果是 CogitatorConfig准备运行时间 具有函数或对象的选项( 存储、 回调例如 security.pii.onDetect 或者说 memory.compaction.beforeCompact, (中文(简体) ), llm.backends, (中文(简体) ), prompts.versions 编号 : prompts.abTests 编号 : prompts.score, (中文(简体) ), runCheckpoints)不能来自YAML,在代码中添加:

import { Cogitator } from '@cogitator-ai/core';
import { loadConfig } from '@cogitator-ai/config';

const config = loadConfig();
const cog = new Cogitator({
  ...config,
  prompts: { ...config.prompts, score: (result) => (result.output.length > 0 ? 1 : 0) },
});

prompts.autoDeployWinner 可以来自YAML(prompts: { autoDeployWinner: true }) (中文(简体) ).


配置参考

LLM 配置

llm:
  defaultProvider: openai # ollama | openai | anthropic | google | azure | bedrock | vllm | mistral | groq | together | deepseek | openrouter
  defaultModel: gpt-6.1-sol
  providers:
    ollama:
      baseUrl: http://localhost:11434
      headers: # optional, sent with every chat request
        X-Gateway-Key: xxx
    openai:
      apiKey: sk-xxx
      baseUrl: https://api.openai.com/v1 # optional, for proxies
      api: responses # optional: responses (default for api.openai.com) | chat-completions
      profile: lmstudio # optional: what the server at baseUrl takes, a preset or { server, maxTokensField, streamUsage, reasoningEffort }
      headers: # optional, sent with every request
        X-Gateway-Key: xxx
    anthropic:
      apiKey: sk-ant-xxx
      baseUrl: https://gateway.example.com/anthropic # optional, default https://api.anthropic.com
      headers: # optional
        X-Team: search
    google:
      apiKey: xxx
      baseUrl: https://gateway.example.com/gemini/v1beta # optional, with the API version
    azure:
      apiKey: xxx
      endpoint: https://xxx.openai.azure.com
      apiVersion: 2025-04-01-preview # optional, the default
      deployment: gpt-6.1-sol # optional
      model: gpt-5 # optional: the model the deployments serve, when their names do not say
    bedrock:
      region: us-east-1 # optional, can use AWS config chain
      accessKeyId: xxx # optional, uses AWS credentials chain
      secretAccessKey: xxx # optional
      endpoint: https://vpce-0abc.bedrock-runtime.us-east-1.vpce.amazonaws.com # optional: a VPC endpoint or a proxy
    vllm:
      baseUrl: http://localhost:8000
      profile: vllm # optional, the default
    mistral:
      apiKey: xxx
    groq:
      apiKey: xxx
    together:
      apiKey: xxx
    deepseek:
      apiKey: xxx
    openrouter: # chat models of every provider, and decision models through cog.decide()
      apiKey: xxx
      headers: # optional, e.g. HTTP-Referer and X-Title app attribution
        X-Title: My App
  pricing: # prices of your own in USD per million tokens, by model string or its tail after any '/'
    llama3.3:70b:
      input: 0.6
      output: 0.6
      inputCached: 0.06 # optional, also inputCacheWrite and inputCacheWrite1h
  retry: # or `false`; default: 2 retries with exponential backoff
    maxRetries: 3
    baseDelay: 1000
    maxDelay: 30000
    maxRetryAfter: 60000
    requestTimeout: 180000 # ms one call may take before it is aborted and retried, off by default
  promptCache: # or `false`; on by default
    ttl: 1h # 5m | 1h (Anthropic)
  modelCircuitBreaker: # when a model agents fall back from (fallbackModels) is skipped
    failureThreshold: 5 # failures in a row, default 5
    resetTimeout: 30000 # ms it is skipped, default 30000
    halfOpenRequests: 3 # successes needed afterwards, default 3
  plugins: # settings for backend plugins registered with registerLLMBackend, by provider name
    my-provider:
      endpoint: http://localhost:9000

内存配置

memory:
  adapter: postgres # thread store: memory | redis | postgres | sqlite | mongodb

  # In-memory (for development)
  inMemory:
    maxEntries: 1000

  # Redis
  redis:
    url: redis://localhost:6379
    # Or individual settings:
    host: localhost
    port: 6379
    password: secret
    keyPrefix: 'cogitator:'
    ttl: 3600 # seconds
    # Cluster mode:
    cluster:
      nodes:
        - host: redis-1
          port: 6379
        - host: redis-2
          port: 6379
      scaleReads: slave # master | slave | all

  # PostgreSQL with pgvector
  postgres:
    connectionString: postgresql://user:pass@localhost:5432/cogitator
    schema: public
    poolSize: 10

  # SQLite
  sqlite:
    path: ./data/cogitator.db
    walMode: true

  # MongoDB
  mongodb:
    uri: mongodb://localhost:27017
    database: cogitator
    collectionPrefix: cog_

  # Qdrant: embedding store searched by contextBuilder, next to the thread store
  qdrant:
    url: http://localhost:6333
    apiKey: xxx
    collection: cogitator
    dimensions: 1536

  # Embedding service for semantic search
  embedding:
    provider: openai # openai | ollama | google (apiKey required for openai and google)
    apiKey: sk-xxx
    model: text-embedding-3-small
    baseUrl: https://api.openai.com/v1 # optional, for every provider
    dimensions: 1536 # optional output size (e.g. text-embedding-3-*)

  # Context builder settings
  contextBuilder:
    maxTokens: 4000
    reserveTokens: 500
    strategy: recent # recent | relevant | hybrid
    includeSystemPrompt: true
    includeFacts: true
    includeSemanticContext: true
    includeGraphContext: false
    graphContextOptions:
      maxNodes: 20
      maxEdges: 50
      maxDepth: 3
      includeInferred: true
      entityTypes: [person, organization] # person | organization | location | concept | event | object | custom

  # Compaction of a run's thread after the run (hierarchical)
  compaction:
    at: 0.8 # share of the model's context window that starts it
    keepRecentTokens: 20000 # newest whole turns kept verbatim (default: the less of 20000 and a quarter of the window)
    chapterTokens: 4000
    chapterConcurrency: 1
    chaptersPerArc: 4
    arcsPerSaga: 4
    summaryModel: google/gemini-3.5-flash # default: the model the run ended on
    summaryPrompt: Keep every price that was quoted.

  # Memory items extracted from a run's conversation after the run
  extraction:
    model: google/gemini-3.5-flash-lite # default: the model the run ended on
    prompt: Mind diets and allergies.
    windowTokens: 4000 # conversation one extraction call reads
    activationConfidence: 0.7 # confidence a quoted user item needs to become active
    scope: user # user | agent | thread
    timeZone: Europe/Lisbon # IANA, when the thread names none (default UTC)

  # The memory tool: notes under /memories every agent keeps across conversations
  files:
    scope: user # user | agent | thread
    readOnly: false
    indexChars: 2000 # characters the list of files takes in the context

  # Cards of what memory holds for the turn, before its first model call
  brief:
    model: google/gemini-3.5-flash-lite # a cheap model, the run's model by default
    maxCards: 4 # 1 to 4
    timeoutMs: 4000

  # What memory makes of the facts about each entity, rewritten when they change
  observations:
    maxEntities: 3 # observations one refresh writes at most
    minItems: 3 # facts an entity needs for an observation

  # A background pass every few runs: repeats go stale, lessons reach the playbook
  consolidation:
    everyRuns: 20
    afterCompaction: true
    maxChanges: 10 # items one pass marks as stale at most, 0 to leave items alone
    maxSubjects: 10 # subjects one pass asks about at most, the next pass goes on
    playbook: apply # apply | shadow | false
    showPlaybook: true

memory.compaction 由 MemoryCompactionConfigSchema (单位:千美元)at 0以上,最多为1个。 它的钩子 beforeCompact 财务报告和审定财务报表 afterCompact 是函数,所以它们设置在代码中。 见 运行后压缩。 。 。 .

memory.extraction 由 MemoryExtractionConfigSchema数字 : model 不为空, windowTokens 0以上的整个数字, activationConfidence 从0到1, scope 一个 user, (中文(简体) ), agent 财务报告和审定财务报表 thread,以及 timeZone 一个IANA时区。 内容 afterExtract 钩被设置在代码中. 见 运行后提取。 。 。 .

memory.files 由 MemoryFilesConfigSchema数字 : scope 一个 user, (中文(简体) ), agent 财务报告和审定财务报表 thread, (中文(简体) ), readOnly 布尔和 indexChars 0以上为整数。 有了它,运行时间 让每一个经纪人 memory 工具,并列出运行在上下文中看到的文件。 见 内存文件。 。 。 .

memory.brief 由 MemoryBriefConfigSchema数字 : model 不为空, maxCards 1至4个整数, timeoutMs 0以上和 maxTokens 整数在 0 以上,运行时间在从代码中构建简要时会投出相同的值。 见 会前简报。 。 。 .

memory.observations 由 MemoryObservationsConfigSchema数字 : model 不为空, maxEntities 财务报告和审定财务报表 minItems 0以上的全数。 见 意 见。 。 。 .

memory.consolidation 由 MemoryConsolidationConfigSchema数字 : model 不为空, everyRuns 0以上的整个数字, afterCompaction 财务报告和审定财务报表 showPlaybook 布尔斯人, maxChanges 整个数字从0, maxSubjects 0以上的整数和 playbook 一个 apply, (中文(简体) ), shadow 财务报告和审定财务报表 false。 。 afterConsolidate 钩子是一个函数,所以它被设置在代码中. 见 合并。 。 。 .

这个 Cogitator 运行时间构建商店 adapter 名称来自其部分: redis 需求 url, (中文(简体) ), host编号 :port 或者说 cluster, (中文(简体) ), postgres 需求 connectionString, (中文(简体) ), sqlite 需求 path 财务报告和审定财务报表 mongodb 需求 uri。一个 Postgres 存储其矢量列大小为 embedding。 。 。 . qdrant 不是一个线程商店: 保留其中之一为 adapter,并与 contextBuilder (单位:千美元)includeSemanticContext: true运行时间搜索 memory.qdrant 为语义上下文.

沙盒配置

sandbox:
  defaults:
    type: docker # docker | native | wasm | os
    image: python:3.11-slim
    timeout: 30000
    workdir: /workspace
    user: sandbox
    env:
      PYTHONUNBUFFERED: '1'
    mounts:
      - source: /srv/data
        target: /workspace/data
        readOnly: true
    # wasmModule / wasmFunction / wasi: defaults for wasm tools
    resources:
      memory: 512m
      cpus: 0.5
      cpuShares: 512
      pidsLimit: 100
    network:
      mode: none # none | bridge | host
      # allowedHosts: [api.example.com]  # wasm only; the docker executor rejects it
      dns:
        - 8.8.8.8

  pool:
    maxSize: 10
    idleTimeoutMs: 60000
    reuseContainers: false # true: reuse containers between executions with the same settings

  # false: fail Docker-sandboxed tools when Docker is unavailable instead of running them on the host
  allowNativeFallback: true

  docker:
    socketPath: /var/run/docker.sock
    # Or TCP:
    host: localhost
    port: 2375

  wasm:
    wasmModule: ./tools.wasm
    memoryPages: 256
    functionName: run
    wasi: true
    cacheSize: 100

sandbox.allowNativeFallback 默认为 true: Docker-sandboxed工具在无法使用Docker时在主机上被解开并运行,同时发出警告. sandbox.pool.reuseContainers 默认为 false:每次执行都得到一个新鲜的容器; true 更快, 但让一个执行留下的文件和进程到达下一个执行 .

反射配置

reflection:
  enabled: true
  reflectAfterToolCall: true
  reflectAfterError: true
  reflectAtEnd: true
  storeInsights: true
  maxInsightsPerAgent: 50
  minConfidenceToStore: 0.7
  useSmallModelForReflection: true
  reflectionModel: gpt-6-luna

护栏配置

guardrails:
  enabled: true
  model: gpt-6-luna
  filterInput: true
  filterOutput: true
  filterToolCalls: true
  filterToolResults: false
  enableCritiqueRevision: true
  maxRevisionIterations: 3
  revisionConfidenceThreshold: 0.8
  strictMode: false
  logViolations: true
  constitution: # optional: your own principles instead of the default constitution
    id: support
    name: Support desk
    version: 1.0.0
    customizable: true
    strictMode: false
    principles:
      - id: no-refund-promises
        name: No refund promises
        description: Never promise refunds the policy does not allow
        category: custom # ethics | safety | privacy | legal | custom
        critiquePrompt: Does the reply promise a refund?
        revisionPrompt: Rewrite the reply without promising a refund.
        severity: medium
        appliesTo: [output] # input | output | tool
  thresholds:
    violence: high
    hate: high
    sexual: medium
    self-harm: high
    illegal: high
    privacy: medium
    misinformation: medium
    manipulation: medium

成本运行配置

costRouting:
  enabled: true
  autoSelectModel: true
  preferLocal: true
  minCapabilityMatch: 0.3
  trackCosts: true
  ollamaUrl: http://localhost:11434
  budget:
    maxCostPerRun: 0.10
    maxCostPerHour: 5.00
    maxCostPerDay: 50.00
    warningThreshold: 0.8

安全配置

security:
  promptInjection:
    detectInjection: true
    detectJailbreak: true
    detectRoleplay: true
    detectEncoding: true
    detectContextManipulation: true
    patterns: # your own regular expression sources, compiled to RegExp
      - 'reveal (the|your) system prompt'
    classifier: local # local | llm
    llmModel: openai/gpt-6-luna # for classifier: llm
    action: block # block | warn | log
    threshold: 0.7
    failMode: secure # when the classifier throws: secure (default) fails the check, open lets the input through
    allowlist:
      - ignore the previous search
  pii:
    mode: mask # mask | redact | block
    detect: [email, phone, credit_card, iban, ssn, ip_address, api_key]
    custom:
      - type: customer_id
        pattern: 'CUS-\d{6}' # a regular expression source, compiled to a RegExp

背景配置

context:
  enabled: true
  strategy: hybrid # truncate | sliding-window | summarize | hybrid
  compressionThreshold: 0.8
  outputReserve: 0.15
  summaryModel: openai/gpt-6-luna
  windowSize: 10

部署配置

阅读者 @cogitator-ai/deploy 财务报告和审定财务报表 cogitator deploy数字 :

deploy:
  target: fly # docker | fly
  server: express # express | fastify | hono | koa
  port: 3000
  registry: registry.fly.io
  image: my-agents
  region: ams
  instances: 2
  services:
    redis: true
    postgres: false
  env:
    NODE_ENV: production
  secrets: [OPENAI_API_KEY]
  health:
    path: /cogitator/health
    interval: 30s
    timeout: 5s
  resources:
    memory: 512mb
    cpu: 1

限制配置

limits:
  maxConcurrentRuns: 10 # runs over the limit wait in order
  defaultTimeout: 120000 # ms, for runs and agents that set no timeout
  maxTokensPerRun: 100000 # checked before each model call
  maxToolResultLength: 100000 # characters of a tool result the model reads

触发配置( 实验)

内容 experimental_triggers 文件可以持有:常规,民意测验间隔和限制. 代理商和工作流程的常规名称,存储和汇来自代码,而秘密则来自其环境变量({ env: NAME }),而不是作为文件中的文本.

experimental_triggers:
  pollInterval: 1000
  routines:
    - id: digest
      prompt: Summarize the news of the day
      target: { agent: assistant }
      overlap: skip
      catchUp: latest
      triggers:
        - { kind: cron, cron: '0 18 * * 1-5', timezone: Europe/Moscow }
        - { kind: github, secret: { env: GITHUB_WEBHOOK_SECRET }, events: [pull_request.opened] }

日志配置

logging:
  level: info # debug | info | warn | error | silent
  format: pretty # json | pretty
  destination: console # console | file
  filePath: ./logs/cogitator.log

A 类 Cogitator 创建于 logging 将它安装为全过程的日志器(上一次这样的运行时间获胜). destination: file 每个条目附加一行 filePath作为JSON,除非 format 设置;没有 filePath,或者在没有文件系统的运行时,它会登录到控制台. createLoggerFromConfig() 从 @cogitator-ai/core 在代码中建立相同的日志 .


环境变量

支持的提供者、限制和部署设置可通过环境变量与 COGITATOR_ 前缀 :

变量说明
COGITATOR_LLM_DEFAULT_PROVIDER默认 LLM 提供者
COGITATOR_LLM_DEFAULT_MODEL默认模式
COGITATOR_OLLAMA_BASE_URLOllama 基础 URL
COGITATOR_OLLAMA_API_KEYOllama API 密钥
COGITATOR_OPENAI_API_KEYOpenAI API 密钥
COGITATOR_OPENAI_BASE_URLOpenAI 基址
COGITATOR_ANTHROPIC_API_KEYAnthropic API 键
COGITATOR_ANTHROPIC_BASE_URLAthropic API 基础
COGITATOR_GOOGLE_API_KEY谷歌 API 密钥
COGITATOR_GOOGLE_BASE_URL双子座 API 基础
COGITATOR_VLLM_BASE_URLvLLM 基础 URL
COGITATOR_AZURE_API_KEYAzure OpenAI API 密钥
COGITATOR_AZURE_ENDPOINTAzure OpenAI 端点
COGITATOR_AZURE_API_VERSIONAzure API 版本
COGITATOR_AZURE_DEPLOYMENTAzure 部署名称
COGITATOR_AZURE_MODELAzure 模型名称
COGITATOR_BEDROCK_REGIONAWS 贝德罗克地区
COGITATOR_BEDROCK_ACCESS_KEY_IDAWS 访问密钥ID
COGITATOR_BEDROCK_SECRET_ACCESS_KEYAWS 秘密访问密钥
COGITATOR_BEDROCK_SESSION_TOKENAWS 会话符号
COGITATOR_BEDROCK_PROFILEAWS 命名配置文件
COGITATOR_BEDROCK_ENDPOINTBedrock 运行时终点
COGITATOR_MISTRAL_API_KEYMistral API 密钥
COGITATOR_GROQ_API_KEYGroq API 密钥
COGITATOR_TOGETHER_API_KEY组合 API 密钥
COGITATOR_DEEPSEEK_API_KEY深搜索 API 密钥
COGITATOR_OPENROUTER_API_KEYOpenRouter API 密钥
COGITATOR_OPENROUTER_BASE_URLOpenRouter API 基础
COGITATOR_LIMITS_MAX_CONCURRENT_RUNS最大并行运行
COGITATOR_LIMITS_DEFAULT_TIMEOUT默认超时( 毫秒)
COGITATOR_LIMITS_MAX_TOKENS_PER_RUN每跑一次最大令牌数
COGITATOR_LIMITS_MAX_TOOL_RESULT_LENGTH工具的最大字符结果模型读取
COGITATOR_DEPLOY_TARGET部署目标
COGITATOR_DEPLOY_PORT部署端口
COGITATOR_DEPLOY_REGISTRY集装箱登记

标准供应商 env vars 也被支持:

OPENAI_API_KEY=sk-xxx
ANTHROPIC_API_KEY=sk-ant-xxx
ANTHROPIC_BASE_URL=https://gateway.example.com/anthropic   # optional proxy or gateway
GOOGLE_API_KEY=xxx            # or GEMINI_API_KEY
OLLAMA_URL=http://localhost:11434   # or OLLAMA_BASE_URL / OLLAMA_HOST, see below
OLLAMA_API_KEY=xxx            # Ollama Cloud / authenticated Ollama
AZURE_OPENAI_API_KEY=xxx
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
AZURE_OPENAI_DEPLOYMENT=gpt-6.1-sol
AWS_REGION=us-east-1          # Bedrock region, credentials come from the AWS SDK chain
MISTRAL_API_KEY=xxx
GROQ_API_KEY=xxx
TOGETHER_API_KEY=xxx
DEEPSEEK_API_KEY=xxx
OPENROUTER_API_KEY=xxx        # or OPENROUTER_BASE_URL for a proxy

loadConfig 读取 COGITATOR_ANTHROPIC_BASE_URL, (中文(简体) ), ANTHROPIC_BASE_URL 财务报告和审定财务报表 COGITATOR_GOOGLE_BASE_URL 与来自环境的 API 密钥一起进入配置, 完毕 cogitator.yml页:1 COGITATOR_ 变量。 Anthropic SDK也读作 ANTHROPIC_BASE_URL 在没有的情况下,由自己负责 baseUrl 已配置.

何时 OLLAMA_API_KEY 设置时没有 Ollama URL (从 env 或 YAML), Ollama 基础 URL 默认为 https://ollama.com; 否则默认为 http://localhost:11434。环境中的 API 键永远不会取代 baseUrl 在 YAML 中配置 .

OLLAMA_BASE_URL, (中文(简体) ), OLLAMA_URL 财务报告和审定财务报表 OLLAMA_HOST (第一集胜出)读取奥拉玛的读取方式 OLLAMA_HOST数字 : gpu-box 财务报告和审定财务报表 0.0.0.0 平均端口11434,一个通配符地址,例如 0.0.0.0 以 localhost,以及 http:// 或者说 https:// 保持计划自己的端口。 其他工具也设置了这些变量(OLLAMA_HOST=0.0.0.0 制造 ollama serve ,所以它们只有在 cogitator.yml 没有时才适用 llm.providers.ollama.baseUrl。 。 。 . COGITATOR_OLLAMA_BASE_URL 覆盖 YAML 值, 如每 个 COGITATOR_ 变量. loadEnvDefaults() 返回此图层 resolveOllamaHost(value) 分析一个单一的值.

贝德罗克证书留在AWS SDK: AWS_ACCESS_KEY_ID, (中文(简体) ), AWS_SECRET_ACCESS_KEY, (中文(简体) ), AWS_SESSION_TOKEN, (中文(简体) ), AWS_PROFILE,SSO和实例角色 所有工作随着SDK的解决, 所以临时的证书保留他们的会话符号。 静态证书只来自 COGITATOR_BEDROCK_* 或者说 llm.providers.bedrock 在YAML中( 编号:accessKeyId, (中文(简体) ), secretAccessKey, (中文(简体) ), sessionToken, (中文(简体) ), profile) (中文(简体) ).

PROVIDER_ENV 列出每个内置提供者的每个变量(什么 loadConfig 读取,提供商SDK读取的内容,以及提供商无法在没有的情况下运行的内容). cogitator deploy 使用同一个表格来决定部署需要哪些秘密.

无 configPath, (中文(简体) ), loadConfig 读取第一个 cogitator.yml, (中文(简体) ), cogitator.yaml, (中文(简体) ), .cogitator.yml 财务报告和审定财务报表 .cogitator.yaml 在工作目录中. findConfigFile(dir) 找到同样的方式.

${VAR} YAML 参考文献

YAML 文件的字符串值可以引用环境变量:

llm:
  providers:
    openai:
      apiKey: ${OPENAI_API_KEY}
      baseUrl: ${OPENAI_BASE_URL:-https://api.openai.com/v1}
语法结果
${VAR}价值 VAR,或未设置时的空字符串
${VAR:-default}default 何时 VAR 未设置 或为空
${VAR-default}default 仅在 VAR 未设置
$$一个字形 $

被替换的值总是字符串,所以对字符串字段(键, URL, 模型名)使用引用 —— 数字字段如 deploy.port 必须保持文字.


优先权顺序

配置在此顺序下被深植( 后推翻更早 ) :

  1. YAML 配置文件 (单位:千美元)cogitator.yml; 最低优先级)
  2. 环境变量 (单位:千美元)COGITATOR_* 和标准提供者变量)
  3. 程序覆盖 (最高优先级)

Fields nobody sets stay unset, 运行时间应用自己的默认值 。 默认的是奥拉玛 baseUrl (见上文)。 未知的顶级密钥被验证后丢出.

奥拉玛接受 llm.providers.ollama.headers 用于在非流式和流式聊天请求中需要额外 HTTP 标题的网关 /api/chat。运行时间保持 Content-Type: application/json,则 apiKey 优先于习惯 Authorization 不论弹壳都用头 没有 apiKey,保留自定义授权.


Schema 验证

所有配置均使用 Zod 计划验证 :

import {
  CogitatorConfigSchema,
  LLMConfigSchema,
  MemoryConfigSchema,
  ReflectionConfigSchema,
} from '@cogitator-ai/config';

// Validate raw config
const result = CogitatorConfigSchema.safeParse(rawConfig);
if (!result.success) {
  console.error('Invalid config:', result.error.issues);
}

// Type-safe config
import type { CogitatorConfigInput, CogitatorConfigOutput } from '@cogitator-ai/config';

可用的外观

司马说明
CogitatorConfigSchema完整配置
LLMConfigSchemaLLM 提供者和默认
MemoryConfigSchema内存适配器和设置
MemoryCompactionConfigSchemamemory.compaction
MemoryExtractionConfigSchemamemory.extraction
MemoryFilesConfigSchemamemory.files
MemoryBriefConfigSchemamemory.brief
MemoryObservationsConfigSchemamemory.observations
MemoryConsolidationConfigSchemamemory.consolidation
SandboxConfigSchemaSandbox 执行设置
ReflectionConfigSchema自反应设置
GuardrailConfigSchema安全护栏
ConstitutionSchemaguardrails.constitution 原则
CostRoutingConfigSchema成本意识模式选择
KnowledgeGraphConfigSchema知识图表设置
PromptOptimizationConfigSchema快速优化
SecurityConfigSchema快速注射和PII口罩
ContextManagerConfigSchema上下文压缩
LoggingConfigSchema日志设置
DeployConfigSchema部署设置
DeployTargetSchema部署目标docker | fly(中文(简体) )
DeployServerSchema服务器框架
LLMRetryConfigSchemallm.retry (单位:千美元)false 或重试选项)
ModelCircuitBreakerConfigSchemallm.modelCircuitBreaker
PromptsConfigSchemaprompts (单位:千美元)autoDeployWinner(中文(简体) )
TriggersConfigSchemaexperimental_triggers (实验性)

KnowledgeGraphConfigSchema 财务报告和审定财务报表 PromptOptimizationConfigSchema 自动验证这些配置;它们不是 CogitatorConfigSchema。 。 。 .


实例

开发配置

# cogitator.dev.yml
llm:
  defaultProvider: ollama
  providers:
    ollama:
      baseUrl: http://localhost:11434

memory:
  adapter: memory
  inMemory:
    maxEntries: 100

logging:
  level: debug
  format: pretty

sandbox:
  defaults:
    type: native # no Docker needed

生产配置

# cogitator.prod.yml
llm:
  defaultProvider: openai
  defaultModel: gpt-6.1-sol
  providers:
    openai:
      apiKey: sk-prod-openai
    anthropic:
      apiKey: sk-ant-prod

memory:
  adapter: postgres
  postgres:
    connectionString: postgresql://user:[email protected]:5432/cogitator
    poolSize: 20
  embedding:
    provider: openai
    apiKey: sk-prod-openai
  contextBuilder:
    maxTokens: 8000
    strategy: hybrid

reflection:
  enabled: true
  storeInsights: true

guardrails:
  enabled: true
  strictMode: true

costRouting:
  enabled: true
  autoSelectModel: true
  budget:
    maxCostPerDay: 100.00

logging:
  level: info
  format: json
  destination: file
  filePath: /var/log/cogitator/app.log

sandbox:
  defaults:
    type: docker
    resources:
      memory: 256m
      cpus: 0.25
  pool:
    maxSize: 20

API 参考

加载Config( 选项)

从文件、 环境和 上载配置 .

interface LoadConfigOptions {
  configPath?: string; // Path to YAML file
  skipEnv?: boolean; // Skip loading from environment variables
  skipYaml?: boolean; // Skip loading from YAML file
  overrides?: CogitatorConfigInput; // Programmatic overrides
}

const config = loadConfig({
  configPath: './cogitator.yml',
  overrides: { logging: { level: 'debug' } },
});

定义 Config( 配置)

类型安全配置定义帮助器.

const config = defineConfig({
  llm: {
    defaultProvider: 'openai',
    providers: {
      openai: { apiKey: 'sk-xxx' },
    },
  },
});

装入 YamlConfig( 路径 )

装入并分析 YAML 配置文件并解析 ${VAR} 参考文献。 没有路径, 它会搜索默认文件名; 不存在的路径丢出 Config file not found. 回归 null 如果找不到配置文件或文件为空; 当文件无法解析(信件包括路径)或其顶层不是映射时丢出。 尚未验证结果(loadConfig - 做那个.

import { loadYamlConfig } from '@cogitator-ai/config';

const config = loadYamlConfig('./cogitator.yml');

装入 EnvConfig ()

从环境变量中装入配置 .

import { loadEnvConfig } from '@cogitator-ai/config';

const config = loadEnvConfig();

interpolateEnv( 值, env?) / interpolateEnvString( 值, env?)

应用 ${VAR} 替换到解析的配置对象或单个字符串(由 loadYamlConfig) (中文(简体) ).

import { interpolateEnvString } from '@cogitator-ai/config';

interpolateEnvString('${HOST:-localhost}:${PORT}', { PORT: '8080' }); // 'localhost:8080'

parseDotenv( 内容) / 加载DotenvFile( 路径)

解析 .env 文档(KEY=VALUE, (中文(简体) ), export 前缀,单/双引出有逃生,内含注释). loadDotenvFile 返回时 {} 当文件不存在时。 两个函数都变异 process.env。 。 。 .

import { loadDotenvFile } from '@cogitator-ai/config';

const env = { ...loadDotenvFile('.env'), ...process.env };

许可证

麻省理工学院

版本与发布记录

@cogitator-ai/config 共发布 98 个版本,首次发布于 2025/12/31;过去 12 个月发布了 98 个版本。

版本发布日期距今
0.36.5latest2026/10/2912 天前
0.36.42026/10/2912 天前
0.36.32026/10/2912 天前
0.36.22026/10/2912 天前
0.36.12026/10/2912 天前
0.36.02026/10/2812 天前

关于 @cogitator-ai/config 的常见问题

@cogitator-ai/config 是什么?

Cogitator (YAML, env) 的配置加载

如何安装 @cogitator-ai/config?

在项目目录运行 npm install @cogitator-ai/config,或使用 pnpm add / yarn add / bun add。

@cogitator-ai/config 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cogitator-ai/config 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@cogitator-ai/config 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cogitator-ai/config 可以商用吗?

@cogitator-ai/config 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cogitator-ai/config 的下载量有多少?

根据 npm 官方下载统计,@cogitator-ai/config 在 2026/10/11 – 2026/11/09 这 30 天内被下载 10,336 次,日均约 345 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cogitator-ai/config 还在维护吗?

最新版本 0.36.5 发布于 2026/10/29(12 天前);至今共发布 98 个版本,其中过去 12 个月发布了 98 个;首次发布于 2025/12/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。