This commit is contained in:
1 parent
74d21cb204
commit
7d3b6804af
5 files changed
+220
-15
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
@@ -284,17 +285,70 @@ Rules:
|
||||
5. Output ONLY a JSON array of translated strings with the same length and order as the input array. No commentary.`
|
||||
|
||||
func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string) ([]string, error) {
|
||||
return c.translateRecover(ctx, texts, bisectDepth(len(texts)))
|
||||
}
|
||||
|
||||
// bisectDepth bounds the halving steps needed to reach single strings.
|
||||
func bisectDepth(n int) int {
|
||||
depth := 0
|
||||
for n > 1 {
|
||||
n /= 2
|
||||
depth++
|
||||
}
|
||||
return depth + 1
|
||||
}
|
||||
|
||||
// translateRecover aligns model answers with inputs. A positional JSON
|
||||
// protocol fails in one deterministic way: the model merges or drops an item
|
||||
// (near-duplicate strings, symbol-only entries) and returns N-1 results, so
|
||||
// blind retries reproduce the same mismatch forever. On a count mismatch the
|
||||
// batch is halved and each half retried; a single stubborn string degrades to
|
||||
// keeping the original text, which the engine's residual scan reports.
|
||||
func (c *chatBatchTranslator) translateRecover(ctx context.Context, texts []string, depth int) ([]string, error) {
|
||||
out, err := c.attempt(ctx, texts)
|
||||
if err == nil && len(out) == len(texts) {
|
||||
return out, nil
|
||||
}
|
||||
if len(texts) == 1 {
|
||||
if err == nil && len(out) >= 1 && strings.TrimSpace(out[0]) != "" {
|
||||
return []string{out[0]}, nil
|
||||
}
|
||||
// Keep the original untranslated; the residual scan reports it.
|
||||
return []string{texts[0]}, nil
|
||||
}
|
||||
if depth <= 0 {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), len(texts))
|
||||
}
|
||||
mid := len(texts) / 2
|
||||
left, err := c.translateRecover(ctx, texts[:mid], depth-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
right, err := c.translateRecover(ctx, texts[mid:], depth-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(left, right...), nil
|
||||
}
|
||||
|
||||
// attempt issues one streaming call. Transport and JSON-shape errors get one
|
||||
// immediate retry; count mismatches are content-deterministic and returned
|
||||
// (wrapped) so the caller bisects instead of repeating the same failure.
|
||||
func (c *chatBatchTranslator) attempt(ctx context.Context, texts []string) ([]string, error) {
|
||||
payload, err := json.Marshal(texts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
if attempt > 0 {
|
||||
for a := 0; a < 2; a++ {
|
||||
if a > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(time.Duration(attempt) * 2 * time.Second):
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}
|
||||
user := fmt.Sprintf("Translate the following JSON array of strings to English. Return a JSON array with exactly %d items in the same order.\n\n%s", len(texts), payload)
|
||||
@@ -303,9 +357,13 @@ func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
out, err := parseTranslationArray(content, len(texts))
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
out, perr := parseTranslationArray(content, len(texts))
|
||||
if perr != nil {
|
||||
var mismatch *countMismatchError
|
||||
if errors.As(perr, &mismatch) {
|
||||
return mismatch.items, perr
|
||||
}
|
||||
lastErr = perr
|
||||
continue
|
||||
}
|
||||
return out, nil
|
||||
@@ -313,6 +371,17 @@ func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string
|
||||
return nil, fmt.Errorf("translation call failed after retries: %w", lastErr)
|
||||
}
|
||||
|
||||
// countMismatchError carries the model's items so bisection can still use
|
||||
// them when the counts do not line up.
|
||||
type countMismatchError struct {
|
||||
got, want int
|
||||
items []string
|
||||
}
|
||||
|
||||
func (e *countMismatchError) Error() string {
|
||||
return fmt.Sprintf("model returned %d translations for %d inputs", e.got, e.want)
|
||||
}
|
||||
|
||||
// translateOnce issues one streaming batch call and returns the concatenated
|
||||
// answer. Streaming is deliberate: long batches then fall under the chat
|
||||
// client's stall-based timeout instead of a single non-stream HTTP timeout.
|
||||
@@ -354,7 +423,7 @@ func parseTranslationArray(content string, want int) ([]string, error) {
|
||||
return nil, fmt.Errorf("model response is not a valid string array: %w", err)
|
||||
}
|
||||
if len(out) != want {
|
||||
return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), want)
|
||||
return nil, &countMismatchError{got: len(out), want: want, items: out}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -309,3 +309,84 @@ func TestXlsxTranslateToolMissingFile(t *testing.T) {
|
||||
t.Fatalf("missing file should fail")
|
||||
}
|
||||
}
|
||||
|
||||
// dropItemsChat simulates the deterministic 192 failure: for any batch larger
|
||||
// than one string the model "merges" two items and returns N-1 translations.
|
||||
type dropItemsChat struct{}
|
||||
|
||||
func (f *dropItemsChat) Chat(ctx context.Context, messages []chat.Message, opts *chat.ChatOptions) (*types.ChatResponse, error) {
|
||||
resp, err := f.ChatStream(ctx, messages, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var content strings.Builder
|
||||
for chunk := range resp {
|
||||
content.WriteString(chunk.Content)
|
||||
}
|
||||
return &types.ChatResponse{Content: content.String()}, nil
|
||||
}
|
||||
|
||||
func (f *dropItemsChat) ChatStream(_ context.Context, messages []chat.Message, opts *chat.ChatOptions) (<-chan types.StreamResponse, error) {
|
||||
content := messages[len(messages)-1].Content
|
||||
start := strings.IndexByte(content, '[')
|
||||
end := strings.LastIndexByte(content, ']')
|
||||
var texts []string
|
||||
if err := json.Unmarshal([]byte(content[start:end+1]), &texts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(texts) > 1 {
|
||||
texts = texts[:len(texts)-1] // drop the last item: 19 of 20
|
||||
} else if len(texts) == 1 {
|
||||
texts = nil // single stubborn string: model refuses to translate it
|
||||
}
|
||||
out := make([]string, 0, len(texts))
|
||||
for _, t := range texts {
|
||||
out = append(out, replaceCJKRuns(t))
|
||||
}
|
||||
b, _ := json.Marshal(out)
|
||||
ch := make(chan types.StreamResponse, 2)
|
||||
ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Content: string(b)}
|
||||
ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Done: true}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (f *dropItemsChat) GetModelName() string { return "dropping" }
|
||||
func (f *dropItemsChat) GetModelID() string { return "dropping-id" }
|
||||
|
||||
// TestXlsxTranslateBatchCountMismatchRecovers covers the field failure where
|
||||
// the model returns N-1 translations for N inputs: bisection must realign
|
||||
// instead of failing the run.
|
||||
func TestXlsxTranslateBatchCountMismatchRecovers(t *testing.T) {
|
||||
texts := make([]string, 20)
|
||||
for i := range texts {
|
||||
texts[i] = fmt.Sprintf("检验项目 %d", i+1)
|
||||
}
|
||||
tr := &chatBatchTranslator{model: &dropItemsChat{}}
|
||||
out, err := tr.TranslateBatch(context.Background(), texts)
|
||||
if err != nil {
|
||||
t.Fatalf("TranslateBatch: %v", err)
|
||||
}
|
||||
if len(out) != len(texts) {
|
||||
t.Fatalf("recovered %d results for %d inputs", len(out), len(texts))
|
||||
}
|
||||
for i := range out {
|
||||
if strings.TrimSpace(out[i]) == "" {
|
||||
t.Fatalf("item %d empty after recovery", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestXlsxTranslateBatchSingleStubbornStringKeepsOriginal covers the terminal
|
||||
// bisection case: one string the model refuses to translate must degrade to
|
||||
// the original text, not fail the run.
|
||||
func TestXlsxTranslateBatchSingleStubbornStringKeepsOriginal(t *testing.T) {
|
||||
tr := &chatBatchTranslator{model: &dropItemsChat{}}
|
||||
out, err := tr.TranslateBatch(context.Background(), []string{"顽固文本"})
|
||||
if err != nil {
|
||||
t.Fatalf("TranslateBatch: %v", err)
|
||||
}
|
||||
if out[0] != "顽固文本" {
|
||||
t.Fatalf("single item altered: %q", out[0])
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user