mock.go

195 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
// Package mock provides a mock AI provider for testing.
package mock

import (
	"context"
	"io"
	"strings"
	"time"

	"congo.gg/pkg/assistant"
)

// Config configures the mock provider behavior.
type Config struct {
	// Response is the static response to return from Chat.
	Response string

	// ToolCalls are the tool calls to return.
	ToolCalls []assistant.ToolCall

	// StreamDelay is the delay between streaming events.
	StreamDelay time.Duration

	// Error is an error to return from all calls.
	Error error
}

// backend implements assistant.Backend for testing.
type backend struct {
	config Config
}

// New creates a mock assistant for testing.
func New(config Config) *assistant.Assistant {
	return &assistant.Assistant{
		Backend: &backend{config: config},
	}
}

// Chat returns the configured response.
func (b *backend) Chat(ctx context.Context, req assistant.ChatRequest) (*assistant.ChatResponse, error) {
	if b.config.Error != nil {
		return nil, b.config.Error
	}

	return &assistant.ChatResponse{
		Content:      b.config.Response,
		ToolCalls:    b.config.ToolCalls,
		FinishReason: finishReason(b.config),
		Usage: assistant.Usage{
			PromptTokens:     countTokens(req),
			CompletionTokens: len(strings.Fields(b.config.Response)),
			TotalTokens:      countTokens(req) + len(strings.Fields(b.config.Response)),
		},
	}, nil
}

// Stream returns a stream that emits the configured response.
func (b *backend) Stream(ctx context.Context, req assistant.ChatRequest) (*assistant.StreamReader, error) {
	if b.config.Error != nil {
		return nil, b.config.Error
	}

	// Create a pipe for streaming
	pr, pw := io.Pipe()

	go func() {
		defer pw.Close()

		delay := b.config.StreamDelay
		if delay == 0 {
			delay = 10 * time.Millisecond
		}

		// Stream content word by word
		if b.config.Response != "" {
			words := strings.Fields(b.config.Response)
			for i, word := range words {
				select {
				case <-ctx.Done():
					return
				default:
				}

				if i > 0 {
					pw.Write([]byte("data: {\"type\":\"content\",\"text\":\" \"}\n\n"))
					time.Sleep(delay)
				}
				pw.Write([]byte("data: {\"type\":\"content\",\"text\":\"" + word + "\"}\n\n"))
				time.Sleep(delay)
			}
		}

		// Stream tool calls
		for _, tc := range b.config.ToolCalls {
			pw.Write([]byte("data: {\"type\":\"tool_call\",\"id\":\"" + tc.ID + "\",\"name\":\"" + tc.Name + "\",\"arguments\":\"" + escapeJSON(tc.Arguments) + "\"}\n\n"))
			time.Sleep(delay)
		}

		pw.Write([]byte("data: [DONE]\n\n"))
	}()

	return assistant.NewStreamReader(pr, parseMockEvent), nil
}

func finishReason(config Config) string {
	if len(config.ToolCalls) > 0 {
		return "tool_calls"
	}
	return "stop"
}

func countTokens(req assistant.ChatRequest) int {
	count := 0
	for _, m := range req.Messages {
		count += len(strings.Fields(m.Content))
	}
	return count
}

func escapeJSON(s string) string {
	s = strings.ReplaceAll(s, "\\", "\\\\")
	s = strings.ReplaceAll(s, "\"", "\\\"")
	s = strings.ReplaceAll(s, "\n", "\\n")
	return s
}

// parseMockEvent parses a mock SSE event.
func parseMockEvent(data string) (*assistant.StreamEvent, error) {
	// Simple mock event parsing
	if strings.Contains(data, `"type":"content"`) {
		// Extract text between "text":" and the closing "
		start := strings.Index(data, `"text":"`) + 8
		end := strings.LastIndex(data, `"`)
		if start > 8 && end > start {
			text := data[start:end]
			text = strings.ReplaceAll(text, "\\n", "\n")
			text = strings.ReplaceAll(text, "\\\"", "\"")
			text = strings.ReplaceAll(text, "\\\\", "\\")
			return &assistant.StreamEvent{
				Type:    assistant.EventContentDelta,
				Content: text,
			}, nil
		}
	}

	if strings.Contains(data, `"type":"tool_call"`) {
		// Extract tool call fields
		id := extractField(data, "id")
		name := extractField(data, "name")
		args := extractField(data, "arguments")
		args = strings.ReplaceAll(args, "\\n", "\n")
		args = strings.ReplaceAll(args, "\\\"", "\"")
		args = strings.ReplaceAll(args, "\\\\", "\\")

		return &assistant.StreamEvent{
			Type: assistant.EventToolCallStart,
			ToolCall: &assistant.ToolCall{
				ID:        id,
				Name:      name,
				Arguments: args,
			},
		}, nil
	}

	return &assistant.StreamEvent{Type: assistant.EventContentDelta}, nil
}

func extractField(data, field string) string {
	key := `"` + field + `":"`
	start := strings.Index(data, key)
	if start < 0 {
		return ""
	}
	start += len(key)
	end := start
	escaped := false
	for end < len(data) {
		if escaped {
			escaped = false
			end++
			continue
		}
		if data[end] == '\\' {
			escaped = true
			end++
			continue
		}
		if data[end] == '"' {
			break
		}
		end++
	}
	return data[start:end]
}