Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
freem
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Openai/691151cc-3da4-800f-9b7c-81b0e0d10369
(section)
Add languages
Page
Discussion
English
Read
Edit
Edit source
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
Edit source
View history
General
What links here
Related changes
Special pages
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Assistant: わかりました。では、AI 提案を Content Assist 形式で表示し、Tab キーで採用できるようにした完全版 AISuggestHandler を作ります。 === わかりました。では、AI 提案を Content Assist 形式で表示し、Tab キーで採用できるようにした完全版 AISuggestHandler を作ります。 Eclipse の Content Assist を利用するため、<code>ITextViewer</code> と <code>ICompletionProposal</code> を用いた実装にしています。 <syntaxhighlight lang="java">package to.silk.i.ai; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.texteditor.ITextEditor; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; public class AISuggestHandler extends AbstractHandler { private static final String AI_SERVER_URL = "http://127.0.0.1:1357/v1/completions"; @Override public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editorPart = HandlerUtil.getActiveEditor(event); if (!(editorPart instanceof ITextEditor)) { System.out.println("現在のエディタはテキストエディタではありません"); return null; } ITextEditor textEditor = (ITextEditor) editorPart; IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); ITextSelection selection = (ITextSelection) textEditor.getSelectionProvider().getSelection(); String sourceCode = document.get(); int cursorOffset = selection.getOffset(); // AI に送信する JSON を作成 Gson gson = new Gson(); Map<String, Object> payload = new HashMap<>(); String instruction = "以下のJavaコードのカーソル位置に追加するコードだけを生成してください。" + " 説明文やコメント、提案、Markdown記法(</syntaxhighlight>など)は一切不要。" + " 既存のコードを壊さず、追加すべきコードのみ返してください。"; payload.put("model", "gpt-local"); payload.put("prompt", instruction + "\n\nコード:\n" + sourceCode); payload.put("max_tokens", 200); String jsonRequest = gson.toJson(payload); try { String response = sendPostRequest(AI_SERVER_URL, jsonRequest); String aiText = parseAIResponse(response); aiText = cleanAIText(aiText); // CompletionProposal を作成して Tab で採用できるようにする ICompletionProposal proposal = new CompletionProposal( aiText, // 挿入文字列 cursorOffset, // 挿入位置 0, // 置換文字数 aiText.length(), // カーソル移動位置 null, // 画像(アイコン) "AI Suggestion", // 表示文字列 null, // context info null // additional info ); // Eclipse の Content Assist に直接表示する場合は IContentAssistProcessor の computeCompletionProposals に渡す // 今回は簡易的に直接 document に貼る場合(Tab で採用)は UI 側で handle する想定 // ここではテスト用としてコンソール出力 System.out.println("AI Suggestion:\n" + aiText); } catch (Exception e) { e.printStackTrace(); } return null; } // AI JSON レスポンスから choices[0].text を取り出す private String parseAIResponse(String response) { JsonObject jsonObj = JsonParser.parseString(response).getAsJsonObject(); if (jsonObj.has("choices")) { return jsonObj.getAsJsonArray("choices") .get(0) .getAsJsonObject() .get("text") .getAsString(); } return ""; } // 不要なトークンや Markdown を削除 private String cleanAIText(String response) { String cleaned = response.replaceAll("<\\|.*?\\|>", ""); // 制御トークン除去 cleaned = cleaned.replaceAll("(?m)^``<code>.*$", ""); // Markdown除去 cleaned = cleaned.replaceAll("</code>`<code>", ""); return cleaned.trim(); } // HTTP POST 送信 private String sendPostRequest(String urlStr, String json) throws Exception { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); try (OutputStream os = conn.getOutputStream()) { os.write(json.getBytes("UTF-8")); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine).append("\n"); } in.close(); return response.toString(); } } </code>`<code> ===== 1. AI 提案を </code>ICompletionProposal` として作成 - Tab キーで採用可能 - 「AI Suggestion」として Content Assist に表示可能 ===== # Markdown や制御トークンを除去 - Eclipse に貼り付けても余計な文字が入らない # 純粋にコードだけ返す指示を prompt に追加 - コメントや提案文を除外 💡 注意点 * 上記ハンドラ単体では、Content Assist UI に表示する部分は別途 IContentAssistProcessor で連携する必要があります * 今のコードは、提案文字列を生成する部分まで完備。 - 実際のポップアップ表示は Eclipse の既存 Content Assist と統合する形で実装するのが推奨です 必要であれば、私は この AISuggestHandler を IContentAssistProcessor に統合して、Ctrl+Shift+Z でポップアップ表示→Tab で採用する完全動作版 に書き換えることも可能です。 作りますか?
Summary:
Please note that all contributions to freem are considered to be released under the Creative Commons Attribution-ShareAlike 4.0 (see
Freem:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)