AIチャットAPI
AIチャットAPIは、拡張機能がAIアシスタントと対話し、コンテキストを認識した支援を提供できるようにします。
概要
AIチャットAPIでは以下のことができます:
- AIアシスタントとの会話セッションを開始
- コードやプロジェクトのコンテキストを提供
- 自然言語でコード関連の質問をする
- AIからコード提案や説明を受け取る
- 会話履歴を管理
- カスタムAIプロンプトを作成
基本的な使用方法
シンプルなチャット
typescript
import { TraeAPI } from '@trae/api';
// AIチャットセッションを開始
const chatSession = await TraeAPI.ai.chat.createSession({
model: 'gpt-4',
systemPrompt: 'あなたは親切なコーディングアシスタントです。',
temperature: 0.7
});
// メッセージを送信
const response = await chatSession.sendMessage('TypeScriptでHTTPサーバーを作成する方法を教えて');
console.log('AI応答:', response.content);
console.log('信頼度:', response.confidence);コンテキスト付きチャット
typescript
// 現在のファイルをコンテキストとして追加
const editor = TraeAPI.window.activeTextEditor;
if (editor) {
const document = editor.document;
const chatSession = await TraeAPI.ai.chat.createSession({
model: 'gpt-4',
context: {
files: [{
path: document.fileName,
content: document.getText(),
language: document.languageId
}],
selection: {
start: editor.selection.start,
end: editor.selection.end,
text: document.getText(editor.selection)
}
}
});
const response = await chatSession.sendMessage('このコードを説明して');
}高度な機能
会話履歴の管理
typescript
// 会話履歴を取得
const history = await chatSession.getHistory();
console.log('会話履歴:', history);
// 特定のメッセージを削除
await chatSession.deleteMessage(messageId);
// 会話をクリア
await chatSession.clearHistory();
// 会話を保存
const savedSession = await chatSession.save('my-coding-session');
// 保存された会話を読み込み
const loadedSession = await TraeAPI.ai.chat.loadSession('my-coding-session');ストリーミング応答
typescript
// ストリーミングでリアルタイム応答を受信
const stream = await chatSession.sendMessageStream('大きなクラスをリファクタリングして');
stream.on('data', (chunk) => {
console.log('部分応答:', chunk.content);
// UIをリアルタイムで更新
updateChatUI(chunk.content);
});
stream.on('end', (finalResponse) => {
console.log('完全な応答:', finalResponse.content);
});
stream.on('error', (error) => {
console.error('ストリーミングエラー:', error);
});カスタムプロンプトテンプレート
typescript
// プロンプトテンプレートを作成
const codeReviewTemplate = TraeAPI.ai.chat.createPromptTemplate({
name: 'code-review',
template: `
以下のコードをレビューしてください:
言語: {{language}}
ファイル: {{filename}}
\`\`\`{{language}}
{{code}}
\`\`\`
以下の観点でレビューしてください:
- コードの品質
- パフォーマンス
- セキュリティ
- ベストプラクティス
改善提案があれば具体的なコード例も提供してください。
`,
variables: ['language', 'filename', 'code']
});
// テンプレートを使用
const response = await chatSession.sendMessage(
codeReviewTemplate.render({
language: 'typescript',
filename: 'user-service.ts',
code: selectedCode
})
);専門的なチャット機能
コード生成チャット
typescript
// コード生成専用のチャットセッション
const codeGenSession = await TraeAPI.ai.chat.createCodeGenerationSession({
language: 'typescript',
framework: 'react',
style: 'functional-components'
});
// コンポーネント生成を依頼
const componentResponse = await codeGenSession.generateComponent({
name: 'UserProfile',
props: ['name', 'email', 'avatar'],
features: ['edit-mode', 'validation']
});
// 生成されたコードを挿入
const editor = TraeAPI.window.activeTextEditor;
if (editor) {
await editor.edit(editBuilder => {
editBuilder.insert(editor.selection.active, componentResponse.code);
});
}デバッグアシスタント
typescript
// デバッグ専用チャットセッション
const debugSession = await TraeAPI.ai.chat.createDebugSession({
language: 'typescript',
debugInfo: {
stackTrace: currentStackTrace,
variables: currentVariables,
breakpoints: activeBreakpoints
}
});
// エラーの分析を依頼
const analysis = await debugSession.analyzeError({
error: errorMessage,
code: problematicCode,
context: surroundingCode
});
console.log('エラー分析:', analysis.explanation);
console.log('修正提案:', analysis.suggestions);ドキュメント生成チャット
typescript
// ドキュメント生成専用セッション
const docSession = await TraeAPI.ai.chat.createDocumentationSession({
format: 'jsdoc',
includeExamples: true,
includeTypes: true
});
// 関数のドキュメントを生成
const docResponse = await docSession.generateDocumentation({
code: functionCode,
language: 'typescript',
type: 'function'
});
// ドキュメントを挿入
const editor = TraeAPI.window.activeTextEditor;
if (editor) {
const position = editor.selection.start;
await editor.edit(editBuilder => {
editBuilder.insert(position, docResponse.documentation + '\n');
});
}チャットUI統合
カスタムチャットパネル
typescript
// カスタムチャットパネルを作成
const chatPanel = TraeAPI.window.createWebviewPanel(
'ai-chat',
'AIアシスタント',
TraeAPI.ViewColumn.Beside,
{
enableScripts: true,
retainContextWhenHidden: true
}
);
// チャットUIのHTML
chatPanel.webview.html = `
<!DOCTYPE html>
<html>
<head>
<title>AIチャット</title>
<style>
.chat-container { height: 100vh; display: flex; flex-direction: column; }
.messages { flex: 1; overflow-y: auto; padding: 10px; }
.input-area { padding: 10px; border-top: 1px solid #ccc; }
.message { margin: 10px 0; padding: 10px; border-radius: 5px; }
.user-message { background: #007acc; color: white; margin-left: 20%; }
.ai-message { background: #f0f0f0; margin-right: 20%; }
</style>
</head>
<body>
<div class="chat-container">
<div id="messages" class="messages"></div>
<div class="input-area">
<input type="text" id="messageInput" placeholder="メッセージを入力..." style="width: 80%;">
<button onclick="sendMessage()" style="width: 18%;">送信</button>
</div>
</div>
<script>
const vscode = acquireVsCodeApi();
function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (message) {
addMessage(message, 'user');
vscode.postMessage({ command: 'sendMessage', text: message });
input.value = '';
}
}
function addMessage(text, sender) {
const messagesDiv = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = \`message \${sender}-message\`;
messageDiv.textContent = text;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
window.addEventListener('message', event => {
const message = event.data;
if (message.command === 'addAIMessage') {
addMessage(message.text, 'ai');
}
});
document.getElementById('messageInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
`;
// メッセージハンドラー
chatPanel.webview.onDidReceiveMessage(async (message) => {
if (message.command === 'sendMessage') {
const response = await chatSession.sendMessage(message.text);
chatPanel.webview.postMessage({
command: 'addAIMessage',
text: response.content
});
}
});インラインチャット
typescript
// エディター内でインラインチャットを表示
const inlineChat = await TraeAPI.window.showInlineChat({
position: editor.selection.active,
placeholder: 'AIに質問する...',
context: {
selectedText: editor.document.getText(editor.selection),
language: editor.document.languageId
}
});
inlineChat.onDidAcceptInput(async (input) => {
const response = await chatSession.sendMessage(input);
// 応答をエディターに挿入
await editor.edit(editBuilder => {
editBuilder.insert(editor.selection.active, response.content);
});
inlineChat.hide();
});高度な設定
モデル設定
typescript
// 異なるAIモデルを使用
const sessions = {
coding: await TraeAPI.ai.chat.createSession({
model: 'gpt-4-turbo',
temperature: 0.3, // より正確な応答
maxTokens: 2048
}),
creative: await TraeAPI.ai.chat.createSession({
model: 'gpt-4',
temperature: 0.8, // より創造的な応答
maxTokens: 1024
}),
fast: await TraeAPI.ai.chat.createSession({
model: 'gpt-3.5-turbo',
temperature: 0.5, // バランスの取れた応答
maxTokens: 512
})
};
// 用途に応じてセッションを選択
const response = await sessions.coding.sendMessage('このアルゴリズムを最適化して');コンテキスト管理
typescript
// 動的コンテキスト更新
class ContextManager {
private context: ChatContext = {};
async updateContext() {
const editor = TraeAPI.window.activeTextEditor;
if (editor) {
this.context.currentFile = {
path: editor.document.fileName,
content: editor.document.getText(),
language: editor.document.languageId,
selection: editor.document.getText(editor.selection)
};
}
// プロジェクト情報を追加
this.context.project = {
name: TraeAPI.workspace.name,
files: await this.getRelevantFiles(),
dependencies: await this.getProjectDependencies()
};
// Git情報を追加
this.context.git = {
branch: await this.getCurrentBranch(),
recentCommits: await this.getRecentCommits()
};
}
async getRelevantFiles(): Promise<string[]> {
const files = await TraeAPI.workspace.findFiles('**/*.{ts,js,tsx,jsx}', '**/node_modules/**');
return files.slice(0, 10).map(file => file.fsPath); // 最初の10ファイル
}
getContext(): ChatContext {
return this.context;
}
}
const contextManager = new ContextManager();
await contextManager.updateContext();
const chatSession = await TraeAPI.ai.chat.createSession({
model: 'gpt-4',
context: contextManager.getContext()
});カスタムAIプロバイダー
typescript
// カスタムAIプロバイダーを登録
TraeAPI.ai.chat.registerProvider('custom-ai', {
async createSession(options: ChatSessionOptions): Promise<ChatSession> {
return new CustomChatSession(options);
},
async getModels(): Promise<string[]> {
return ['custom-model-1', 'custom-model-2'];
},
async validateApiKey(apiKey: string): Promise<boolean> {
// APIキーの検証ロジック
return true;
}
});
// カスタムプロバイダーを使用
const customSession = await TraeAPI.ai.chat.createSession({
provider: 'custom-ai',
model: 'custom-model-1'
});APIリファレンス
ChatSession
typescript
interface ChatSession {
// メッセージ送信
sendMessage(message: string, options?: MessageOptions): Promise<ChatResponse>;
sendMessageStream(message: string, options?: MessageOptions): Promise<ChatStream>;
// 履歴管理
getHistory(): Promise<ChatMessage[]>;
deleteMessage(messageId: string): Promise<void>;
clearHistory(): Promise<void>;
// セッション管理
save(name: string): Promise<SavedSession>;
load(name: string): Promise<void>;
close(): Promise<void>;
// コンテキスト管理
updateContext(context: ChatContext): Promise<void>;
getContext(): ChatContext;
}ChatResponse
typescript
interface ChatResponse {
content: string;
confidence: number;
model: string;
usage: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
metadata?: {
reasoning?: string;
sources?: string[];
suggestions?: string[];
};
}ChatContext
typescript
interface ChatContext {
files?: FileContext[];
selection?: SelectionContext;
project?: ProjectContext;
git?: GitContext;
custom?: Record<string, any>;
}
interface FileContext {
path: string;
content: string;
language: string;
selection?: string;
}ベストプラクティス
- 適切なコンテキストを提供してより正確な応答を得る
- 会話履歴を管理してメモリ使用量を制御
- ストリーミング応答を使用してユーザー体験を向上
- エラーハンドリングを適切に実装
- APIキーを安全に管理する
- レート制限を考慮してリクエストを調整
- ユーザーのプライバシーを保護する
エラーハンドリング
typescript
try {
const response = await chatSession.sendMessage('コードを説明して');
console.log(response.content);
} catch (error) {
if (error instanceof TraeAPI.AIError) {
switch (error.code) {
case 'RATE_LIMIT_EXCEEDED':
TraeAPI.window.showWarningMessage('レート制限に達しました。しばらく待ってから再試行してください。');
break;
case 'INVALID_API_KEY':
TraeAPI.window.showErrorMessage('APIキーが無効です。設定を確認してください。');
break;
case 'CONTEXT_TOO_LARGE':
TraeAPI.window.showWarningMessage('コンテキストが大きすぎます。選択範囲を小さくしてください。');
break;
default:
TraeAPI.window.showErrorMessage(`AI エラー: ${error.message}`);
}
} else {
console.error('予期しないエラー:', error);
}
}関連API
- Editor API - エディター統合用
- Workspace API - ワークスペース情報用