summaryrefslogtreecommitdiff
path: root/internal/llm/copilot.go
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2025-08-18 09:28:48 +0300
committerPaul Buetow <paul@buetow.org>2025-08-18 09:28:48 +0300
commit96ace6c7019a914e21b25fa94ddfc4ee9239c2fb (patch)
tree30550bcab30c91e917a4d8b3feccda829a364437 /internal/llm/copilot.go
parent6d29ac7e4b2604b5c7df50f33f8ef2357709faf2 (diff)
refactor(lsp,llm,hexailsp,appconfig): split long funcs; add tests
- Extract helpers to keep funcs <=50 lines; no behavior changes - Add tests for prompt removal, code actions, and LLM request builders - Table-drive TestInParamList; run gofmt
Diffstat (limited to 'internal/llm/copilot.go')
-rw-r--r--internal/llm/copilot.go166
1 files changed, 92 insertions, 74 deletions
diff --git a/internal/llm/copilot.go b/internal/llm/copilot.go
index 47ce11e..67cffc9 100644
--- a/internal/llm/copilot.go
+++ b/internal/llm/copilot.go
@@ -17,20 +17,20 @@ import (
// copilotClient implements Client against GitHub Copilot's Chat Completions API.
type copilotClient struct {
- httpClient *http.Client
- apiKey string
- baseURL string
- defaultModel string
- chatLogger logging.ChatLogger
- defaultTemperature *float64
+ httpClient *http.Client
+ apiKey string
+ baseURL string
+ defaultModel string
+ chatLogger logging.ChatLogger
+ defaultTemperature *float64
}
type copilotChatRequest struct {
- Model string `json:"model"`
- Messages []copilotMessage `json:"messages"`
- Temperature *float64 `json:"temperature,omitempty"`
- MaxTokens *int `json:"max_tokens,omitempty"`
- Stop []string `json:"stop,omitempty"`
+ Model string `json:"model"`
+ Messages []copilotMessage `json:"messages"`
+ Temperature *float64 `json:"temperature,omitempty"`
+ MaxTokens *int `json:"max_tokens,omitempty"`
+ Stop []string `json:"stop,omitempty"`
}
type copilotMessage struct {
@@ -57,20 +57,20 @@ type copilotChatResponse struct {
// Constructor (kept among the first functions by convention)
func newCopilot(baseURL, model, apiKey string, defaultTemp *float64) Client {
- if strings.TrimSpace(baseURL) == "" {
- baseURL = "https://api.githubcopilot.com"
- }
- if strings.TrimSpace(model) == "" {
- model = "gpt-4.1"
- }
- return copilotClient{
- httpClient: &http.Client{Timeout: 30 * time.Second},
- apiKey: apiKey,
- baseURL: strings.TrimRight(baseURL, "/"),
- defaultModel: model,
- chatLogger: logging.NewChatLogger("copilot"),
- defaultTemperature: defaultTemp,
- }
+ if strings.TrimSpace(baseURL) == "" {
+ baseURL = "https://api.githubcopilot.com"
+ }
+ if strings.TrimSpace(model) == "" {
+ model = "gpt-4.1"
+ }
+ return copilotClient{
+ httpClient: &http.Client{Timeout: 30 * time.Second},
+ apiKey: apiKey,
+ baseURL: strings.TrimRight(baseURL, "/"),
+ defaultModel: model,
+ chatLogger: logging.NewChatLogger("copilot"),
+ defaultTemperature: defaultTemp,
+ }
}
func (c copilotClient) Chat(ctx context.Context, messages []Message, opts ...RequestOption) (string, error) {
@@ -84,38 +84,14 @@ func (c copilotClient) Chat(ctx context.Context, messages []Message, opts ...Req
if o.Model == "" {
o.Model = c.defaultModel
}
-
start := time.Now()
- logMessages := make([]struct {
- Role string
- Content string
- }, len(messages))
+ logMessages := make([]struct{ Role, Content string }, len(messages))
for i, m := range messages {
- logMessages[i] = struct {
- Role string
- Content string
- }{Role: m.Role, Content: m.Content}
+ logMessages[i] = struct{ Role, Content string }{m.Role, m.Content}
}
c.chatLogger.LogStart(false, o.Model, o.Temperature, o.MaxTokens, o.Stop, logMessages)
- req := copilotChatRequest{Model: o.Model}
- req.Messages = make([]copilotMessage, len(messages))
- for i, m := range messages {
- req.Messages[i] = copilotMessage{Role: m.Role, Content: m.Content}
- }
- if o.Temperature != 0 {
- req.Temperature = &o.Temperature
- } else if c.defaultTemperature != nil {
- t := *c.defaultTemperature
- req.Temperature = &t
- }
- if o.MaxTokens > 0 {
- req.MaxTokens = &o.MaxTokens
- }
- if len(o.Stop) > 0 {
- req.Stop = o.Stop
- }
-
+ req := buildCopilotChatRequest(o, messages, c.defaultTemperature)
body, err := json.Marshal(req)
if err != nil {
logging.Logf("llm/copilot ", "marshal error: %v", err)
@@ -124,34 +100,19 @@ func (c copilotClient) Chat(ctx context.Context, messages []Message, opts ...Req
endpoint := c.baseURL + "/chat/completions"
logging.Logf("llm/copilot ", "POST %s", endpoint)
- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
- if err != nil {
- logging.Logf("llm/copilot ", "new request error: %v", err)
- return "", err
- }
- httpReq.Header.Set("Content-Type", "application/json")
- httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
-
- resp, err := c.httpClient.Do(httpReq)
+ resp, err := c.doJSON(ctx, endpoint, body, map[string]string{
+ "Authorization": "Bearer " + c.apiKey,
+ })
if err != nil {
logging.Logf("llm/copilot ", "%shttp error after %s: %v%s", logging.AnsiRed, time.Since(start), err, logging.AnsiBase)
return "", err
}
defer resp.Body.Close()
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- var apiErr copilotChatResponse
- _ = json.NewDecoder(resp.Body).Decode(&apiErr)
- if apiErr.Error != nil && strings.TrimSpace(apiErr.Error.Message) != "" {
- logging.Logf("llm/copilot ", "%sapi error status=%d type=%s msg=%s duration=%s%s", logging.AnsiRed, resp.StatusCode, apiErr.Error.Type, apiErr.Error.Message, time.Since(start), logging.AnsiBase)
- return "", fmt.Errorf("copilot error: %s (status %d)", apiErr.Error.Message, resp.StatusCode)
- }
- logging.Logf("llm/copilot ", "%shttp non-2xx status=%d duration=%s%s", logging.AnsiRed, resp.StatusCode, time.Since(start), logging.AnsiBase)
- return "", fmt.Errorf("copilot http error: status %d", resp.StatusCode)
+ if err := handleCopilotNon2xx(resp, start); err != nil {
+ return "", err
}
-
- var out copilotChatResponse
- if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
- logging.Logf("llm/copilot ", "%sdecode error after %s: %v%s", logging.AnsiRed, time.Since(start), err, logging.AnsiBase)
+ out, err := decodeCopilotChat(resp, start)
+ if err != nil {
return "", err
}
if len(out.Choices) == 0 {
@@ -166,3 +127,60 @@ func (c copilotClient) Chat(ctx context.Context, messages []Message, opts ...Req
// Provider metadata
func (c copilotClient) Name() string { return "copilot" }
func (c copilotClient) DefaultModel() string { return c.defaultModel }
+
+// helpers
+func buildCopilotChatRequest(o Options, messages []Message, defaultTemp *float64) copilotChatRequest {
+ req := copilotChatRequest{Model: o.Model}
+ req.Messages = make([]copilotMessage, len(messages))
+ for i, m := range messages {
+ req.Messages[i] = copilotMessage{Role: m.Role, Content: m.Content}
+ }
+ if o.Temperature != 0 {
+ req.Temperature = &o.Temperature
+ } else if defaultTemp != nil {
+ t := *defaultTemp
+ req.Temperature = &t
+ }
+ if o.MaxTokens > 0 {
+ req.MaxTokens = &o.MaxTokens
+ }
+ if len(o.Stop) > 0 {
+ req.Stop = o.Stop
+ }
+ return req
+}
+
+func (c copilotClient) doJSON(ctx context.Context, url string, body []byte, headers map[string]string) (*http.Response, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ for k, v := range headers {
+ req.Header.Set(k, v)
+ }
+ return c.httpClient.Do(req)
+}
+
+func handleCopilotNon2xx(resp *http.Response, start time.Time) error {
+ if resp.StatusCode >= 200 && resp.StatusCode < 300 {
+ return nil
+ }
+ var apiErr copilotChatResponse
+ _ = json.NewDecoder(resp.Body).Decode(&apiErr)
+ if apiErr.Error != nil && strings.TrimSpace(apiErr.Error.Message) != "" {
+ logging.Logf("llm/copilot ", "%sapi error status=%d type=%s msg=%s duration=%s%s", logging.AnsiRed, resp.StatusCode, apiErr.Error.Type, apiErr.Error.Message, time.Since(start), logging.AnsiBase)
+ return fmt.Errorf("copilot error: %s (status %d)", apiErr.Error.Message, resp.StatusCode)
+ }
+ logging.Logf("llm/copilot ", "%shttp non-2xx status=%d duration=%s%s", logging.AnsiRed, resp.StatusCode, time.Since(start), logging.AnsiBase)
+ return fmt.Errorf("copilot http error: status %d", resp.StatusCode)
+}
+
+func decodeCopilotChat(resp *http.Response, start time.Time) (copilotChatResponse, error) {
+ var out copilotChatResponse
+ if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
+ logging.Logf("llm/copilot ", "%sdecode error after %s: %v%s", logging.AnsiRed, time.Since(start), err, logging.AnsiBase)
+ return copilotChatResponse{}, err
+ }
+ return out, nil
+}