This commit is contained in:
1 parent
c6088aeb4b
commit
f12128a5c3
4 files changed
+135
-32
No files matched your search
@@ -44,6 +44,12 @@ const (
|
||||
// 600-second command timeout so the tool can return a structured timeout
|
||||
// result instead of being cancelled first by the generic agent wrapper.
|
||||
shellExecToolTimeout = 10*time.Minute + 5*time.Second
|
||||
// xlsxTranslateToolTimeout is slightly longer than xlsx_translate's own
|
||||
// 20-minute internal budget so the tool can return a structured timeout
|
||||
// result instead of being cancelled first by the generic agent wrapper.
|
||||
// Workbook translation runs many LLM batches serialised by the provider's
|
||||
// concurrency gate, which no other tool comes close to needing.
|
||||
xlsxTranslateToolTimeout = 20*time.Minute + 5*time.Second
|
||||
// webFetchToolSlack is how much longer the agent wrapper waits than the
|
||||
// shared page-fetch budget. Same 5s headroom as shell_exec, so web_fetch can
|
||||
// return its own timeout result instead of being cancelled first.
|
||||
@@ -117,6 +123,8 @@ func toolExecutionTimeout(toolName string, arguments ...string) time.Duration {
|
||||
switch toolName {
|
||||
case "shell_exec":
|
||||
return shellExecToolTimeout
|
||||
case agenttools.ToolXlsxTranslate:
|
||||
return xlsxTranslateToolTimeout
|
||||
case "web_fetch":
|
||||
return webfetch.PageFetchTimeout() + webFetchToolSlack
|
||||
}
|
||||
|
||||
@@ -132,9 +132,7 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
// ---- Translate ----
|
||||
runCtx, cancel := context.WithTimeout(ctx, t.timeout)
|
||||
defer cancel()
|
||||
translated, report, err := xlsxtranslate.Translate(runCtx, data, &xlsxtranslate.Options{
|
||||
BatchSize: 40,
|
||||
}, &chatBatchTranslator{model: t.model})
|
||||
translated, report, err := xlsxtranslate.Translate(runCtx, data, &xlsxtranslate.Options{}, &chatBatchTranslator{model: t.model})
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][XlsxTranslate] session=%s file=%s failed: %v", sessionID, source, err)
|
||||
return &types.ToolResult{Success: false,
|
||||
@@ -300,15 +298,12 @@ func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string
|
||||
}
|
||||
}
|
||||
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)
|
||||
resp, err := c.model.Chat(ctx, []chat.Message{
|
||||
{Role: "system", Content: translateSystemPrompt},
|
||||
{Role: "user", Content: user},
|
||||
}, &chat.ChatOptions{Temperature: 0.2, MaxCompletionTokens: 16384})
|
||||
content, err := c.translateOnce(ctx, user)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
out, err := parseTranslationArray(resp.Content, len(texts))
|
||||
out, err := parseTranslationArray(content, len(texts))
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
@@ -318,6 +313,29 @@ func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string
|
||||
return nil, fmt.Errorf("translation call failed after retries: %w", lastErr)
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (c *chatBatchTranslator) translateOnce(ctx context.Context, user string) (string, error) {
|
||||
ch, err := c.model.ChatStream(ctx, []chat.Message{
|
||||
{Role: "system", Content: translateSystemPrompt},
|
||||
{Role: "user", Content: user},
|
||||
}, &chat.ChatOptions{Temperature: 0.2, MaxCompletionTokens: 16384})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var content strings.Builder
|
||||
for chunk := range ch {
|
||||
switch chunk.ResponseType {
|
||||
case types.ResponseTypeError:
|
||||
return "", fmt.Errorf("%s", chunk.Content)
|
||||
default:
|
||||
content.WriteString(chunk.Content)
|
||||
}
|
||||
}
|
||||
return content.String(), nil
|
||||
}
|
||||
|
||||
// parseTranslationArray extracts the JSON array from a model response that
|
||||
// may wrap it in markdown fences or prose.
|
||||
func parseTranslationArray(content string, want int) ([]string, error) {
|
||||
|
||||
@@ -90,7 +90,19 @@ type fakeTranslateChat struct {
|
||||
prompts []string
|
||||
}
|
||||
|
||||
func (f *fakeTranslateChat) Chat(_ context.Context, messages []chat.Message, _ *chat.ChatOptions) (*types.ChatResponse, error) {
|
||||
func (f *fakeTranslateChat) 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 *fakeTranslateChat) ChatStream(_ context.Context, messages []chat.Message, _ *chat.ChatOptions) (<-chan types.StreamResponse, error) {
|
||||
f.prompts = append(f.prompts, messages[len(messages)-1].Content)
|
||||
content := messages[len(messages)-1].Content
|
||||
start := strings.IndexByte(content, '[')
|
||||
@@ -104,11 +116,11 @@ func (f *fakeTranslateChat) Chat(_ context.Context, messages []chat.Message, _ *
|
||||
out = append(out, replaceCJKRuns(t))
|
||||
}
|
||||
b, _ := json.Marshal(out)
|
||||
return &types.ChatResponse{Content: string(b)}, nil
|
||||
}
|
||||
|
||||
func (f *fakeTranslateChat) ChatStream(_ context.Context, _ []chat.Message, _ *chat.ChatOptions) (<-chan types.StreamResponse, error) {
|
||||
return nil, fmt.Errorf("not implemented")
|
||||
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 *fakeTranslateChat) GetModelName() string { return "fake" }
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -22,8 +24,12 @@ type Translator interface {
|
||||
// each field.
|
||||
type Options struct {
|
||||
// BatchSize is the number of strings sent to the LLM per call.
|
||||
// Default 40.
|
||||
// Default 20.
|
||||
BatchSize int
|
||||
// BatchConcurrency is how many LLM batches may run in parallel.
|
||||
// Default 4. Providers rate-limit; higher values queue on the chat
|
||||
// client's own concurrency gate.
|
||||
BatchConcurrency int
|
||||
// MaxUnitRunes caps a single translatable text unit. Longer units are
|
||||
// left untranslated and reported, so one oversized cell cannot blow up
|
||||
// an LLM call. Default 6000.
|
||||
@@ -40,7 +46,14 @@ func (o *Options) batchSize() int {
|
||||
if o != nil && o.BatchSize > 0 {
|
||||
return o.BatchSize
|
||||
}
|
||||
return 40
|
||||
return 20
|
||||
}
|
||||
|
||||
func (o *Options) batchConcurrency() int {
|
||||
if o != nil && o.BatchConcurrency > 0 {
|
||||
return o.BatchConcurrency
|
||||
}
|
||||
return 4
|
||||
}
|
||||
|
||||
func (o *Options) maxUnitRunes() int {
|
||||
@@ -266,36 +279,70 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([
|
||||
todo = append(todo, src)
|
||||
}
|
||||
}
|
||||
for lo := 0; lo < len(todo); lo += opt.batchSize() {
|
||||
hi := lo + opt.batchSize()
|
||||
|
||||
// Batches run with bounded parallelism: a 63 MB workbook translates
|
||||
// several hundred units, and serial batches would spend far longer on
|
||||
// LLM latency than on everything else combined.
|
||||
batchSize := opt.batchSize()
|
||||
var batches [][]string
|
||||
for lo := 0; lo < len(todo); lo += batchSize {
|
||||
hi := lo + batchSize
|
||||
if hi > len(todo) {
|
||||
hi = len(todo)
|
||||
}
|
||||
batch := todo[lo:hi]
|
||||
masked := make([]string, len(batch))
|
||||
tokens := make([][]string, len(batch))
|
||||
for i, src := range batch {
|
||||
masked[i], tokens[i] = mask(src)
|
||||
batches = append(batches, todo[lo:hi])
|
||||
}
|
||||
out, err := tr.TranslateBatch(ctx, masked)
|
||||
batchOut := make([][]string, len(batches))
|
||||
batchTokens := make([][][]string, len(batches))
|
||||
batchErr := make([]error, len(batches))
|
||||
report.LLMCalls = len(batches)
|
||||
if concurrency := opt.batchConcurrency(); concurrency <= 1 || len(batches) <= 1 {
|
||||
for i, batch := range batches {
|
||||
batchOut[i], batchTokens[i], batchErr[i] = runBatch(ctx, tr, batch)
|
||||
}
|
||||
} else {
|
||||
sem := make(chan struct{}, concurrency)
|
||||
var failed atomic.Bool
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
var wg sync.WaitGroup
|
||||
for i := range batches {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
if failed.Load() {
|
||||
return // a sibling already failed; stop burning provider calls
|
||||
}
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
out, tokens, err := runBatch(runCtx, tr, batches[i])
|
||||
batchOut[i], batchTokens[i], batchErr[i] = out, tokens, err
|
||||
if err != nil {
|
||||
return nil, report, fmt.Errorf("LLM batch %d failed: %w", lo/opt.batchSize()+1, err)
|
||||
failed.Store(true)
|
||||
cancel()
|
||||
}
|
||||
if len(out) != len(batch) {
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
for i, batch := range batches {
|
||||
if batchErr[i] != nil {
|
||||
return nil, report, fmt.Errorf("LLM batch %d failed: %w", i+1, batchErr[i])
|
||||
}
|
||||
if len(batchOut[i]) != len(batch) {
|
||||
return nil, report, fmt.Errorf("LLM batch %d returned %d results for %d inputs",
|
||||
lo/opt.batchSize()+1, len(out), len(batch))
|
||||
i+1, len(batchOut[i]), len(batch))
|
||||
}
|
||||
report.LLMCalls++
|
||||
for i, dst := range out {
|
||||
restored, miss := unmask(dst, tokens[i])
|
||||
for j, dst := range batchOut[i] {
|
||||
restored, miss := unmask(dst, batchTokens[i][j])
|
||||
if len(miss) > 0 {
|
||||
report.Warnings = append(report.Warnings, fmt.Sprintf(
|
||||
"译文存在未能回填的占位符,请人工复核:%s", truncate(batch[i], 40)))
|
||||
"译文存在未能回填的占位符,请人工复核:%s", truncate(batch[j], 40)))
|
||||
}
|
||||
if opt.normalizePunctuation() {
|
||||
restored = normalizePunctuation(restored)
|
||||
}
|
||||
translations[batch[i]] = restored
|
||||
translations[batch[j]] = restored
|
||||
}
|
||||
}
|
||||
report.AppliedTranslations = len(translations)
|
||||
@@ -497,6 +544,24 @@ func readZip(f *zip.File) ([]byte, error) {
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// runBatch masks one batch and hands it to the translator, returning the
|
||||
// translations together with the per-string placeholder tokens for unmasking.
|
||||
func runBatch(ctx context.Context, tr Translator, batch []string) ([]string, [][]string, error) {
|
||||
masked := make([]string, len(batch))
|
||||
tokens := make([][]string, len(batch))
|
||||
for i, src := range batch {
|
||||
masked[i], tokens[i] = mask(src)
|
||||
}
|
||||
out, err := tr.TranslateBatch(ctx, masked)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(out) != len(batch) {
|
||||
return nil, nil, fmt.Errorf("translator returned %d results for %d inputs", len(out), len(batch))
|
||||
}
|
||||
return out, tokens, nil
|
||||
}
|
||||
|
||||
func isSheetXML(name string) bool {
|
||||
return strings.HasPrefix(name, "xl/worksheets/sheet") && strings.HasSuffix(name, ".xml")
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user