Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions internal/aistudio/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -853,6 +853,8 @@ func (s *PooledService) CountTokens(ctx context.Context, request TokenCountReque
if opts.StripThoughtSignatures {
request.Contents = stripThoughtSignatures(request.Contents)
}
var droppedMedia *assistantMediaCountMap
request.Contents, droppedMedia = dropUnsupportedAssistantMedia(request.Contents, true)
systemOnly := len(request.Contents) == 0
if systemOnly {
if strings.TrimSpace(SystemText(request.System)) == "" {
Expand All @@ -871,6 +873,9 @@ func (s *PooledService) CountTokens(ctx context.Context, request TokenCountReque
if systemOnly && len(count.Contents) == 1 {
count = systemOnlyCount(count)
}
if err == nil && droppedMedia != nil {
count.Contents = droppedMedia.restore(count.Contents, count.System != nil)
}
return count, err
}

Expand Down
195 changes: 193 additions & 2 deletions internal/aistudio/turns.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package aistudio

import (
"mime"
"slices"
"strings"
)
Expand Down Expand Up @@ -28,10 +29,200 @@ func shouldRewriteAssistantTail(modelID string, rewrite bool) bool {
return rewrite && !nativePrefillModels[modelID] && !strings.HasPrefix(modelID, "gemma-")
}

// normalizeTurns 按 clientSystem 改写客户端系统提示,按 dropUserRejected 删去 user 轮中的客户端身份句;在 rewrite 时改写末尾连续 assistant 轮:prompt 非空时正文作为续写前缀连同 prompt 写入系统指令,为空时正文作为最后一轮 user;没有对话内容时以系统提示作为 user 轮
// upstreamAssistantMediaMIME 是上游 GenerateContent(含 Drive 上传)直接接受的非 text/* 模型历史内联媒体类型
var upstreamAssistantMediaMIME = map[string]bool{
"application/json": true,
"application/x-ipynb+json": true,
"application/pdf": true,
"application/zip": true,
"application/x-zip": true,
"application/x-zip-compressed": true,
"application/hwp": true,
"application/hwp+zip": true,
"application/msword": true,
"application/vnd.ms-excel": true,
"application/vnd.ms-powerpoint": true,
"application/vnd.oasis.opendocument.text": true,
"application/vnd.oasis.opendocument.spreadsheet": true,
"application/vnd.oasis.opendocument.presentation": true,
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": true,
"application/vnd.openxmlformats-officedocument.wordprocessingml.template": true,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": true,
"application/vnd.openxmlformats-officedocument.presentationml.presentation": true,
"image/png": true,
"image/jpeg": true,
"image/webp": true,
"image/heic": true,
"image/heif": true,
"audio/aac": true,
"audio/aiff": true,
"audio/alaw": true,
"audio/flac": true,
"audio/l16": true,
"audio/m4a": true,
"audio/mp3": true,
"audio/mp4": true,
"audio/mpeg": true,
"audio/mulaw": true,
"audio/ogg": true,
"audio/opus": true,
"audio/pcm": true,
"audio/s16le": true,
"audio/wav": true,
"audio/wave": true,
"audio/x-wav": true,
"audio/webm": true,
"video/mp4": true,
"video/mpeg": true,
"video/mov": true,
"video/quicktime": true,
"video/avi": true,
"video/x-flv": true,
"video/mpg": true,
"video/webm": true,
"video/wmv": true,
"video/3gpp": true,
}

// supportedAssistantMediaMIME 判断声明的媒体类型是否属于上游接受的模型历史内联媒体类型
func supportedAssistantMediaMIME(mimeType string) bool {
mediaType, _, err := mime.ParseMediaType(mimeType)
if err != nil {
return false
}
return strings.HasPrefix(mediaType, "text/") || upstreamAssistantMediaMIME[mediaType]
}

// assistantMediaTurnMap 记录单个原非空轮次在丢弃不支持媒体后的保留情况
type assistantMediaTurnMap struct {
origParts int
kept []int
dropped bool
}

// assistantMediaCountMap 记录 CountTokens 过滤模型历史不支持媒体前后的轮次与片段对应关系,用于把返回的逐项计数还原到原位置
type assistantMediaCountMap struct {
turns []assistantMediaTurnMap
sentTurns int
}

// restore 按过滤前的非空轮次与片段下标还原 CountTokens 返回的逐轮明细,被丢弃的片段与整轮补零
func (m *assistantMediaCountMap) restore(got []ContentTokens, hasSystem bool) []ContentTokens {
if m == nil || len(got) != m.sentTurns || (m.sentTurns == 0 && !hasSystem) {
return got
}
restored := make([]ContentTokens, len(m.turns))
sent := 0
for index, turn := range m.turns {
if turn.dropped {
restored[index] = ContentTokens{PartTokens: make([]int64, turn.origParts)}
continue
}
entry := got[sent]
sent++
if turn.kept == nil || len(entry.PartTokens) != len(turn.kept) {
restored[index] = entry
continue
}
parts := make([]int64, turn.origParts)
for keptIndex, origIndex := range turn.kept {
parts[origIndex] = entry.PartTokens[keptIndex]
}
restored[index] = ContentTokens{PartTokens: parts, RoleTokens: entry.RoleTokens}
}
return restored
}

// DropUnsupportedAssistantMedia 丢弃模型历史轮中上游不接受的内联媒体,保留思考签名,清空后的模型轮不发送
func DropUnsupportedAssistantMedia(contents []Content) []Content {
filtered, _ := dropUnsupportedAssistantMedia(contents, false)
return filtered
}

func dropUnsupportedAssistantMedia(contents []Content, trackCount bool) ([]Content, *assistantMediaCountMap) {
var filtered []Content
var keptByTurn map[int][]int
for index, content := range contents {
if content.Role != RoleAssistant {
continue
}
var parts []Part
var kept []int
for partIndex, part := range content.Parts {
blob := part.InlineData
if blob == nil || (len(blob.Data) > 0 && supportedAssistantMediaMIME(blob.MIME)) {
if parts != nil {
parts = append(parts, part)
if trackCount {
kept = append(kept, partIndex)
}
}
continue
}
if parts == nil {
parts = make([]Part, partIndex, len(content.Parts))
copy(parts, content.Parts[:partIndex])
if trackCount {
kept = make([]int, partIndex, len(content.Parts))
for i := range partIndex {
kept[i] = i
}
}
}
if part.ThoughtSignature != "" {
parts = append(parts, Part{ThoughtSignature: part.ThoughtSignature})
if trackCount {
kept = append(kept, partIndex)
}
}
}
if parts == nil {
continue
}
if filtered == nil {
filtered = slices.Clone(contents)
}
filtered[index].Parts = parts
if trackCount && len(kept) != len(content.Parts) {
if keptByTurn == nil {
keptByTurn = make(map[int][]int)
}
keptByTurn[index] = kept
}
}
if filtered == nil {
return contents, nil
}
var countMap *assistantMediaCountMap
if trackCount && len(keptByTurn) > 0 {
countMap = &assistantMediaCountMap{turns: make([]assistantMediaTurnMap, 0, len(contents))}
for index, content := range contents {
if len(content.Parts) == 0 {
continue
}
kept, changed := keptByTurn[index]
if !changed {
countMap.turns = append(countMap.turns, assistantMediaTurnMap{origParts: len(content.Parts)})
countMap.sentTurns++
continue
}
if len(kept) == 0 {
countMap.turns = append(countMap.turns, assistantMediaTurnMap{origParts: len(content.Parts), dropped: true})
continue
}
countMap.turns = append(countMap.turns, assistantMediaTurnMap{origParts: len(content.Parts), kept: kept})
countMap.sentTurns++
}
}
return slices.DeleteFunc(filtered, func(content Content) bool {
return content.Role == RoleAssistant && len(content.Parts) == 0
}), countMap
}

// normalizeTurns 按 clientSystem 改写客户端系统提示,按 dropUserRejected 删去 user 轮中的客户端身份句,按 DropUnsupportedAssistantMedia 丢弃模型历史轮中上游不接受的内联媒体;在 rewrite 时改写末尾连续 assistant 轮:prompt 非空时正文作为续写前缀连同 prompt 写入系统指令,为空时正文作为最后一轮 user;没有对话内容时以系统提示作为 user 轮
func normalizeTurns(system []string, contents []Content, rewrite bool, prompt string) ([]string, []Content) {
system = clientSystem(system)
contents = dropUserRejected(contents)
contents = DropUnsupportedAssistantMedia(dropUserRejected(contents))
if rewrite {
tail := len(contents)
for tail > 0 && contents[tail-1].Role == RoleAssistant {
Expand Down
1 change: 1 addition & 0 deletions internal/app/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -2367,6 +2367,7 @@ func (service *trackedService) Generate(ctx context.Context, request aistudio.Ge
api.SetAccessLogGenerationConfig(ctx, request.Config)
api.SetAccessLogGenerationInput(ctx, request)
api.StartAccessLog(ctx)
request.Contents = aistudio.DropUnsupportedAssistantMedia(request.Contents)
request.Model = service.catalogModelID(ctx, request.Model)
requestCtx, cancel, err := service.dataRequestContext(ctx)
if err == nil && suffixErr != nil {
Expand Down