Skip to content

5.10b API 参考

💡 一句话总结:完整的 OpenCode SDK API 参考。


JavaScript/TypeScript SDK

OpenCode 客户端

typescript
class OpenCode {
  constructor(config: OpenCodeConfig);
  
  // 属性
  chat: ChatAPI;
  sessions: SessionsAPI;
  files: FilesAPI;
  tools: ToolsAPI;
  agents: AgentsAPI;
  config: ConfigAPI;
  
  // 方法
  async initialize(): Promise<void>;
  async destroy(): Promise<void>;
}

ChatAPI

typescript
class ChatAPI {
  async send(options: ChatOptions): Promise<ChatResponse>;
  async sendStream(options: ChatOptions): AsyncIterable<ChatChunk>;
  async getHistory(sessionId: string): Promise<ChatMessage[]>;
  async clearHistory(sessionId: string): Promise<void>;
}

SessionsAPI

typescript
class SessionsAPI {
  async create(options: SessionOptions): Promise<Session>;
  async get(sessionId: string): Promise<Session>;
  async list(options?: ListOptions): Promise<Session[]>;
  async delete(sessionId: string): Promise<void>;
  async update(sessionId: string, options: UpdateOptions): Promise<Session>;
}

FilesAPI

typescript
class FilesAPI {
  async read(path: string): Promise<string>;
  async write(path: string, content: string): Promise<void>;
  async delete(path: string): Promise<void>;
  async list(path: string): Promise<FileInfo[]>;
  async search(pattern: string): Promise<string[]>;
  async exists(path: string): Promise<boolean>;
}

ToolsAPI

typescript
class ToolsAPI {
  async execute(options: ToolOptions): Promise<ToolResult>;
  async list(): Promise<ToolInfo[]>;
  async getInfo(name: string): Promise<ToolInfo>;
}

Python SDK

python
class OpenCode:
    def __init__(self, api_key: str, **kwargs):
        ...
    
    @property
    def chat(self) -> ChatAPI:
        ...
    
    @property
    def sessions(self) -> SessionsAPI:
        ...
    
    @property
    def files(self) -> FilesAPI:
        ...

类型定义

ChatOptions

typescript
interface ChatOptions {
  message: string;
  context?: Record<string, any>;
  stream?: boolean;
  model?: string;
  temperature?: number;
  maxTokens?: number;
}

Session

typescript
interface Session {
  id: string;
  title: string;
  agent: string;
  createdAt: Date;
  updatedAt: Date;
  messageCount: number;
}

ToolResult

typescript
interface ToolResult {
  success: boolean;
  output: string;
  error?: string;
  executionTime: number;
}

错误处理

typescript
try {
  const response = await client.chat.send({
    message: "帮我创建一个函数",
  });
} catch (error) {
  if (error instanceof OpenCodeError) {
    console.error(`错误代码: ${error.code}`);
    console.error(`错误信息: ${error.message}`);
    console.error(`状态码: ${error.status}`);
  }
}

检查点 ✅

全部通过才能继续

  • [ ] 能使用客户端 API
  • [ ] 能理解类型定义
  • [ ] 能处理错误
  • [ ] 能使用所有功能

本课小结

你学会了:

  1. JavaScript SDK API
  2. Python SDK API
  3. 类型定义
  4. 错误处理

下一课预告

下一课我们将学习企业版功能。


📚 更多完整模板Prompt 模板库