chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,64 @@
|
||||
# Chat attachment boundaries
|
||||
|
||||
Attachments remain readable without a sandbox. Durable storage and the temporary-document
|
||||
row are authoritative; sandbox files are disposable copies.
|
||||
|
||||
| Responsibility | Owner |
|
||||
| --- | --- |
|
||||
| Upload, session access, retention, task scheduling | `service/temporary_document.go` |
|
||||
| Parser, OCR, image extraction, chunking | `service/temporary_document_parse.go` |
|
||||
| Quick Answer excerpts and Agent attachment manifest | `service/temporary_document_prompt.go` |
|
||||
| Authorized reads, bounded parse waits | `attachment/Reader` |
|
||||
| Image preparation, scoped observations and reuse | `attachment/ImageReader` |
|
||||
| Observation persistence and concurrent updates | `repository/attachment_descriptions.go` |
|
||||
| Turn-start original/parsed-file reconciliation | `service/session_attachment_staging.go` |
|
||||
| Copies produced by a successful read | `service/attachment_sandbox.go` |
|
||||
| URI routing, pagination, image numbering and tool output | `agent/tools/read_file_attachment.go` |
|
||||
| Vision transport and fallback for other tools | `agent/engine.go`, `agent/tool_images.go` |
|
||||
|
||||
`agent_attachments.go` wires session-scoped storage adapters into `Reader`, then
|
||||
passes only `interfaces.AttachmentReader` to `read_file`. The reader authorizes
|
||||
against persisted message attachments before looking up the tenant's document,
|
||||
including documents inherited from a parent session. Neither the tool nor the
|
||||
Agent engine queries attachment repositories.
|
||||
|
||||
## Read and synchronization flow
|
||||
|
||||
1. At turn start, stage originals and already-ready parsed text if the selected
|
||||
sandbox supports session input files. Host workspaces have no input directory
|
||||
and are never used for attachment staging.
|
||||
2. `read_file attachment://...` resolves the session attachment and waits within
|
||||
the configured parse budget. A successful read projects newly-ready parsed
|
||||
text immediately, including when parsing finished after turn-start staging.
|
||||
3. Image reads default to one image with `brief` plus an optional `focus`.
|
||||
Use complete `attachment://<handle>/images/N` addresses, never bare `/images/N`.
|
||||
Exact chart/table values and calculations use `full` with a focused question;
|
||||
full reads return at most one image. Explicit brief batches are capped at four.
|
||||
Observations preserve category, series and unit alongside each value. Missing
|
||||
associations or inconsistent totals require a focused re-read, not guessed data.
|
||||
4. Non-vision chat models use the configured VLM. Successful observations are
|
||||
keyed by document, prepared-image hash, model ID and normalized reading prompt
|
||||
(including detail/focus). Equal requests reuse the observation across turns
|
||||
and authorized forks; different requirements do not reuse a narrower answer.
|
||||
Descriptions have a 60-second deadline (150 seconds for full reads), starting
|
||||
after a model slot is acquired. Failed or empty descriptions
|
||||
are not cached, and the engine does not repeat an attempted description.
|
||||
5. The document metadata stores a bounded observation cache through optimistic
|
||||
updates that preserve parser metadata and concurrent writes. Cache entries
|
||||
inherit the document's deletion and retention rules. They are not merged into
|
||||
parsed Markdown or presented as exhaustive OCR.
|
||||
6. After an image read, copy the prepared image and any available observation to
|
||||
`<original>.assets/`. Tool results expose the paths, and observations carry
|
||||
their source, detail, focus, model and timestamp. Normal turn-start staging
|
||||
preserves these files while the original belongs to the session. After a
|
||||
sandbox rebuild, the next read recreates copies from durable data/cache.
|
||||
|
||||
No sandbox is needed for steps 2–5. Projection failures are reported separately
|
||||
and do not turn a successful durable read into a failure. Native vision sends
|
||||
images directly to the chat model and copies the image if a sandbox is present;
|
||||
it does not perform an extra VLM call just to manufacture a cached observation.
|
||||
|
||||
The cache reuses observations for the same model ID and prompt, not arbitrary
|
||||
semantic similarity between focus strings. Raw VLM reasoning from a native vision
|
||||
response is not an attachment artifact. These boundaries keep cache scope explicit
|
||||
and avoid speculative re-reading of every extracted image.
|
||||
@@ -0,0 +1,183 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/models/imageprep"
|
||||
"academy/internal/searchutil"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
const (
|
||||
// Deadlines start once a VLM slot is held, so queueing behind other reads
|
||||
// does not eat into the model's time. Full transcriptions run longer.
|
||||
imageDescribeTimeout = 60 * time.Second
|
||||
imageDescribeFullTimeout = 150 * time.Second
|
||||
imageDescribeSlots = 4
|
||||
)
|
||||
|
||||
// Description records the scope of an observation; it is never merged into
|
||||
// parsed document text or treated as a complete reading of the image.
|
||||
type Description struct {
|
||||
Text string `json:"text"`
|
||||
Detail string `json:"detail"`
|
||||
Focus string `json:"focus,omitempty"`
|
||||
Model string `json:"model"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// DescriptionCache persists scoped observations alongside their owning document.
|
||||
type DescriptionCache interface {
|
||||
Get(ctx context.Context, documentID, key string) (*Description, error)
|
||||
Put(ctx context.Context, documentID, key string, value Description) error
|
||||
}
|
||||
|
||||
// Projection is optional. The durable document and cache remain usable when
|
||||
// the sandbox is absent, expires, or fails to accept a copy.
|
||||
type Projection interface {
|
||||
Document(context.Context, *types.TemporaryDocument) (string, error)
|
||||
Image(
|
||||
ctx context.Context, doc *types.TemporaryDocument, number int,
|
||||
data []byte, mime, key string, description *Description,
|
||||
) (map[string]string, error)
|
||||
}
|
||||
|
||||
// ImageReader describes requested images and reuses equivalent prior observations.
|
||||
type ImageReader struct {
|
||||
Model string
|
||||
Describe func(context.Context, []byte, string) (string, error)
|
||||
Cache DescriptionCache
|
||||
calls singleflight.Group
|
||||
slotsOnce sync.Once
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
// ReadImages authorizes the document once, then prepares, describes and
|
||||
// projects the requested images concurrently.
|
||||
func (r *Reader) ReadImages(
|
||||
ctx context.Context, documentID string, numbers []int, detail, focus string,
|
||||
) ([]interfaces.AttachmentImageRead, error) {
|
||||
resolved, err := r.Resolve(ctx, documentID, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc := resolved.Document
|
||||
if doc == nil || doc.Status != types.TemporaryDocumentStatusReady {
|
||||
return nil, fmt.Errorf("attachment is not ready")
|
||||
}
|
||||
if r.readImage == nil {
|
||||
return nil, fmt.Errorf("attachment image storage is unavailable")
|
||||
}
|
||||
images := doc.ViewableImages()
|
||||
reads := make([]interfaces.AttachmentImageRead, len(numbers))
|
||||
var wg sync.WaitGroup
|
||||
for i, number := range numbers {
|
||||
reads[i].Number = number
|
||||
if number < 1 || number > len(images) {
|
||||
reads[i].Err = fmt.Errorf("image number out of range")
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
reads[i].Image, reads[i].Err = r.readImageAt(ctx, doc, number, images[number-1].URL, detail, focus)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return reads, nil
|
||||
}
|
||||
|
||||
func (r *Reader) readImageAt(
|
||||
ctx context.Context, doc *types.TemporaryDocument, number int, url, detail, focus string,
|
||||
) (*interfaces.AttachmentImage, error) {
|
||||
data, err := r.readImage(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prepared, err := imageprep.Prepare(data, searchutil.VisionImageLimits)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to prepare image %d: %w", number, err)
|
||||
}
|
||||
result := &interfaces.AttachmentImage{DataURI: prepared.DataURI()}
|
||||
var description *Description
|
||||
var key string
|
||||
if r.Images != nil && r.Images.Describe != nil {
|
||||
text := ""
|
||||
result.Description = &text
|
||||
description, key, err = r.Images.describe(ctx, doc.ID, prepared.Data, detail, focus)
|
||||
if description != nil {
|
||||
*result.Description = description.Text
|
||||
}
|
||||
if err != nil {
|
||||
result.Warning = "Image description: " + err.Error()
|
||||
}
|
||||
}
|
||||
if r.Projection != nil {
|
||||
result.Files, err = r.Projection.Image(ctx, doc, number, prepared.Data, prepared.MIMEType, key, description)
|
||||
if err != nil {
|
||||
result.Warning = strings.TrimSpace(result.Warning + " Could not sync image to sandbox: " + err.Error())
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *ImageReader) describe(
|
||||
ctx context.Context, documentID string, data []byte, detail, focus string,
|
||||
) (*Description, string, error) {
|
||||
detail, focus = types.NormalizeImageRead(detail, focus)
|
||||
prompt := types.ImageReadPrompt(detail, focus)
|
||||
identity, _ := json.Marshal([]string{r.Model, prompt, fmt.Sprintf("%x", sha256.Sum256(data))})
|
||||
key := fmt.Sprintf("%x", sha256.Sum256(identity))
|
||||
timeout := imageDescribeTimeout
|
||||
if detail == types.ImageDetailFull {
|
||||
timeout = imageDescribeFullTimeout
|
||||
}
|
||||
// Coalesce duplicate reads in one engine; the durable cache also serves
|
||||
// subsequent turns and forked sessions after their own authorization.
|
||||
// The shared call is detached from whichever caller started it, so one
|
||||
// caller giving up cannot fail the others waiting on the same image.
|
||||
shared := context.WithoutCancel(ctx)
|
||||
result := r.calls.DoChan(documentID+":"+key, func() (interface{}, error) {
|
||||
if r.Cache != nil {
|
||||
cached, err := r.Cache.Get(shared, documentID, key)
|
||||
if err == nil && cached != nil {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
r.slotsOnce.Do(func() { r.slots = make(chan struct{}, imageDescribeSlots) })
|
||||
r.slots <- struct{}{}
|
||||
defer func() { <-r.slots }()
|
||||
imageCtx, cancel := context.WithTimeout(shared, timeout)
|
||||
defer cancel()
|
||||
text, err := r.Describe(imageCtx, data, prompt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return nil, fmt.Errorf("vision model returned no description")
|
||||
}
|
||||
value := &Description{Text: text, Detail: detail, Focus: focus, Model: r.Model, CreatedAt: time.Now().UTC()}
|
||||
if r.Cache != nil {
|
||||
if err := r.Cache.Put(shared, documentID, key, *value); err != nil {
|
||||
return value, fmt.Errorf("save description: %w", err)
|
||||
}
|
||||
}
|
||||
return value, nil
|
||||
})
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, key, ctx.Err()
|
||||
case value := <-result:
|
||||
description, _ := value.Val.(*Description)
|
||||
return description, key, value.Err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Package attachment owns session-authorized attachment reads. It has no agent,
|
||||
// tool, database or sandbox dependency; adapters supply storage and projections.
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
const pollInterval = 500 * time.Millisecond
|
||||
|
||||
// Store supplies the session inventory and tenant-scoped document lookup.
|
||||
type Store interface {
|
||||
SessionAttachments(context.Context) (types.MessageAttachments, error)
|
||||
TemporaryDocument(context.Context, string) (*types.TemporaryDocument, error)
|
||||
}
|
||||
|
||||
// Reader coordinates authorized attachment reads independently of tools and sandboxes.
|
||||
type Reader struct {
|
||||
store Store
|
||||
parseWait time.Duration
|
||||
readImage func(context.Context, string) ([]byte, error)
|
||||
Images *ImageReader
|
||||
Projection Projection
|
||||
}
|
||||
|
||||
// NewReader binds durable storage to one conversation and its parse wait budget.
|
||||
func NewReader(store Store, wait time.Duration, readImage func(context.Context, string) ([]byte, error)) *Reader {
|
||||
return &Reader{store: store, parseWait: wait, readImage: readImage}
|
||||
}
|
||||
|
||||
// WaitTimeout bounds parsing plus one image batch: the batch is described
|
||||
// concurrently, with room for one queue round behind other reads.
|
||||
func (r *Reader) WaitTimeout() time.Duration {
|
||||
wait := r.parseWait
|
||||
if r.Images != nil && r.Images.Describe != nil {
|
||||
wait += imageDescribeFullTimeout + imageDescribeTimeout
|
||||
}
|
||||
return wait
|
||||
}
|
||||
|
||||
// List loads the authorized inventory once, then resolves each document without
|
||||
// waiting or projecting files. Listing must not reload the message history per item.
|
||||
func (r *Reader) List(ctx context.Context) ([]interfaces.AttachmentDocument, error) {
|
||||
inventory, err := r.inventory(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]interfaces.AttachmentDocument, 0, len(inventory))
|
||||
for _, item := range inventory {
|
||||
doc, err := r.store.TemporaryDocument(ctx, item.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load attachment %s: %w", item.ID, err)
|
||||
}
|
||||
out = append(out, interfaces.AttachmentDocument{Attachment: item, Document: doc})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Resolve opens a session attachment, optionally waiting for parsing and syncing its text.
|
||||
func (r *Reader) Resolve(ctx context.Context, ref string, wait bool) (*interfaces.AttachmentDocument, error) {
|
||||
inventory, err := r.inventory(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item, err := findAttachment(inventory, ref)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", interfaces.ErrAttachmentNotFound, err)
|
||||
}
|
||||
var doc *types.TemporaryDocument
|
||||
if wait {
|
||||
doc, err = r.awaitDocument(ctx, item.ID)
|
||||
} else {
|
||||
doc, err = r.store.TemporaryDocument(ctx, item.ID)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &interfaces.AttachmentDocument{Attachment: item, Document: doc}
|
||||
if wait && doc != nil && doc.Status == types.TemporaryDocumentStatusReady && r.Projection != nil {
|
||||
result.ParsedPath, err = r.Projection.Document(ctx, doc)
|
||||
if err != nil {
|
||||
result.Warning = "Could not sync parsed text to sandbox: " + err.Error()
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// inventory returns the session's stored attachments, deduplicated by ID.
|
||||
// Inline uploads without a stored document have nothing to read and are left
|
||||
// out.
|
||||
func (r *Reader) inventory(ctx context.Context) (types.MessageAttachments, error) {
|
||||
if r.store == nil {
|
||||
return nil, fmt.Errorf("attachments are unavailable")
|
||||
}
|
||||
all, err := r.store.SessionAttachments(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load conversation attachments: %w", err)
|
||||
}
|
||||
seen := make(map[string]int, len(all))
|
||||
out := make(types.MessageAttachments, 0, len(all))
|
||||
for _, attachment := range all {
|
||||
id := strings.TrimSpace(attachment.ID)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if i, ok := seen[id]; ok {
|
||||
// Later rows carry the content persisted after resolution.
|
||||
if out[i].Content == "" {
|
||||
out[i] = attachment
|
||||
}
|
||||
continue
|
||||
}
|
||||
seen[id] = len(out)
|
||||
out = append(out, attachment)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func findAttachment(inventory types.MessageAttachments, ref string) (types.MessageAttachment, error) {
|
||||
ref = strings.TrimSpace(ref)
|
||||
var byName []types.MessageAttachment
|
||||
for _, attachment := range inventory {
|
||||
if types.AttachmentHandle(attachment.ID) == ref || attachment.ID == ref {
|
||||
return attachment, nil
|
||||
}
|
||||
if strings.EqualFold(attachment.FileName, ref) {
|
||||
byName = append(byName, attachment)
|
||||
}
|
||||
}
|
||||
if len(byName) > 0 {
|
||||
return byName[len(byName)-1], nil
|
||||
}
|
||||
paths := make([]string, 0, len(inventory))
|
||||
for _, attachment := range inventory {
|
||||
paths = append(paths, fmt.Sprintf("%s (%s)", types.AttachmentPath(attachment.ID), attachment.FileName))
|
||||
}
|
||||
if len(paths) == 0 {
|
||||
return types.MessageAttachment{}, fmt.Errorf("this conversation has no readable attachments")
|
||||
}
|
||||
return types.MessageAttachment{}, fmt.Errorf(
|
||||
"unknown attachment %q; available: %s", ref, strings.Join(paths, ", "))
|
||||
}
|
||||
|
||||
// awaitDocument loads the document, polling while it is still being parsed
|
||||
// until parseWait elapses or ctx is cancelled.
|
||||
func (r *Reader) awaitDocument(ctx context.Context, id string) (*types.TemporaryDocument, error) {
|
||||
deadline := time.Now().Add(r.parseWait)
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
document, err := r.store.TemporaryDocument(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load attachment: %w", err)
|
||||
}
|
||||
if document == nil || !attachmentPending(document.Status) || !time.Now().Before(deadline) {
|
||||
return document, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(pollInterval):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func attachmentPending(status string) bool {
|
||||
return status == types.TemporaryDocumentStatusUploaded || status == types.TemporaryDocumentStatusProcessing
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type testStore struct {
|
||||
doc *types.TemporaryDocument
|
||||
allowed bool
|
||||
loads int
|
||||
}
|
||||
|
||||
func (s *testStore) SessionAttachments(context.Context) (types.MessageAttachments, error) {
|
||||
if !s.allowed {
|
||||
return nil, nil
|
||||
}
|
||||
return types.MessageAttachments{{ID: s.doc.ID, FileName: "report.pdf"}}, nil
|
||||
}
|
||||
|
||||
func (s *testStore) TemporaryDocument(context.Context, string) (*types.TemporaryDocument, error) {
|
||||
s.loads++
|
||||
return s.doc, nil
|
||||
}
|
||||
|
||||
type testCache struct {
|
||||
mu sync.Mutex
|
||||
values map[string]Description
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (c *testCache) Get(_ context.Context, id, key string) (*Description, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.fail {
|
||||
return nil, errors.New("cache offline")
|
||||
}
|
||||
v, ok := c.values[id+key]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
func (c *testCache) Put(_ context.Context, id, key string, v Description) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.fail {
|
||||
return errors.New("cache offline")
|
||||
}
|
||||
c.values[id+key] = v
|
||||
return nil
|
||||
}
|
||||
|
||||
func imageFixture(t *testing.T) (*testStore, []byte) {
|
||||
t.Helper()
|
||||
var b bytes.Buffer
|
||||
require.NoError(t, png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 2, 2))))
|
||||
return &testStore{allowed: true, doc: &types.TemporaryDocument{
|
||||
ID: "document", Status: types.TemporaryDocumentStatusReady,
|
||||
ResourceRef: "local://owner/image", MimeType: "image/png",
|
||||
}}, b.Bytes()
|
||||
}
|
||||
|
||||
func readOne(
|
||||
ctx context.Context, reader *Reader, number int, detail, focus string,
|
||||
) (*interfaces.AttachmentImage, error) {
|
||||
reads, err := reader.ReadImages(ctx, "document", []int{number}, detail, focus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reads[0].Image, reads[0].Err
|
||||
}
|
||||
|
||||
func TestReaderAuthorizesBeforeDocumentImageOrCacheAccess(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
store.allowed = false
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) {
|
||||
t.Fatal("unauthorized file access")
|
||||
return data, nil
|
||||
})
|
||||
_, err := readOne(context.Background(), reader, 1, "brief", "")
|
||||
require.ErrorIs(t, err, interfaces.ErrAttachmentNotFound)
|
||||
require.Zero(t, store.loads)
|
||||
}
|
||||
|
||||
func TestDescriptionsSurviveReadersAndSeparateReadingRequirements(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
cache := &testCache{values: map[string]Description{}}
|
||||
calls := 0
|
||||
makeReader := func(model string) *Reader {
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) { return data, nil })
|
||||
reader.Images = &ImageReader{
|
||||
Model: model, Cache: cache,
|
||||
Describe: func(ctx context.Context, _ []byte, prompt string) (string, error) {
|
||||
calls++
|
||||
deadline, ok := ctx.Deadline()
|
||||
require.True(t, ok)
|
||||
require.LessOrEqual(t, time.Until(deadline), imageDescribeFullTimeout)
|
||||
return prompt, nil
|
||||
},
|
||||
}
|
||||
return reader
|
||||
}
|
||||
ctx := context.Background()
|
||||
first, err := readOne(ctx, makeReader("vision-a"), 1, "", " axes ")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, first.Description)
|
||||
again, err := readOne(ctx, makeReader("vision-a"), 1, "brief", "axes")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, first.Description, again.Description)
|
||||
require.Equal(t, 1, calls)
|
||||
for _, tc := range []struct{ model, detail, focus string }{
|
||||
{"vision-a", "brief", "legend"}, {"vision-a", "full", "axes"}, {"vision-b", "brief", "axes"},
|
||||
} {
|
||||
_, err = readOne(ctx, makeReader(tc.model), 1, tc.detail, tc.focus)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.Equal(t, 4, calls)
|
||||
data = append(data, 0) // Different source bytes cannot reuse the observation.
|
||||
_, err = readOne(ctx, makeReader("vision-a"), 1, "brief", "axes")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 5, calls)
|
||||
}
|
||||
|
||||
func TestFailedDescriptionsAreRetriedAndCacheFailureDoesNotLoseResult(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
cache := &testCache{values: map[string]Description{}}
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) { return data, nil })
|
||||
calls := 0
|
||||
reader.Images = &ImageReader{Cache: cache, Describe: func(context.Context, []byte, string) (string, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return "", errors.New("model unavailable")
|
||||
}
|
||||
return "chart", nil
|
||||
}}
|
||||
first, err := readOne(context.Background(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, first.Warning)
|
||||
require.Empty(t, *first.Description)
|
||||
second, err := readOne(context.Background(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "chart", *second.Description)
|
||||
require.Equal(t, 2, calls)
|
||||
cache.fail = true
|
||||
third, err := readOne(context.Background(), reader, 1, "brief", "new focus")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "chart", *third.Description)
|
||||
require.Contains(t, third.Warning, "save description")
|
||||
}
|
||||
|
||||
type failedProjection struct{ images int }
|
||||
|
||||
func (*failedProjection) Document(context.Context, *types.TemporaryDocument) (string, error) {
|
||||
return "", errors.New("sandbox offline")
|
||||
}
|
||||
|
||||
func (p *failedProjection) Image(
|
||||
context.Context, *types.TemporaryDocument, int, []byte, string, string, *Description,
|
||||
) (map[string]string, error) {
|
||||
p.images++
|
||||
return nil, errors.New("sandbox offline")
|
||||
}
|
||||
|
||||
func TestNativeVisionAndUnavailableSandboxDoNotRequireDescription(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) { return data, nil })
|
||||
projection := &failedProjection{}
|
||||
reader.Projection = projection
|
||||
document, err := reader.Resolve(context.Background(), "document", true)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, document.Document)
|
||||
require.Contains(t, document.Warning, "sandbox offline")
|
||||
view, err := readOne(context.Background(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, view.DataURI)
|
||||
require.Nil(t, view.Description)
|
||||
require.Equal(t, 1, projection.images)
|
||||
require.Contains(t, view.Warning, "sandbox offline")
|
||||
}
|
||||
|
||||
func TestConcurrentDescriptionRequestsShareOneCall(t *testing.T) {
|
||||
cache := &testCache{values: map[string]Description{}}
|
||||
var calls atomic.Int32
|
||||
reader := &ImageReader{Cache: cache, Describe: func(context.Context, []byte, string) (string, error) {
|
||||
calls.Add(1)
|
||||
return "chart", nil
|
||||
}}
|
||||
var wg sync.WaitGroup
|
||||
for range 8 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
value, _, err := reader.describe(context.Background(), "document", []byte("image"), "brief", "axes")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "chart", value.Text)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestReadImagesAuthorizesOnceAndDescribesConcurrently(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
store.doc.MimeType = "application/pdf"
|
||||
store.doc.ImageRefs = types.JSON(`[{"url":"a"},{"url":"b"},{"url":"c"}]`)
|
||||
reader := NewReader(store, 0, func(_ context.Context, url string) ([]byte, error) {
|
||||
return append(append([]byte(nil), data...), url...), nil
|
||||
})
|
||||
var inside sync.WaitGroup
|
||||
inside.Add(3)
|
||||
reader.Images = &ImageReader{Describe: func(_ context.Context, _ []byte, _ string) (string, error) {
|
||||
inside.Done()
|
||||
// Every description has to be in flight at once to get past here.
|
||||
inside.Wait()
|
||||
return "chart", nil
|
||||
}}
|
||||
done := make(chan []interfaces.AttachmentImageRead)
|
||||
go func() {
|
||||
reads, err := reader.ReadImages(context.Background(), "document", []int{1, 2, 3, 9}, "brief", "")
|
||||
require.NoError(t, err)
|
||||
done <- reads
|
||||
}()
|
||||
select {
|
||||
case reads := <-done:
|
||||
require.Len(t, reads, 4)
|
||||
for i, read := range reads[:3] {
|
||||
require.Equal(t, i+1, read.Number)
|
||||
require.NoError(t, read.Err)
|
||||
require.Equal(t, "chart", *read.Image.Description)
|
||||
}
|
||||
require.Equal(t, 9, reads[3].Number)
|
||||
require.Error(t, reads[3].Err)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("images were described one at a time")
|
||||
}
|
||||
require.Equal(t, 1, store.loads)
|
||||
}
|
||||
|
||||
func TestDescriptionDeadlineStartsAfterQueueing(t *testing.T) {
|
||||
reader := &ImageReader{}
|
||||
reader.slotsOnce.Do(func() { reader.slots = make(chan struct{}, 1) })
|
||||
reader.slots <- struct{}{}
|
||||
const queued = 200 * time.Millisecond
|
||||
time.AfterFunc(queued, func() { <-reader.slots })
|
||||
var remaining time.Duration
|
||||
reader.Describe = func(ctx context.Context, _ []byte, _ string) (string, error) {
|
||||
deadline, ok := ctx.Deadline()
|
||||
require.True(t, ok)
|
||||
remaining = time.Until(deadline)
|
||||
return "chart", nil
|
||||
}
|
||||
_, _, err := reader.describe(context.Background(), "document", []byte("image"), "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, remaining, imageDescribeTimeout-queued/2)
|
||||
}
|
||||
|
||||
func TestCancelledCallerDoesNotFailSharedDescription(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
reader := &ImageReader{Describe: func(ctx context.Context, _ []byte, _ string) (string, error) {
|
||||
calls.Add(1)
|
||||
close(started)
|
||||
<-release
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "chart", nil
|
||||
}}
|
||||
firstCtx, cancel := context.WithCancel(context.Background())
|
||||
firstErr := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, err := reader.describe(firstCtx, "document", []byte("image"), "brief", "")
|
||||
firstErr <- err
|
||||
}()
|
||||
<-started
|
||||
second := make(chan *Description, 1)
|
||||
go func() {
|
||||
value, _, err := reader.describe(context.Background(), "document", []byte("image"), "brief", "")
|
||||
require.NoError(t, err)
|
||||
second <- value
|
||||
}()
|
||||
time.Sleep(50 * time.Millisecond) // let the second caller join the in-flight call
|
||||
cancel()
|
||||
require.ErrorIs(t, <-firstErr, context.Canceled)
|
||||
close(release)
|
||||
require.Equal(t, "chart", (<-second).Text)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestChartPromptDoesNotReuseLegacyUnstructuredObservation(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
const oldPrompt = "Describe this image in at most 120 words. " +
|
||||
"Include its type, key labels, numbers and relationships. Do not transcribe long passages. " +
|
||||
"Say when content is illegible; do not guess. Plain text only."
|
||||
identity, err := json.Marshal([]string{"vision", oldPrompt, fmt.Sprintf("%x", sha256.Sum256(data))})
|
||||
require.NoError(t, err)
|
||||
key := fmt.Sprintf("%x", sha256.Sum256(identity))
|
||||
cache := &testCache{values: map[string]Description{
|
||||
store.doc.ID + key: {Text: "160 148 120 116 96", Model: "vision"},
|
||||
}}
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) { return data, nil })
|
||||
calls := 0
|
||||
reader.Images = &ImageReader{
|
||||
Model: "vision", Cache: cache,
|
||||
Describe: func(_ context.Context, image []byte, prompt string) (string, error) {
|
||||
calls++
|
||||
require.NotEmpty(t, image)
|
||||
require.Contains(t, prompt, "one labelled row per category")
|
||||
return "East: Q1=102, Q2=148 (万元)", nil
|
||||
},
|
||||
}
|
||||
first, err := readOne(t.Context(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "East: Q1=102, Q2=148 (万元)", *first.Description)
|
||||
_, err = readOne(t.Context(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, calls, "reuse the new observation, not the legacy OCR list")
|
||||
}
|
||||
Reference in new issue
Block a user