⚡
Go × LM Studioで挑戦!壊れないJSON&爆速応答のローカルLLM実験
1. はじめに 🎯
生成AIを「実務」で使うときに地味に大事なのが フォーマットの安定性。
JSONが壊れてパースできないと、その先の処理が一気にストップしますよね。
今回は Go言語 × LM Studio で「ローカルLLMに JSON固定出力をさせる」技術検証を行います。
しかもただのJSONじゃなくて、絵文字短縮ルール入りでユニークさも出していきます。
2. セットアップ ⚙️
LM Studio の準備
1. LM Studio をインストール(Apple Silicon Mac対応版をDL)
2. モデルとして mistral-small-3.2 を読み込み
3. Server タブから OpenAI 互換 API を起動(デフォルト: http://localhost:1234/v1)
Go プロジェクトの用意
go mod init json-test
go get github.com/joho/godotenv
.env ファイルを用意します:
LMSTUDIO_API=http://localhost:1234/v1/chat/completions
LMSTUDIO_MODEL=mistralai/mistral-small-3.2
3. 実装 (Go)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/joho/godotenv"
)
type ChatReq struct {
Model string `json:"model"`
Messages []ChatMessage `json:"messages"`
Temp float32 `json:"temperature"`
}
type ChatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatResp struct {
Choices []struct {
Message ChatMessage `json:"message"`
} `json:"choices"`
}
func main() {
err := godotenv.Load()
if err != nil {
log.Println(".env ファイルが見つかりませんでした")
}
api := os.Getenv("LMSTUDIO_API")
model := os.Getenv("LMSTUDIO_MODEL")
prompt := `次の文章を絵文字付きJSONで返してください。
入力: "会議は10時に開始します。注意事項があります"
出力例: {"emojiText": "会議は⏰10時に開始します。⚠️があります"}`
reqBody := ChatReq{
Model: model,
Messages: []ChatMessage{
{Role: "user", Content: prompt},
},
Temp: 0.2,
}
b, _ := json.Marshal(reqBody)
start := time.Now()
resp, err := http.Post(api, "application/json", bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var out ChatResp
if err := json.Unmarshal(body, &out); err != nil {
log.Fatal("JSON parse error:", err, string(body))
}
elapsed := time.Since(start)
fmt.Println("応答:", out.Choices[0].Message.Content)
fmt.Println("処理時間:", elapsed)
}
4. 実験結果 📊
% go run main.go
応答: json
{
"emojiText": "会議は⏰10時に開始します。⚠️注意事項があります"
}
処理時間: 1.707114458s
5. まとめ 🎉
- Go言語から LM Studio を叩いて JSON固定出力の安定性検証を実施
👉 辞書ルール fallback を組み合わせればさらに堅牢に。
Discussion