~kris/9p

llm9p

ref: 43312541d2dbe1beabd1050d2ae8d3c828f234c9 llm9p/internal/llmfs/ask.go -rw-r--r-- 1.6 KiB
43312541 — pdfinn docs: Update README to reflect pluggable backend architecture 7 months ago
                                                                                
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
package llmfs

import (
	"context"
	"io"
	"strings"
	"sync"

	"github.com/NERVsystems/llm9p/internal/llm"
	"github.com/NERVsystems/llm9p/internal/protocol"
)

// AskFile is the main interaction file - write a prompt, read the response
type AskFile struct {
	*protocol.BaseFile
	client       llm.Backend
	mu           sync.RWMutex
	lastResponse string
}

// NewAskFile creates the ask file
func NewAskFile(client llm.Backend) *AskFile {
	return &AskFile{
		BaseFile: protocol.NewBaseFile("ask", 0666),
		client:   client,
	}
}

func (f *AskFile) Read(p []byte, offset int64) (int, error) {
	f.mu.RLock()
	content := f.lastResponse
	f.mu.RUnlock()

	// Add newline if not present
	if content != "" && !strings.HasSuffix(content, "\n") {
		content += "\n"
	}

	if offset >= int64(len(content)) {
		return 0, io.EOF
	}
	n := copy(p, content[offset:])
	return n, nil
}

func (f *AskFile) Write(p []byte, offset int64) (int, error) {
	prompt := strings.TrimSpace(string(p))
	if prompt == "" {
		return len(p), nil // Empty write is a no-op
	}

	// Make the API call
	response, err := f.client.Ask(context.Background(), prompt)
	if err != nil {
		// Store error as response so it can be read
		f.mu.Lock()
		f.lastResponse = "Error: " + err.Error()
		f.mu.Unlock()
		return len(p), nil // Return success so client knows write completed
	}

	f.mu.Lock()
	f.lastResponse = response
	f.mu.Unlock()

	return len(p), nil
}

func (f *AskFile) Stat() protocol.Stat {
	s := f.BaseFile.Stat()
	f.mu.RLock()
	content := f.lastResponse
	f.mu.RUnlock()
	if content != "" && !strings.HasSuffix(content, "\n") {
		content += "\n"
	}
	s.Length = uint64(len(content))
	return s
}