Skip to content

AI Chat API

The AI Chat API provides integration with Trae IDE's built-in AI assistant, allowing extensions to interact with the AI chat system, send messages, and receive responses.

Overview

The AI Chat API enables you to:

  • Send messages to the AI assistant
  • Receive AI responses
  • Access chat history
  • Create custom AI interactions
  • Integrate AI capabilities into extensions

Basic Usage

Sending Messages

typescript
import { TraeAPI } from '@trae/api';

// Send a simple message
const response = await TraeAPI.ai.chat.sendMessage('Explain this code snippet');
console.log('AI Response:', response.content);

// Send message with context
const contextualResponse = await TraeAPI.ai.chat.sendMessage(
  'How can I optimize this function?',
  {
    context: {
      selectedText: editor.document.getText(editor.selection),
      fileName: editor.document.fileName,
      language: editor.document.languageId
    }
  }
);

Listening to Chat Events

typescript
// Listen to new messages
TraeAPI.ai.chat.onDidReceiveMessage((message) => {
  console.log('New AI message:', message.content);
  console.log('Message type:', message.type); // 'user' | 'assistant' | 'system'
});

// Listen to chat session changes
TraeAPI.ai.chat.onDidChangeActiveSession((session) => {
  console.log('Active session changed:', session.id);
});

// Listen to typing indicators
TraeAPI.ai.chat.onDidStartTyping(() => {
  console.log('AI is typing...');
});

TraeAPI.ai.chat.onDidStopTyping(() => {
  console.log('AI finished typing');
});

Chat Sessions

Creating and Managing Sessions

typescript
// Create a new chat session
const session = await TraeAPI.ai.chat.createSession({
  title: 'Code Review Session',
  systemPrompt: 'You are a helpful code reviewer. Focus on best practices and potential improvements.'
});

// Get active session
const activeSession = TraeAPI.ai.chat.getActiveSession();

// Switch to a different session
await TraeAPI.ai.chat.setActiveSession(session.id);

// Get all sessions
const allSessions = await TraeAPI.ai.chat.getSessions();

// Delete a session
await TraeAPI.ai.chat.deleteSession(session.id);

Session Configuration

typescript
// Configure session settings
await TraeAPI.ai.chat.updateSessionConfig(session.id, {
  model: 'gpt-4',
  temperature: 0.7,
  maxTokens: 2000,
  systemPrompt: 'Updated system prompt'
});

// Get session history
const history = await TraeAPI.ai.chat.getSessionHistory(session.id);
console.log('Message count:', history.length);

Advanced Features

Code Context Integration

typescript
// Send message with current editor context
async function askAboutCurrentCode() {
  const editor = TraeAPI.window.activeTextEditor;
  if (!editor) {
    return;
  }

  const selection = editor.selection;
  const selectedText = editor.document.getText(selection);
  const fullText = editor.document.getText();
  
  const response = await TraeAPI.ai.chat.sendMessage(
    'Explain this code and suggest improvements',
    {
      context: {
        selectedText,
        fullText,
        fileName: editor.document.fileName,
        language: editor.document.languageId,
        cursorPosition: selection.start,
        workspaceFolder: TraeAPI.workspace.getWorkspaceFolder(editor.document.uri)?.name
      }
    }
  );
  
  // Display response in a custom panel
  showResponsePanel(response);
}

Custom AI Commands

typescript
// Register AI-powered commands
TraeAPI.commands.registerCommand('myExtension.explainCode', async () => {
  const editor = TraeAPI.window.activeTextEditor;
  if (!editor || editor.selection.isEmpty) {
    TraeAPI.window.showWarningMessage('Please select some code first');
    return;
  }

  const selectedCode = editor.document.getText(editor.selection);
  
  await TraeAPI.ai.chat.sendMessage(
    `Explain this ${editor.document.languageId} code:\n\n${selectedCode}`,
    {
      context: {
        action: 'explain',
        language: editor.document.languageId,
        selectedText: selectedCode
      }
    }
  );
  
  // Focus on chat panel
  await TraeAPI.commands.executeCommand('workbench.view.extension.trae-ai');
});

TraeAPI.commands.registerCommand('myExtension.generateTests', async () => {
  const editor = TraeAPI.window.activeTextEditor;
  if (!editor) {
    return;
  }

  const code = editor.document.getText();
  
  await TraeAPI.ai.chat.sendMessage(
    `Generate unit tests for this ${editor.document.languageId} code:\n\n${code}`,
    {
      context: {
        action: 'generate-tests',
        language: editor.document.languageId,
        fileName: editor.document.fileName
      }
    }
  );
});

Streaming Responses

typescript
// Handle streaming responses
const stream = TraeAPI.ai.chat.sendMessageStream(
  'Write a comprehensive guide for this API',
  {
    context: { /* context data */ }
  }
);

stream.onData((chunk) => {
  // Handle partial response
  console.log('Received chunk:', chunk.content);
  updateUI(chunk.content);
});

stream.onComplete((fullResponse) => {
  console.log('Complete response:', fullResponse.content);
  finalizeUI(fullResponse);
});

stream.onError((error) => {
  console.error('Stream error:', error);
  showErrorMessage(error.message);
});

Message Types and Formatting

Message Structure

typescript
interface ChatMessage {
  id: string;
  type: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: Date;
  context?: MessageContext;
  metadata?: MessageMetadata;
}

interface MessageContext {
  selectedText?: string;
  fileName?: string;
  language?: string;
  cursorPosition?: TraeAPI.Position;
  workspaceFolder?: string;
  action?: string;
}

Formatting Messages

typescript
// Send formatted message with code blocks
const formattedMessage = `
I need help with this TypeScript function:

\`\`\`typescript
${selectedCode}
\`\`\`

Can you help me optimize it for better performance?
`;

await TraeAPI.ai.chat.sendMessage(formattedMessage);

// Send message with markdown formatting
const markdownMessage = `
## Code Review Request

**File:** \`${fileName}\`
**Language:** ${language}

### Code:
\`\`\`${language}
${code}
\`\`\`

### Questions:
1. Are there any potential bugs?
2. How can I improve performance?
3. Does this follow best practices?
`;

await TraeAPI.ai.chat.sendMessage(markdownMessage);

Integration Examples

Code Review Assistant

typescript
class CodeReviewAssistant {
  async reviewCurrentFile() {
    const editor = TraeAPI.window.activeTextEditor;
    if (!editor) {
      return;
    }

    const document = editor.document;
    const code = document.getText();
    
    const reviewPrompt = `
Please review this ${document.languageId} file for:
- Code quality and best practices
- Potential bugs or issues
- Performance improvements
- Security considerations

\`\`\`${document.languageId}
${code}
\`\`\`
    `;

    await TraeAPI.ai.chat.sendMessage(reviewPrompt, {
      context: {
        action: 'code-review',
        fileName: document.fileName,
        language: document.languageId
      }
    });
  }

  async explainError(errorMessage: string, line: number) {
    const editor = TraeAPI.window.activeTextEditor;
    if (!editor) {
      return;
    }

    const lineText = editor.document.lineAt(line).text;
    
    const prompt = `
I'm getting this error:
\`${errorMessage}\`

On this line of ${editor.document.languageId} code:
\`\`\`${editor.document.languageId}
${lineText}
\`\`\`

Can you explain what's wrong and how to fix it?
    `;

    await TraeAPI.ai.chat.sendMessage(prompt, {
      context: {
        action: 'explain-error',
        errorMessage,
        line,
        lineText
      }
    });
  }
}

Documentation Generator

typescript
class DocumentationGenerator {
  async generateDocumentation() {
    const editor = TraeAPI.window.activeTextEditor;
    if (!editor) {
      return;
    }

    const selection = editor.selection;
    const selectedText = editor.document.getText(selection);
    
    if (!selectedText) {
      TraeAPI.window.showWarningMessage('Please select a function or class to document');
      return;
    }

    const prompt = `
Generate comprehensive documentation for this ${editor.document.languageId} code:

\`\`\`${editor.document.languageId}
${selectedText}
\`\`\`

Include:
- Description of what it does
- Parameters and their types
- Return value
- Usage examples
- Any important notes or warnings
    `;

    const response = await TraeAPI.ai.chat.sendMessage(prompt, {
      context: {
        action: 'generate-docs',
        selectedText,
        language: editor.document.languageId
      }
    });

    // Insert documentation above the selected code
    const position = selection.start;
    const documentation = `/**\n * ${response.content.replace(/\n/g, '\n * ')}\n */\n`;
    
    await editor.edit(editBuilder => {
      editBuilder.insert(position, documentation);
    });
  }
}

API Reference

Chat Methods

sendMessage()

typescript
sendMessage(
  message: string,
  options?: {
    context?: MessageContext;
    sessionId?: string;
  }
): Promise<ChatMessage>;

sendMessageStream()

typescript
sendMessageStream(
  message: string,
  options?: {
    context?: MessageContext;
    sessionId?: string;
  }
): ChatStream;

createSession()

typescript
createSession(options: {
  title?: string;
  systemPrompt?: string;
  model?: string;
}): Promise<ChatSession>;

Events

onDidReceiveMessage

typescript
onDidReceiveMessage: Event<ChatMessage>;

onDidChangeActiveSession

typescript
onDidChangeActiveSession: Event<ChatSession>;

Best Practices

  1. Provide context with your messages for better AI responses
  2. Use appropriate message formatting (markdown, code blocks)
  3. Handle errors gracefully when AI service is unavailable
  4. Respect rate limits and avoid spamming requests
  5. Cache responses when appropriate to improve performance
  6. Use streaming for long responses to improve user experience
  7. Implement proper cleanup for event listeners

Error Handling

typescript
try {
  const response = await TraeAPI.ai.chat.sendMessage('Help me with this code');
  console.log(response.content);
} catch (error) {
  if (error instanceof TraeAPI.AIServiceError) {
    TraeAPI.window.showErrorMessage(`AI service error: ${error.message}`);
  } else if (error instanceof TraeAPI.RateLimitError) {
    TraeAPI.window.showWarningMessage('Rate limit exceeded. Please try again later.');
  } else {
    console.error('Unexpected error:', error);
  }
}

Your Ultimate AI-Powered IDE Learning Guide