API 参考

完整的 Gemini CLI API 文档,包含详细的方法描述、参数和实用示例。

API 部分

导航到不同的 API 类别

核心 API

与 Gemini 模型交互和管理对话的主要 API

插件 API

用于开发自定义插件和扩展的 API

配置 API

用于管理 CLI 配置和设置的 API

工具 API

用于管理和执行内置工具的 API

核心 API

与 Gemini 模型交互和管理对话的主要 API

chat()

启动与 Gemini 的交互式聊天会话

签名:

chat(options?: ChatOptions): Promise<ChatSession>

示例:

import { GeminiCLI } from '@google/generative-ai-cli';

const cli = new GeminiCLI();
const session = await cli.chat({
  model: 'gemini-pro',
  temperature: 0.7
});

ask()

发送单个提示并获取响应

签名:

ask(prompt: string, options?: AskOptions): Promise<string>

示例:

const response = await cli.ask("什么是机器学习?", {
  maxTokens: 1000,
  temperature: 0.5
});

analyze()

使用 AI 辅助分析文件或代码

签名:

analyze(files: string[], options?: AnalyzeOptions): Promise<AnalysisResult>

示例:

const analysis = await cli.analyze(['src/main.js'], {
  type: 'code-review',
  includeMetrics: true
});

插件 API

用于开发自定义插件和扩展的 API

registerPlugin()

向 CLI 注册新插件

签名:

registerPlugin(plugin: Plugin): void

示例:

const myPlugin = {
  name: 'my-custom-plugin',
  version: '1.0.0',
  commands: {
    'custom-command': async (args) => {
      // 插件逻辑在这里
      return '插件执行成功';
    }
  }
};

cli.registerPlugin(myPlugin);

createTool()

创建供 AI 使用的自定义工具

签名:

createTool(definition: ToolDefinition): Tool

示例:

const weatherTool = cli.createTool({
  name: 'get_weather',
  description: '获取指定位置的当前天气',
  parameters: {
    location: { type: 'string', required: true }
  },
  execute: async ({ location }) => {
    // 获取天气数据
    return `${location}的天气:晴朗,25°C`;
  }
});

配置 API

用于管理 CLI 配置和设置的 API

getConfig()

获取当前配置值

签名:

getConfig(key?: string): any

示例:

// 获取所有配置
const config = cli.getConfig();

// 获取特定配置值
const model = cli.getConfig('model');

setConfig()

设置配置值

签名:

setConfig(key: string, value: any): void

示例:

// 设置模型
cli.setConfig('model', 'gemini-pro');

// 设置多个值
cli.setConfig('temperature', 0.8);
cli.setConfig('maxTokens', 2000);

resetConfig()

重置配置为默认值

签名:

resetConfig(key?: string): void

示例:

// 重置所有配置
cli.resetConfig();

// 重置特定键
cli.resetConfig('temperature');

工具 API

用于管理和执行内置工具的 API

listTools()

获取可用工具列表

签名:

listTools(): Tool[]

示例:

const tools = cli.listTools();
console.log(tools.map(t => t.name));
// ['read_file', 'write_file', 'run_shell_command', ...]

executeTool()

执行特定工具

签名:

executeTool(name: string, args: any): Promise<any>

示例:

// 读取文件
const content = await cli.executeTool('read_file', {
  path: './package.json'
});

// 运行 shell 命令
const result = await cli.executeTool('run_shell_command', {
  command: 'ls -la'
});

常用类型

API 中使用的 TypeScript 接口和类型

ChatOptions

启动聊天会话的选项

model

string

要使用的模型(例如:"gemini-pro")

temperature

number

创造性水平(0-1)

maxTokens

number

最大响应长度

systemPrompt

string

系统指令

ToolDefinition

创建自定义工具的定义

name

string

唯一工具名称

description

string

AI 的工具描述

parameters

object

参数模式

execute

function

工具执行函数

其他资源

探索更多文档和示例