mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 08:01:07 +00:00
feat: add support for partial image generation in streaming requests
This commit is contained in:
1 parent
4f7371ac58
commit
e8a104c09c
8 files changed
+382
-69
No files matched your search
@@ -27,6 +27,7 @@ type ImageGenerationInput struct {
|
||||
Resolution string
|
||||
ResponseFormat string
|
||||
Streaming bool
|
||||
PartialImages int
|
||||
}
|
||||
|
||||
// ImageEditInput 表示图片编辑用例已经完成协议校验后的输入。
|
||||
@@ -58,7 +59,7 @@ func (s *Service) GenerateImage(ctx context.Context, input ImageGenerationInput)
|
||||
return adapter.GenerateImage(executionCtx, provider.ImageGenerationRequest{
|
||||
Credential: credential, Model: upstream, Prompt: input.Prompt, Count: input.Count,
|
||||
Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution,
|
||||
ResponseFormat: input.ResponseFormat, Streaming: input.Streaming,
|
||||
ResponseFormat: input.ResponseFormat, Streaming: input.Streaming, PartialImages: input.PartialImages,
|
||||
})
|
||||
}, input.Streaming, input.Resolution, input.Count, 0)
|
||||
}
|
||||
|
||||
@@ -754,7 +754,7 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) {
|
||||
|
||||
result, err := service.GenerateImage(ctx, ImageGenerationInput{
|
||||
RequestID: "req-image-stream", ClientKey: key, PublicModel: "grok-imagine-image-quality",
|
||||
Prompt: "test", Count: 2, Resolution: "1k", ResponseFormat: "url", Streaming: true,
|
||||
Prompt: "test", Count: 1, Resolution: "1k", ResponseFormat: "url", Streaming: true, PartialImages: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -766,8 +766,8 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) {
|
||||
if string(body) != "event: image_generation.completed\ndata: {}\n\ndata: [DONE]\n\n" {
|
||||
t.Fatalf("stream body = %q", body)
|
||||
}
|
||||
if !adapter.Streaming() {
|
||||
t.Fatal("stream flag was not propagated to the Web image adapter")
|
||||
if !adapter.Streaming() || adapter.PartialImages() != 1 {
|
||||
t.Fatalf("image stream options were not propagated: streaming=%t partial_images=%d", adapter.Streaming(), adapter.PartialImages())
|
||||
}
|
||||
if logs, total, err := auditRepo.List(ctx, 0, 10); err != nil || total != 0 || len(logs) != 0 {
|
||||
t.Fatalf("audit persisted before finalization: logs=%#v total=%d err=%v", logs, total, err)
|
||||
@@ -780,8 +780,8 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) {
|
||||
t.Fatalf("audit logs=%#v total=%d err=%v", logs, total, err)
|
||||
}
|
||||
if !logs[0].Streaming || logs[0].Operation != "image" || logs[0].Provider != string(account.ProviderWeb) || logs[0].ErrorCode != "" ||
|
||||
logs[0].MediaInputImages != 0 || logs[0].MediaOutputImages != 2 ||
|
||||
logs[0].PricingModel != "grok-imagine-image-quality-1k" || logs[0].EstimatedCostInUSDTicks != 1_000_000_000 {
|
||||
logs[0].MediaInputImages != 0 || logs[0].MediaOutputImages != 1 ||
|
||||
logs[0].PricingModel != "grok-imagine-image-quality-1k" || logs[0].EstimatedCostInUSDTicks != 500_000_000 {
|
||||
t.Fatalf("audit = %#v", logs[0])
|
||||
}
|
||||
windows, err := accountRepo.GetQuotaWindows(ctx, []uint64{credential.ID})
|
||||
@@ -1146,6 +1146,7 @@ type webRateLimitAdapter struct{}
|
||||
type webImageStreamAdapter struct {
|
||||
mu sync.Mutex
|
||||
streaming bool
|
||||
partialImages int
|
||||
editResolution string
|
||||
synced chan string
|
||||
failureEgress *infraegress.Manager
|
||||
@@ -1209,6 +1210,7 @@ func (a *webImageStreamAdapter) TierOrder(string) []account.WebTier {
|
||||
func (a *webImageStreamAdapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) {
|
||||
a.mu.Lock()
|
||||
a.streaming = request.Streaming
|
||||
a.partialImages = request.PartialImages
|
||||
failureEgress := a.failureEgress
|
||||
a.attempts = append(a.attempts, request.Credential.ID)
|
||||
a.mu.Unlock()
|
||||
@@ -1243,6 +1245,11 @@ func (a *webImageStreamAdapter) Streaming() bool {
|
||||
defer a.mu.Unlock()
|
||||
return a.streaming
|
||||
}
|
||||
func (a *webImageStreamAdapter) PartialImages() int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.partialImages
|
||||
}
|
||||
func (a *webImageStreamAdapter) EditResolution() string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
@@ -219,6 +219,7 @@ type ImageGenerationRequest struct {
|
||||
Resolution string
|
||||
ResponseFormat string
|
||||
Streaming bool
|
||||
PartialImages int
|
||||
}
|
||||
|
||||
type ImageInput struct {
|
||||
|
||||
@@ -43,14 +43,20 @@ type imagineImageValue struct {
|
||||
URL string
|
||||
Blob string
|
||||
Position int
|
||||
Width int
|
||||
Height int
|
||||
position bool
|
||||
}
|
||||
|
||||
type imagineSlot struct {
|
||||
image imagineImageValue
|
||||
completed bool
|
||||
moderated bool
|
||||
emitted bool
|
||||
image imagineImageValue
|
||||
preview imagineImageValue
|
||||
final bool
|
||||
previewReady bool
|
||||
previewEmitted bool
|
||||
completed bool
|
||||
moderated bool
|
||||
emitted bool
|
||||
}
|
||||
|
||||
type imagineCollector struct {
|
||||
@@ -71,12 +77,25 @@ func resolveImagineModel(model, resolution string, count int) (imagineModelConfi
|
||||
return imagineModelConfig{Pro: resolution == "2k", NativeBatchSize: batchSize, MaxReturnCount: 10}, true
|
||||
}
|
||||
|
||||
func imagineUpstreamGenerationCount(streaming bool, count int, config imagineModelConfig) int {
|
||||
if streaming {
|
||||
return count
|
||||
}
|
||||
return config.NativeBatchSize
|
||||
}
|
||||
|
||||
func invalidImageRequest(message string) (*provider.Response, error) {
|
||||
return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{
|
||||
"message": message, "type": "invalid_request_error",
|
||||
}}), nil
|
||||
}
|
||||
|
||||
func imageGenerationUserError(message, param, code string) (*provider.Response, error) {
|
||||
return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{
|
||||
"message": message, "type": "image_generation_user_error", "param": param, "code": code,
|
||||
}}), nil
|
||||
}
|
||||
|
||||
func newImagineCollector() *imagineCollector {
|
||||
return &imagineCollector{slots: make(map[string]*imagineSlot)}
|
||||
}
|
||||
@@ -100,12 +119,27 @@ func (c *imagineCollector) Accept(message map[string]any) {
|
||||
c.slots[imageID] = slot
|
||||
}
|
||||
if typeName == "image" {
|
||||
slot.image.URL = absoluteAssetURL(rawURL)
|
||||
slot.image.Blob, _ = message["blob"].(string)
|
||||
if position, ok := firstInt(message, "side_by_side_index", "order", "grid_index"); ok {
|
||||
slot.image.Position = position
|
||||
slot.image.position = true
|
||||
}
|
||||
width, _ := numberAsInt(message["width"])
|
||||
height, _ := numberAsInt(message["height"])
|
||||
progress, hasProgress := numberAsInt(message["percentage_complete"])
|
||||
if hasProgress && progress < 100 {
|
||||
slot.preview = imagineImageValue{
|
||||
ID: imageID, URL: absoluteAssetURL(rawURL), Position: slot.image.Position,
|
||||
Width: width, Height: height, position: slot.image.position,
|
||||
}
|
||||
slot.preview.Blob, _ = message["blob"].(string)
|
||||
slot.previewReady = true
|
||||
return
|
||||
}
|
||||
slot.image.URL = absoluteAssetURL(rawURL)
|
||||
slot.image.Blob, _ = message["blob"].(string)
|
||||
slot.image.Width = width
|
||||
slot.image.Height = height
|
||||
slot.final = true
|
||||
return
|
||||
}
|
||||
status, _ := message["current_status"].(string)
|
||||
@@ -113,9 +147,20 @@ func (c *imagineCollector) Accept(message map[string]any) {
|
||||
slot.image.Position = position
|
||||
slot.image.position = true
|
||||
}
|
||||
if width, ok := numberAsInt(message["width"]); ok && slot.image.Width == 0 {
|
||||
slot.image.Width = width
|
||||
}
|
||||
if height, ok := numberAsInt(message["height"]); ok && slot.image.Height == 0 {
|
||||
slot.image.Height = height
|
||||
}
|
||||
if status != "completed" {
|
||||
return
|
||||
}
|
||||
if rawURL != "" && !slot.final {
|
||||
slot.image.URL = absoluteAssetURL(rawURL)
|
||||
slot.image.Blob, _ = message["blob"].(string)
|
||||
slot.final = true
|
||||
}
|
||||
if !slot.completed {
|
||||
slot.completed = true
|
||||
c.terminalCount++
|
||||
@@ -128,7 +173,7 @@ func (c *imagineCollector) Done(expected int) bool {
|
||||
return false
|
||||
}
|
||||
for _, slot := range c.slots {
|
||||
if slot.completed && !slot.moderated && slot.image.URL == "" && slot.image.Blob == "" {
|
||||
if slot.completed && !slot.moderated && (!slot.final || (slot.image.URL == "" && slot.image.Blob == "")) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -138,30 +183,39 @@ func (c *imagineCollector) Done(expected int) bool {
|
||||
func (c *imagineCollector) Images() []imagineImageValue {
|
||||
values := make([]imagineImageValue, 0, len(c.slots))
|
||||
for _, slot := range c.slots {
|
||||
if slot.completed && !slot.moderated && (slot.image.URL != "" || slot.image.Blob != "") {
|
||||
if slot.completed && !slot.moderated && slot.final && (slot.image.URL != "" || slot.image.Blob != "") {
|
||||
values = append(values, slot.image)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(values, func(i, j int) bool {
|
||||
if values[i].position != values[j].position {
|
||||
return values[i].position
|
||||
}
|
||||
if values[i].Position != values[j].Position {
|
||||
return values[i].Position < values[j].Position
|
||||
}
|
||||
return values[i].ID < values[j].ID
|
||||
})
|
||||
sortImagineImages(values)
|
||||
return values
|
||||
}
|
||||
|
||||
func (c *imagineCollector) ReadyImages() []imagineImageValue {
|
||||
values := make([]imagineImageValue, 0, len(c.slots))
|
||||
for _, slot := range c.slots {
|
||||
if slot.completed && !slot.moderated && !slot.emitted && (slot.image.URL != "" || slot.image.Blob != "") {
|
||||
if slot.completed && !slot.moderated && slot.final && !slot.emitted && (slot.image.URL != "" || slot.image.Blob != "") {
|
||||
slot.emitted = true
|
||||
values = append(values, slot.image)
|
||||
}
|
||||
}
|
||||
sortImagineImages(values)
|
||||
return values
|
||||
}
|
||||
|
||||
func (c *imagineCollector) ReadyPreviews() []imagineImageValue {
|
||||
values := make([]imagineImageValue, 0)
|
||||
for _, slot := range c.slots {
|
||||
if slot.previewReady && !slot.previewEmitted {
|
||||
slot.previewEmitted = true
|
||||
values = append(values, slot.preview)
|
||||
}
|
||||
}
|
||||
sortImagineImages(values)
|
||||
return values
|
||||
}
|
||||
|
||||
func sortImagineImages(values []imagineImageValue) {
|
||||
sort.SliceStable(values, func(i, j int) bool {
|
||||
if values[i].position != values[j].position {
|
||||
return values[i].position
|
||||
@@ -171,7 +225,16 @@ func (c *imagineCollector) ReadyImages() []imagineImageValue {
|
||||
}
|
||||
return values[i].ID < values[j].ID
|
||||
})
|
||||
return values
|
||||
}
|
||||
|
||||
func (c *imagineCollector) UsableCount() int {
|
||||
count := 0
|
||||
for _, slot := range c.slots {
|
||||
if slot.completed && !slot.moderated && slot.final && (slot.image.URL != "" || slot.image.Blob != "") {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func firstString(value map[string]any, keys ...string) string {
|
||||
@@ -211,6 +274,15 @@ func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGener
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
if request.Streaming && count != 1 {
|
||||
return imageGenerationUserError("Streaming is only supported with n=1.", "input", "unsupported_parameter")
|
||||
}
|
||||
if request.PartialImages < 0 || request.PartialImages > 3 {
|
||||
return invalidImageRequest("partial_images 必须在 0 到 3 之间")
|
||||
}
|
||||
if request.PartialImages > 0 && !request.Streaming {
|
||||
return invalidImageRequest("partial_images 仅可在 stream=true 时使用")
|
||||
}
|
||||
format := strings.ToLower(strings.TrimSpace(request.ResponseFormat))
|
||||
if format == "" {
|
||||
format = "url"
|
||||
@@ -539,7 +611,8 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err)
|
||||
return nil, err
|
||||
}
|
||||
if err := connection.WriteJSON(imagineRequestMessage(newWebID("img"), request.Prompt, ratio, cfg.AllowNSFW, modelConfig.Pro, modelConfig.NativeBatchSize)); err != nil {
|
||||
upstreamCount := imagineUpstreamGenerationCount(request.Streaming, count, modelConfig)
|
||||
if err := connection.WriteJSON(imagineRequestMessage(newWebID("img"), request.Prompt, ratio, cfg.AllowNSFW, modelConfig.Pro, upstreamCount)); err != nil {
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err)
|
||||
return nil, err
|
||||
}
|
||||
@@ -548,13 +621,12 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen
|
||||
streamCtx, cancel := context.WithCancel(ctx)
|
||||
leaseOwned = false
|
||||
connectionOwned = false
|
||||
streamID := newWebID("imggen")
|
||||
go a.streamImagineImages(streamCtx, writer, connection, lease, request.Credential, streamID, count, format, ratio, resolution, modelConfig)
|
||||
go a.streamImagineImages(streamCtx, writer, connection, lease, request.Credential, count, request.PartialImages, modelConfig)
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil
|
||||
}
|
||||
|
||||
collector := newImagineCollector()
|
||||
for !collector.Done(modelConfig.NativeBatchSize) {
|
||||
for collector.UsableCount() < count && !collector.Done(modelConfig.NativeBatchSize) {
|
||||
messageType, data, readErr := connection.ReadMessage()
|
||||
if readErr != nil {
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, readErr)
|
||||
@@ -1009,7 +1081,7 @@ func (a *Adapter) imageBytes(ctx context.Context, credential account.Credential,
|
||||
return a.downloadImage(ctx, credential, image.URL)
|
||||
}
|
||||
|
||||
func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter, connection *websocket.Conn, lease *egress.Lease, credential account.Credential, streamID string, count int, format, ratio, resolution string, modelConfig imagineModelConfig) {
|
||||
func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter, connection *websocket.Conn, lease *egress.Lease, credential account.Credential, count, partialImages int, modelConfig imagineModelConfig) {
|
||||
defer lease.Release()
|
||||
defer connection.Close()
|
||||
done := make(chan struct{})
|
||||
@@ -1021,17 +1093,9 @@ func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter
|
||||
case <-done:
|
||||
}
|
||||
}()
|
||||
createdAt := time.Now().Unix()
|
||||
if err := writeSSE(writer, "image_generation.started", map[string]any{
|
||||
"type": "image_generation.started", "id": streamID, "object": "image_generation",
|
||||
"created": createdAt, "model": "grok-imagine-image-quality", "status": "in_progress",
|
||||
"n": count, "aspect_ratio": ratio, "resolution": strings.ToLower(strings.TrimSpace(resolution)),
|
||||
}); err != nil {
|
||||
_ = writer.CloseWithError(err)
|
||||
return
|
||||
}
|
||||
collector := newImagineCollector()
|
||||
emitted := 0
|
||||
partialIndex := 0
|
||||
for emitted < count {
|
||||
messageType, data, readErr := connection.ReadMessage()
|
||||
if readErr != nil {
|
||||
@@ -1040,7 +1104,6 @@ func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter
|
||||
return
|
||||
}
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, readErr)
|
||||
writeImagineStreamFailure(writer, streamID, "upstream_stream_error", "图片生成流意外中断")
|
||||
_ = writer.CloseWithError(readErr)
|
||||
return
|
||||
}
|
||||
@@ -1054,25 +1117,44 @@ func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter
|
||||
if message["type"] == "error" {
|
||||
upstreamErr := fmt.Errorf("Imagine WebSocket 返回错误")
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, upstreamErr)
|
||||
writeImagineStreamFailure(writer, streamID, "upstream_error", "上游图片生成失败")
|
||||
_ = writer.CloseWithError(upstreamErr)
|
||||
return
|
||||
}
|
||||
collector.Accept(message)
|
||||
if partialImages > 0 {
|
||||
for _, image := range collector.ReadyPreviews() {
|
||||
if partialIndex >= partialImages {
|
||||
continue
|
||||
}
|
||||
raw, err := a.imageBytes(ctx, credential, image)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
_ = writer.CloseWithError(ctx.Err())
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := writeSSE(writer, "image_generation.partial_image", openAIImageStreamEvent("image_generation.partial_image", image, raw, partialIndex)); err != nil {
|
||||
_ = writer.CloseWithError(err)
|
||||
return
|
||||
}
|
||||
partialIndex++
|
||||
}
|
||||
}
|
||||
for _, image := range collector.ReadyImages() {
|
||||
if emitted >= count {
|
||||
break
|
||||
}
|
||||
item, err := a.imageDataItem(ctx, credential, image, format)
|
||||
raw, err := a.imageBytes(ctx, credential, image)
|
||||
if err != nil {
|
||||
writeImagineStreamFailure(writer, streamID, "image_output_error", "图片结果处理失败")
|
||||
_ = writer.CloseWithError(err)
|
||||
return
|
||||
}
|
||||
if err := writeSSE(writer, "image_generation.image.completed", map[string]any{
|
||||
"type": "image_generation.image.completed", "id": streamID,
|
||||
"index": emitted, "image": item,
|
||||
}); err != nil {
|
||||
if err := a.saveStreamImage(ctx, raw); err != nil {
|
||||
_ = writer.CloseWithError(err)
|
||||
return
|
||||
}
|
||||
if err := writeSSE(writer, "image_generation.completed", openAIImageStreamEvent("image_generation.completed", image, raw, 0)); err != nil {
|
||||
_ = writer.CloseWithError(err)
|
||||
return
|
||||
}
|
||||
@@ -1080,31 +1162,51 @@ func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter
|
||||
}
|
||||
if collector.Done(modelConfig.NativeBatchSize) && emitted < count {
|
||||
incompleteErr := fmt.Errorf("上游仅返回 %d/%d 张可用图片", emitted, count)
|
||||
writeImagineStreamFailure(writer, streamID, "image_generation_incomplete", incompleteErr.Error())
|
||||
_ = writer.CloseWithError(incompleteErr)
|
||||
return
|
||||
}
|
||||
}
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, http.StatusOK, nil)
|
||||
if err := writeSSE(writer, "image_generation.completed", map[string]any{
|
||||
"type": "image_generation.completed", "id": streamID, "object": "image_generation",
|
||||
"created": createdAt, "model": "grok-imagine-image-quality", "status": "completed", "n": emitted,
|
||||
}); err != nil {
|
||||
_ = writer.CloseWithError(err)
|
||||
return
|
||||
}
|
||||
if _, err := io.WriteString(writer, "data: [DONE]\n\n"); err != nil {
|
||||
_ = writer.CloseWithError(err)
|
||||
return
|
||||
}
|
||||
_ = writer.Close()
|
||||
}
|
||||
|
||||
func writeImagineStreamFailure(writer io.Writer, streamID, code, message string) {
|
||||
_ = writeSSE(writer, "image_generation.failed", map[string]any{
|
||||
"type": "image_generation.failed", "id": streamID, "status": "failed",
|
||||
"error": map[string]any{"code": code, "message": message},
|
||||
})
|
||||
func openAIImageStreamEvent(eventType string, image imagineImageValue, raw []byte, partialIndex int) map[string]any {
|
||||
width, height := image.Width, image.Height
|
||||
size := "auto"
|
||||
if width > 0 && height > 0 {
|
||||
size = fmt.Sprintf("%dx%d", width, height)
|
||||
}
|
||||
value := map[string]any{
|
||||
"type": eventType, "b64_json": base64.StdEncoding.EncodeToString(raw),
|
||||
"created_at": time.Now().Unix(), "size": size, "quality": "auto",
|
||||
"background": "auto", "output_format": imageOutputFormat(raw),
|
||||
}
|
||||
if eventType == "image_generation.partial_image" {
|
||||
value["partial_image_index"] = partialIndex
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func imageOutputFormat(raw []byte) string {
|
||||
mimeType := http.DetectContentType(raw)
|
||||
switch mimeType {
|
||||
case "image/png":
|
||||
return "png"
|
||||
case "image/webp":
|
||||
return "webp"
|
||||
default:
|
||||
return "jpeg"
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Adapter) saveStreamImage(ctx context.Context, raw []byte) error {
|
||||
if a.assets == nil {
|
||||
return provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, fmt.Errorf("图片媒体存储未配置"))
|
||||
}
|
||||
if _, err := a.saveImageWithRetry(ctx, raw); err != nil {
|
||||
return provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) downloadImage(ctx context.Context, credential account.Credential, rawURL string) ([]byte, error) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -590,6 +591,32 @@ func TestImagineResolutionAndBatchMapping(t *testing.T) {
|
||||
t.Fatalf("resolution=%s count=%d config=%#v", test.resolution, test.count, config)
|
||||
}
|
||||
}
|
||||
config, _ := resolveImagineModel("imagine", "1k", 1)
|
||||
if got := imagineUpstreamGenerationCount(true, 1, config); got != 1 {
|
||||
t.Fatalf("streaming upstream count = %d, want 1", got)
|
||||
}
|
||||
if got := imagineUpstreamGenerationCount(false, 1, config); got != 4 {
|
||||
t.Fatalf("non-streaming upstream count = %d, want 4", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageStreamingRejectsMultipleOutputs(t *testing.T) {
|
||||
response, err := (&Adapter{}).GenerateImage(context.Background(), provider.ImageGenerationRequest{
|
||||
Model: "grok-imagine-image-quality", Prompt: "cat", Count: 2, Streaming: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(body, &payload) != nil {
|
||||
t.Fatalf("body=%s", body)
|
||||
}
|
||||
errorValue, _ := payload["error"].(map[string]any)
|
||||
if response.StatusCode != http.StatusBadRequest || errorValue["message"] != "Streaming is only supported with n=1." || errorValue["type"] != "image_generation_user_error" || errorValue["param"] != "input" || errorValue["code"] != "unsupported_parameter" {
|
||||
t.Fatalf("status=%d error=%#v", response.StatusCode, errorValue)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageAspectRatioFollowsXAIContractAndSizeAlias(t *testing.T) {
|
||||
@@ -629,6 +656,91 @@ func TestImagineCollectorHandlesOutOfOrderFrames(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestImagineCollectorIgnoresWebSocketPreviewFrames(t *testing.T) {
|
||||
collector := newImagineCollector()
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image", "id": "image-a", "order": 0.0,
|
||||
"percentage_complete": 50.0,
|
||||
"url": "https://imagine-public.x.ai/imagine-public/images/image-a.png",
|
||||
"blob": "preview",
|
||||
})
|
||||
previews := collector.ReadyPreviews()
|
||||
if len(previews) != 1 || previews[0].ID != "image-a" || previews[0].Blob != "preview" || len(collector.ReadyPreviews()) != 0 {
|
||||
t.Fatalf("previews = %#v", previews)
|
||||
}
|
||||
collector.Accept(map[string]any{
|
||||
"type": "json", "current_status": "completed", "image_id": "image-a",
|
||||
"order": 0.0, "moderated": false,
|
||||
})
|
||||
if collector.Done(1) || collector.UsableCount() != 0 || len(collector.Images()) != 0 {
|
||||
t.Fatalf("preview became final: %#v", collector)
|
||||
}
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image", "id": "image-a", "order": 0.0,
|
||||
"percentage_complete": 100.0,
|
||||
"url": "https://imagine-public.x.ai/imagine-public/images/image-a.jpg",
|
||||
"blob": "final",
|
||||
})
|
||||
if !collector.Done(1) || collector.UsableCount() != 1 {
|
||||
t.Fatalf("final image not recognized: %#v", collector)
|
||||
}
|
||||
images := collector.Images()
|
||||
if len(images) != 1 || images[0].URL != "https://imagine-public.x.ai/imagine-public/images/image-a.jpg" || images[0].Blob != "final" {
|
||||
t.Fatalf("images = %#v", images)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImagineCollectorKeepsInterleavedJobsIsolated(t *testing.T) {
|
||||
collector := newImagineCollector()
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image", "id": "image-a", "order": 0.0, "percentage_complete": 50.0, "blob": "a-preview",
|
||||
})
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image", "id": "image-b", "order": 1.0, "percentage_complete": 50.0, "blob": "b-preview",
|
||||
})
|
||||
previews := collector.ReadyPreviews()
|
||||
if len(previews) != 2 || previews[0].ID != "image-a" || previews[0].Blob != "a-preview" || previews[1].ID != "image-b" || previews[1].Blob != "b-preview" {
|
||||
t.Fatalf("previews = %#v", previews)
|
||||
}
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image", "id": "image-b", "order": 1.0, "percentage_complete": 100.0, "blob": "b-final",
|
||||
})
|
||||
collector.Accept(map[string]any{"type": "json", "current_status": "completed", "image_id": "image-b", "order": 1.0, "moderated": false})
|
||||
ready := collector.ReadyImages()
|
||||
if len(ready) != 1 || ready[0].ID != "image-b" || ready[0].Blob != "b-final" {
|
||||
t.Fatalf("first ready = %#v", ready)
|
||||
}
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image", "id": "image-a", "order": 0.0, "percentage_complete": 100.0, "blob": "a-final",
|
||||
})
|
||||
collector.Accept(map[string]any{"type": "json", "current_status": "completed", "image_id": "image-a", "order": 0.0, "moderated": false})
|
||||
ready = collector.ReadyImages()
|
||||
if len(ready) != 1 || ready[0].ID != "image-a" || ready[0].Blob != "a-final" {
|
||||
t.Fatalf("second ready = %#v", ready)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImagineCollectorCanReturnRequestedSubsetBeforeNativeBatchCompletes(t *testing.T) {
|
||||
collector := newImagineCollector()
|
||||
for index := 0; index < 3; index++ {
|
||||
id := fmt.Sprintf("image-%d", index)
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image", "id": id, "order": float64(index), "percentage_complete": 100.0,
|
||||
"url": "https://imagine-public.x.ai/imagine-public/images/" + id + ".jpg",
|
||||
})
|
||||
collector.Accept(map[string]any{
|
||||
"type": "json", "current_status": "completed", "image_id": id,
|
||||
"order": float64(index), "moderated": false,
|
||||
})
|
||||
}
|
||||
if collector.Done(4) || collector.UsableCount() != 3 {
|
||||
t.Fatalf("collector=%#v usable=%d", collector, collector.UsableCount())
|
||||
}
|
||||
if collector.UsableCount() < 2 {
|
||||
t.Fatal("a request for two images should already be satisfiable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImagineCollectorSettlesModeratedSlots(t *testing.T) {
|
||||
collector := newImagineCollector()
|
||||
collector.Accept(map[string]any{"type": "json", "current_status": "completed", "image_id": "blocked", "moderated": true})
|
||||
@@ -643,7 +755,7 @@ func TestGeneratedImageAssetHostsRemainStrict(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageStreamExtensionEventsAndPayloads(t *testing.T) {
|
||||
func TestImageStreamUsesOfficialOpenAIEventsWithoutTokenUsage(t *testing.T) {
|
||||
adapter := &Adapter{assets: imageAssetStoreStub{}}
|
||||
urlItem, err := adapter.imageDataItem(context.Background(), account.Credential{}, imagineImageValue{URL: "https://imgen.x.ai/image.jpg", Blob: "aW1hZ2U="}, "url")
|
||||
if err != nil || urlItem["url"] != "https://api.example/v1/media/images/img_test" || urlItem["mime_type"] != "image/jpeg" || urlItem["revised_prompt"] != "" {
|
||||
@@ -653,11 +765,22 @@ func TestImageStreamExtensionEventsAndPayloads(t *testing.T) {
|
||||
if err != nil || b64Item["b64_json"] != "aW1hZ2U=" || b64Item["mime_type"] != "image/jpeg" {
|
||||
t.Fatalf("base64 item = %#v, err=%v", b64Item, err)
|
||||
}
|
||||
png := []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n', 0, 0, 0, 0, 'I', 'H', 'D', 'R'}
|
||||
partial := openAIImageStreamEvent("image_generation.partial_image", imagineImageValue{ID: "image-a", Width: 960, Height: 960}, png, 0)
|
||||
if partial["type"] != "image_generation.partial_image" || partial["partial_image_index"] != 0 || partial["size"] != "960x960" || partial["output_format"] != "png" || partial["usage"] != nil {
|
||||
t.Fatalf("partial event = %#v", partial)
|
||||
}
|
||||
completed := openAIImageStreamEvent("image_generation.completed", imagineImageValue{ID: "image-a", Width: 960, Height: 960}, []byte("jpeg"), 0)
|
||||
if completed["type"] != "image_generation.completed" || completed["partial_image_index"] != nil || completed["quality"] != "auto" || completed["usage"] != nil {
|
||||
t.Fatalf("completed event = %#v", completed)
|
||||
}
|
||||
var output bytes.Buffer
|
||||
writeImagineStreamFailure(&output, "imggen_test", "upstream_error", "generation failed")
|
||||
if err := writeSSE(&output, "image_generation.partial_image", partial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
value := output.String()
|
||||
if !strings.Contains(value, "event: image_generation.failed") || !strings.Contains(value, `"id":"imggen_test"`) || !strings.Contains(value, `"code":"upstream_error"`) {
|
||||
t.Fatalf("failure event = %q", value)
|
||||
if !strings.Contains(value, "event: image_generation.partial_image") || strings.Contains(value, "image_generation.started") || strings.Contains(value, "image_generation.image.completed") || strings.Contains(value, `"usage"`) {
|
||||
t.Fatalf("stream event = %q", value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ type imageGenerationRequest struct {
|
||||
Model string `json:"model"`
|
||||
Prompt string `json:"prompt"`
|
||||
Count *int `json:"n"`
|
||||
PartialImages *int `json:"partial_images"`
|
||||
Size string `json:"size"`
|
||||
AspectRatio string `json:"aspect_ratio"`
|
||||
Resolution string `json:"resolution"`
|
||||
@@ -265,6 +266,22 @@ func (h *Handler) generateImage(c *gin.Context) {
|
||||
}
|
||||
count = *request.Count
|
||||
}
|
||||
if request.Stream && count != 1 {
|
||||
writeImageGenerationUserError(c, "unsupported_parameter", "input", "Streaming is only supported with n=1.")
|
||||
return
|
||||
}
|
||||
partialImages := 0
|
||||
if request.PartialImages != nil {
|
||||
if *request.PartialImages < 0 || *request.PartialImages > 3 {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "partial_images 必须在 0 到 3 之间")
|
||||
return
|
||||
}
|
||||
partialImages = *request.PartialImages
|
||||
if partialImages > 0 && !request.Stream {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "partial_images 仅可在 stream=true 时使用")
|
||||
return
|
||||
}
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
@@ -272,7 +289,8 @@ func (h *Handler) generateImage(c *gin.Context) {
|
||||
result, err := h.gateway.GenerateImage(c.Request.Context(), gateway.ImageGenerationInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: request.Model, Prompt: request.Prompt,
|
||||
Count: count, Size: request.Size, AspectRatio: request.AspectRatio,
|
||||
Resolution: request.Resolution, ResponseFormat: request.ResponseFormat, Streaming: request.Stream,
|
||||
Resolution: request.Resolution, ResponseFormat: request.ResponseFormat,
|
||||
Streaming: request.Stream, PartialImages: partialImages,
|
||||
})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
@@ -1025,6 +1043,12 @@ func writeOpenAIError(c *gin.Context, status int, code, message string) {
|
||||
c.AbortWithStatusJSON(status, gin.H{"error": gin.H{"message": message, "type": errorType, "code": code, "param": nil}})
|
||||
}
|
||||
|
||||
func writeImageGenerationUserError(c *gin.Context, code, param, message string) {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": gin.H{
|
||||
"message": message, "type": "image_generation_user_error", "param": param, "code": code,
|
||||
}})
|
||||
}
|
||||
|
||||
func writeGatewayError(c *gin.Context, err error) {
|
||||
status, code := http.StatusBadGateway, "upstream_unavailable"
|
||||
message := "上游服务暂不可用"
|
||||
|
||||
@@ -300,6 +300,59 @@ func TestImageEditAcceptsOfficialJSONShape(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageGenerationValidatesOpenAIPartialImages(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
NewHandler(nil, nil, 1<<20).Register(router.Group("/v1"))
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{name: "negative", body: `{"model":"grok-imagine-image-quality","prompt":"cat","stream":true,"partial_images":-1}`},
|
||||
{name: "too many", body: `{"model":"grok-imagine-image-quality","prompt":"cat","stream":true,"partial_images":4}`},
|
||||
{name: "requires stream", body: `{"model":"grok-imagine-image-quality","prompt":"cat","partial_images":1}`},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/images/generations", strings.NewReader(test.body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "partial_images") {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
invalidStreamingCount := httptest.NewRequest(http.MethodPost, "/v1/images/generations", strings.NewReader(`{
|
||||
"model":"grok-imagine-image-quality","prompt":"cat","n":2,"stream":true
|
||||
}`))
|
||||
invalidStreamingCount.Header.Set("Content-Type", "application/json")
|
||||
invalidStreamingCountRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(invalidStreamingCountRecorder, invalidStreamingCount)
|
||||
if invalidStreamingCountRecorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("stream n status=%d body=%s", invalidStreamingCountRecorder.Code, invalidStreamingCountRecorder.Body.String())
|
||||
}
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(invalidStreamingCountRecorder.Body.Bytes(), &payload) != nil {
|
||||
t.Fatalf("stream n body=%s", invalidStreamingCountRecorder.Body.String())
|
||||
}
|
||||
errorValue, _ := payload["error"].(map[string]any)
|
||||
if errorValue["message"] != "Streaming is only supported with n=1." || errorValue["type"] != "image_generation_user_error" || errorValue["param"] != "input" || errorValue["code"] != "unsupported_parameter" {
|
||||
t.Fatalf("stream n error=%#v", errorValue)
|
||||
}
|
||||
|
||||
valid := httptest.NewRequest(http.MethodPost, "/v1/images/generations", strings.NewReader(`{
|
||||
"model":"grok-imagine-image-quality","prompt":"cat","n":1,"stream":true,"partial_images":1
|
||||
}`))
|
||||
valid.Header.Set("Content-Type", "application/json")
|
||||
validRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(validRecorder, valid)
|
||||
if validRecorder.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("valid status=%d body=%s", validRecorder.Code, validRecorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractUsageFromCompletedEvent(t *testing.T) {
|
||||
metadata := extractMetadata([]byte(`{"type":"response.completed","response":{"id":"resp_1","model":"grok-4.5-build-free","usage":{"input_tokens":10,"input_tokens_details":{"cached_tokens":4},"output_tokens":5,"output_tokens_details":{"reasoning_tokens":2},"total_tokens":15,"cost_in_usd_ticks":158500,"num_sources_used":1,"num_server_side_tools_used":2,"context_details":{"input_tokens":9,"output_tokens":4}}}}`))
|
||||
usage := metadata.Usage
|
||||
|
||||
@@ -39,6 +39,8 @@ type SwaggerImageGenerationRequest struct {
|
||||
AspectRatio string `json:"aspect_ratio,omitempty" example:"16:9"`
|
||||
Resolution string `json:"resolution,omitempty" example:"2k"`
|
||||
ResponseFormat string `json:"response_format,omitempty" example:"url"`
|
||||
Stream bool `json:"stream,omitempty" example:"false"`
|
||||
PartialImages int `json:"partial_images,omitempty" example:"0"`
|
||||
}
|
||||
|
||||
// SwaggerImageReference 表示图片 URL 输入。
|
||||
|
||||
Reference in new issue
Block a user