核心 API

完整的 Gemini CLI 核心 API 参考和使用指南

API 参考30 分钟阅读

API 模块

核心 API 模块和方法

GeminiClient

核心 Gemini API 客户端类

src/core/gemini.ts

constructor

constructor(config: GeminiConfig)

创建 Gemini 客户端实例

参数:
configGeminiConfig

客户端配置对象

示例:
const client = new GeminiClient({
  apiKey: process.env.GEMINI_API_KEY,
  model: 'gemini-pro',
  temperature: 0.7
})

chat

async chat(message: string, context?: Context): Promise<ChatResponse>

发送聊天消息并获取响应

参数:
messagestring

用户输入消息

contextContext

可选的上下文信息

返回:
Promise<ChatResponse>

聊天响应对象

示例:
const response = await client.chat('Hello, Gemini!', {
  files: ['src/index.ts'],
  history: previousMessages
})

stream

async stream(message: string, context?: Context): AsyncGenerator<string>

流式聊天响应

参数:
messagestring

用户输入消息

contextContext

可选的上下文信息

返回:
AsyncGenerator<string>

流式响应生成器

示例:
for await (const chunk of client.stream('Explain this code')) {
  process.stdout.write(chunk)
}

SessionManager

会话状态管理器

src/core/session.ts

createSession

createSession(id?: string): Session

创建新会话

参数:
idstring

可选的会话 ID

返回:
Session

新创建的会话对象

示例:
const session = sessionManager.createSession('my-session')

getSession

getSession(id: string): Session | null

获取指定会话

参数:
idstring

会话 ID

返回:
Session | null

会话对象或 null

示例:
const session = sessionManager.getSession('my-session')

saveSession

async saveSession(session: Session): Promise<void>

将会话保存到持久存储

参数:
sessionSession

要保存的会话对象

示例:
await sessionManager.saveSession(session)

ContextManager

上下文处理管理器

src/core/context.ts

addFile

async addFile(filePath: string): Promise<void>

将文件添加到上下文

参数:
filePathstring

文件路径

示例:
await contextManager.addFile('src/utils/helper.ts')

addDirectory

async addDirectory(dirPath: string, options?: DirOptions): Promise<void>

将目录添加到上下文

参数:
dirPathstring

目录路径

optionsDirOptions

目录扫描选项

示例:
await contextManager.addDirectory('src/', {
  exclude: ['*.test.ts'],
  maxDepth: 3
})

getContext

getContext(): Context

获取当前上下文

返回:
Context

当前上下文对象

示例:
const context = contextManager.getContext()

类型定义

核心 API 的 TypeScript 类型定义

GeminiConfig

Gemini 客户端配置接口

apiKeystring
必需

Google AI API 密钥

modelstring

要使用的模型名称,默认为 "gemini-pro"

temperaturenumber

生成温度,介于 0-1 之间

maxTokensnumber

最大令牌数

timeoutnumber

请求超时时间(毫秒)

ChatResponse

聊天响应接口

contentstring
必需

响应内容

usageTokenUsage
必需

令牌使用信息

modelstring
必需

使用的模型

finishReasonstring

完成原因

Context

上下文信息接口

filesFileContext[]

文件上下文列表

historyMessage[]

消息历史

metadataRecord<string, any>

元数据

Session

会话接口

idstring
必需

唯一会话标识符

messagesMessage[]
必需

消息历史

contextContext

会话上下文

createdAtDate
必需

创建时间

updatedAtDate
必需

更新时间

使用示例

常见的 API 使用场景和代码示例

基本聊天

简单聊天交互示例

import { GeminiClient } from '@gemini/core'

const client = new GeminiClient({
  apiKey: process.env.GEMINI_API_KEY,
  model: 'gemini-pro'
})

async function basicChat() {
  try {
    const response = await client.chat('Hello, how are you?')
    console.log('AI:', response.content)
  } catch (error) {
    console.error('Chat error:', error.message)
  }
}

文件上下文

包含文件上下文的聊天

import { GeminiClient, ContextManager } from '@gemini/core'

const client = new GeminiClient({ apiKey: process.env.GEMINI_API_KEY })
const contextManager = new ContextManager()

async function chatWithFiles() {
  // Add files to context
  await contextManager.addFile('src/utils/helper.ts')
  await contextManager.addDirectory('src/components/')

  const context = contextManager.getContext()

  const response = await client.chat(
    'Explain the helper functions in this codebase',
    context
  )

  console.log(response.content)
}

会话管理

管理持久会话

import { SessionManager } from '@gemini/core'

const sessionManager = new SessionManager()

async function manageSessions() {
  // Create new session
  const session = sessionManager.createSession('project-review')

  // Add messages to session
  session.messages.push({
    role: 'user',
    content: 'Review this code for best practices'
  })

  // Save session
  await sessionManager.saveSession(session)

  // Restore session later
  const restored = sessionManager.getSession('project-review')
  console.log('Session messages:', restored?.messages.length)
}

流式响应

实时流式输出

import { GeminiClient } from '@gemini/core'

const client = new GeminiClient({ apiKey: process.env.GEMINI_API_KEY })

async function streamingChat() {
  console.log('AI: ')

  for await (const chunk of client.stream('Write a short story')) {
    process.stdout.write(chunk)
  }

  console.log('\n\nStream completed!')
}

错误处理

API 错误类型和处理方法

AuthenticationError

无效或过期的 API 密钥

GEMINI_AUTH_ERROR

解决方案:

检查 API 密钥是否正确设置,确保密钥有效且未过期

RateLimitError

请求频率超出限制

GEMINI_RATE_LIMIT

解决方案:

实施指数退避重试机制,或升级到更高配额计划

ContextTooLargeError

上下文内容超出模型限制

GEMINI_CONTEXT_TOO_LARGE

解决方案:

减少上下文文件数量或使用文件摘要功能

NetworkError

网络连接问题

GEMINI_NETWORK_ERROR

解决方案:

检查网络连接,配置代理设置,或增加超时时间

下一步

通过这些资源继续您的开发之旅