Cortex Code Agent SDK

Cortex Code Agent SDK 允许您使用 Python 和 TypeScript 构建代理式 AI 应用程序。您的代理可以使用支持 Cortex Code 的相同工具和代理循环来读取文件、运行命令、搜索代码库、执行 SQL 以及编辑代码。

SDK 包含用于文件操作、Shell 命令和代码编辑的内置工具,因此您的代理可以立即开始工作,而无需您实现工具执行。

import { query } from "cortex-code-agent-sdk";

for await (const message of query({
  prompt: "What does this codebase do? Give me a one-paragraph summary.",
  options: { cwd: process.cwd() },
})) {
  if (message.type === "assistant") {
    for (const block of message.content) {
      if (block.type === "text") process.stdout.write(block.text);
    }
  }
}

开始使用

先决条件

要求

详细信息

Cortex Code CLI

使用 curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh 安装

Snowflake 连接

通过 Snowflake CLI 连接设置进行配置,通常位于 ~/.snowflake/connections.toml 中。系统还支持 ~/.snowflake/config.toml 中的现有设置。传递 connection 选项或在 TOML 文件中设置 default_connection_name。请参阅 配置连接

Node.js (TypeScript)

18.0.0 版本或更高版本

Python (Python SDK)

3.10 版本或更高版本

1.安装 Cortex Code CLI

安装 CLI:

curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh

2.安装 SDK

从 npm 或 PyPI 安装 SDK:

npm install cortex-code-agent-sdk

3.配置 Snowflake 连接

通过您的 Snowflake CLI 连接设置进行 SDK 身份验证。向 ~/.snowflake/connections.toml 添加连接或使用 ~/.snowflake/config.toml 中的现有设置(请参阅 配置连接):

[my-connection]
account = "myorg-myaccount"
user = "myuser"
authenticator = "externalbrowser"

SDK 使用 CLI 的默认连接,除非您通过 connection 选项显式指定一个。

如果 Cortex Code CLI 不在您的 PATH 中,请通过设置 CORTEX_CODE_CLI_PATH=/path/to/cortex 或在 SDK 选项中传递 cliPath (TypeScript) 或 cli_path (Python) 来将 SDK 指向它。

4.运行首个代理

以下示例创建了一个代理,该代理会探索您的项目并总结其功能:

import { query } from "cortex-code-agent-sdk";

for await (const message of query({
  prompt: "What does this codebase do? Give me a one-paragraph summary.",
  options: { cwd: process.cwd() },
})) {
  if (message.type === "assistant") {
    for (const block of message.content) {
      if (block.type === "text") process.stdout.write(block.text);
    }
  }
  if (message.type === "result") {
    console.log("\nDone:", message.subtype);
  }
}

有关更完整的教程,请参阅 快速入门

功能

内置工具

您的代理可以读取文件、运行命令、执行 SQL 并搜索代码库,无需额外配置。可用工具因环境和运行时能力而异:

工具

描述

读取

读取工作目录中的任何文件

写入

创建新文件

编辑

对现有文件进行精确编辑

Bash

运行终端命令、脚本和 Git 操作

Glob

按模式(**/*.tssrc/**/*.py)查找文件

Grep

使用正则表达式搜索文件内容

SQL

针对 Snowflake 执行 SQL 查询

多轮会话

您可以跨多轮交换维护上下文。代理会保留读取的文件、执行的分析以及对话历史记录:

import { createCortexCodeSession } from "cortex-code-agent-sdk";

const session = await createCortexCodeSession({ cwd: process.cwd() });

await session.send("Read the authentication module");
for await (const event of session.stream()) {
  if (event.type === "result") break;
}

// Second turn - "it" refers to the auth module from context
await session.send("Now find all places that call it");
for await (const event of session.stream()) {
  if (event.type === "result") break;
}

await session.close();

您还可以继续上一个会话,或将其分叉为一个新会话:

// Continue the most recent conversation
const session = await createCortexCodeSession({
  cwd: process.cwd(),
  continue: true,
});

// Or fork a resumed session into a new session ID
const forked = await createCortexCodeSession({
  cwd: process.cwd(),
  resume: "previous-session-id",
  forkSession: true,
});

MCP 服务器

您可以通过模型上下文协议连接到外部系统:

from cortex_code_agent_sdk import CortexCodeAgentOptions

options = CortexCodeAgentOptions(
    mcp_servers={
        "my-tools": {
            "command": "node",
            "args": ["my-mcp-server.js"],
        },
    },
)

Hook

您可以在代理生命周期的关键点运行自定义代码。可用的 Hook 事件包括 PreToolUsePostToolUseStopUserPromptSubmit 等。Python 和 TypeScript SDKs 均支持 Hook。有关详细信息,请参阅 Python SDK 参考TypeScript SDK 参考

结构化输出

您可以强制代理返回与 JSON 模式匹配的响应:

const result = query({
  prompt: "Analyze this codebase",
  options: {
    cwd: ".",
    outputFormat: {
      type: "json_schema",
      schema: {
        type: "object",
        properties: {
          languages: { type: "array", items: { type: "string" } },
          summary: { type: "string" },
        },
        required: ["languages", "summary"],
      },
    },
  },
});

有关更多信息,请参阅 结构化输出

会话控制

您可以通过会话选项控制代理行为:

选项

描述

maxTurns / max_turns

限制代理停止前的执行轮次

effort

设置模型思考工作量("minimal""low""medium""high""max"

abortController / abort_event

在轮次中途中断运行中的代理。会话保持活动状态,以供后续提示使用。

env

将环境变量传递给代理进程

additionalDirectories / add_dirs

添加代理在 cwd 之外可以访问的额外目录

plugins

加载自定义扩展的插件目录

systemPrompt / system_prompt

替换或追加到默认系统提示

settingSources / setting_sources

控制加载哪些设置文件("user""project""local"

支持的模型

使用 model 选项设置模型。Snowflake 建议使用 "auto",以自动选择可用的最高质量模型。

模型

标识符

自动(推荐)

auto

Claude Opus 4.6

claude-opus-4-6

Claude Sonnet 4.6

claude-sonnet-4-6

Claude Opus 4.5

claude-opus-4-5

Claude Sonnet 4.5

claude-sonnet-4-5

Claude Sonnet 4.0

claude-4-sonnet

OpenAI GPT 5.2

openai-gpt-5.2

跨区域推理

模型可用性因区域而异。账户管理员可以启用跨区域推理,以访问本地不可用的模型:

ALTER ACCOUNT SET CORTEX_ENABLED_CROSS_REGION = 'AWS_US';

有关更多信息,请参阅 跨区域推理

后续步骤