File size: 9,338 Bytes
f9a28cd
b1cfe1b
4588c8c
 
 
 
 
 
b1cfe1b
 
 
 
 
11486ce
c7d34c1
 
b1cfe1b
96bdf6c
c7d34c1
 
e445b51
 
 
c7d34c1
 
 
 
 
f9a28cd
c7d34c1
11486ce
4588c8c
e445b51
 
c7d34c1
 
 
 
 
11486ce
 
 
4588c8c
 
 
 
 
11486ce
 
 
 
 
 
c7d34c1
 
e445b51
b1cfe1b
e445b51
 
 
 
 
c7d34c1
e445b51
c7d34c1
 
 
 
 
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
e445b51
11486ce
 
e445b51
 
 
 
 
f9a28cd
 
 
 
 
 
b1cfe1b
 
f9a28cd
b1cfe1b
 
96bdf6c
 
 
f9a28cd
 
a2c232b
 
 
 
f9a28cd
 
96bdf6c
 
f9a28cd
 
 
 
 
96bdf6c
 
f9a28cd
 
11486ce
 
 
96bdf6c
c7d34c1
 
4588c8c
e445b51
 
 
 
4588c8c
 
 
 
c7d34c1
 
 
b1cfe1b
c7d34c1
 
e445b51
4588c8c
 
 
 
 
 
 
 
 
 
 
 
 
 
e445b51
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import { CHANNEL_REQUEST_MODES, CHANNEL_REQUEST_MODE_ADMIN_CONTROL } from '@/lib/channel-request-mode';
import { getChannelPoolSummary, toPublicChannelFailure } from '@/lib/channel-router';
import {
    getImageBackendCompatibility,
    getImageCountRangeCompatibilityForBackend,
    getPartialImagesRangeCompatibilityForBackend,
    summarizeImageUpstreamProfile
} from '@/lib/image-upstream-profile';
import {
    readImageGenerationBackend,
    readImageStreamMode,
    readImageStreamingStrategy
} from '@/lib/image-upstream-strategy';
import { summarizeOpenAIImageTransport } from '@/lib/openai-image-transport';
import { getServerChannelState } from '@/lib/server-channel-router';
import { readBooleanEnv, readPositiveIntegerEnv } from '@/lib/server-runtime';
import { computeStreamingBatchRecommendation } from '@/lib/streaming-batch';
import { getWebuiImageCleanupSummary } from '@/lib/webui-image-cleanup-runtime';
import { NextResponse } from 'next/server';

const RESPONSES_IMAGE_BACKEND_REQUIRED_ENV = ['ENABLE_RESPONSES_IMAGE_BACKEND'] as const;
const RESPONSES_IMAGE_BACKEND_OPTIONAL_ENV = ['OPENAI_RESPONSES_API_MODEL'] as const;

export async function GET() {
    try {
        const serverChannelState = getServerChannelState();
        const summary = getChannelPoolSummary(serverChannelState.config);
        const healthSummary = serverChannelState.router?.getHealthSummary();
        const requestModeHealthSummary = serverChannelState.router?.getRequestModeHealthSummary();
        const maxStreamsPerCredential = readPositiveIntegerEnv(process.env, 'OPENAI_MAX_STREAMS_PER_CREDENTIAL', 1);
        const channelQueueSummary = serverChannelState.channelCapacityQueue.summary();
        const responsesImageBackendFeatureEnabled = readBooleanEnv(process.env, 'ENABLE_RESPONSES_IMAGE_BACKEND');
        const responsesImageBackendHasDefaultModel = Boolean(process.env.OPENAI_RESPONSES_API_MODEL?.trim());
        const responsesImageBackendMissingEnv = readResponsesImageBackendMissingEnv(process.env);
        const recommendedStreamingConcurrency = computeStreamingBatchRecommendation({
            credentialCount: healthSummary?.healthyCredentialCount ?? summary.credentialCount,
            maxStreamsPerCredential,
            strategy: summary.strategy
        });
        const upstreamProfile = summarizeImageUpstreamProfile({
            serverProfiles: summary.channels.map((channel) => channel.effectiveProfile)
        });
        const responsesImageBackendIncompatibleConstraints = readResponsesImageBackendIncompatibleConstraints(
            upstreamProfile.activeConstraints
        );
        const responsesImageBackendEnabled =
            responsesImageBackendFeatureEnabled && responsesImageBackendIncompatibleConstraints.length === 0;
        const providerManifests = summary.channels
            .filter((channel) => channel.providerManifest)
            .map((channel) => ({
                channelId: channel.id,
                manifest: channel.providerManifest
            }));

        return NextResponse.json({
            streaming: {
                defaultBackend: readImageGenerationBackend(new FormData(), process.env),
                defaultMode: readImageStreamMode(new FormData(), process.env),
                defaultStrategy: readImageStreamingStrategy(new FormData(), process.env),
                unavailableMarkScope: 'channel+backend+strategy+operation',
                availability: serverChannelState.streamingAvailability.summary()
            },
            streamingBatch: {
                enabled: true,
                recommendedConcurrency: recommendedStreamingConcurrency,
                requestCredentialConcurrency: maxStreamsPerCredential,
                healthyCredentialCount: healthSummary?.healthyCredentialCount ?? summary.credentialCount,
                unhealthyCredentialCount: healthSummary?.unhealthyCredentialCount ?? 0,
                channelCount: healthSummary?.channelCount ?? summary.channelCount,
                healthyChannelCount: healthSummary?.healthyChannelCount ?? summary.channelCount,
                unhealthyChannelCount: healthSummary?.unhealthyChannelCount ?? 0,
                lastFailure: toPublicChannelFailure(healthSummary?.lastFailure)
            },
            channelQueue: {
                enabled: channelQueueSummary.enabled,
                capacityPerCredential: channelQueueSummary.capacityPerKey,
                maxWaitMs: channelQueueSummary.maxWaitMs,
                maxSize: channelQueueSummary.maxSize,
                active: channelQueueSummary.active,
                queued: channelQueueSummary.queued,
                credentials: channelQueueSummary.keys.map((item) => ({
                    credentialId: item.key,
                    active: item.active,
                    queued: item.queued
                }))
            },
            channelRecovery: {
                failureCooldownEnabled: serverChannelState.channelRecovery.failureCooldownEnabled,
                failureCooldownMs: serverChannelState.channelRecovery.failureCooldownMs,
                requireProbeForRecovery: serverChannelState.channelRecovery.requireProbeForRecovery,
                pendingProbeCredentialCount: healthSummary?.pendingRecoveryProbeCredentialCount ?? 0,
                pendingProbeChannelCount: healthSummary?.pendingRecoveryProbeChannelCount ?? 0,
                probe: serverChannelState.channelRecoveryProber?.summary()
            },
            channelRouting: {
                strategy: summary.strategy,
                credentialCount: summary.credentialCount,
                channelCount: summary.channelCount,
                supportedRequestModes: CHANNEL_REQUEST_MODES,
                configuredRequestModes:
                    requestModeHealthSummary?.configuredRequestModes ??
                    (summary.credentialCount > 0 ? CHANNEL_REQUEST_MODES : []),
                effectiveRequestModes:
                    requestModeHealthSummary?.effectiveRequestModes ??
                    (summary.credentialCount > 0 ? CHANNEL_REQUEST_MODES : []),
                defaultRequestModePriority:
                    requestModeHealthSummary?.defaultRequestModePriority ??
                    CHANNEL_REQUEST_MODE_ADMIN_CONTROL.defaultPriority,
                requestModeControls: CHANNEL_REQUEST_MODE_ADMIN_CONTROL,
                requestModeHealth: requestModeHealthSummary?.modes ?? [],
                upstreamProxyByChannel: summary.channels.map((channel) => ({
                    channelId: channel.id,
                    upstreamProxy: channel.upstreamProxy
                })),
                requestModesByChannel: summary.channels.map((channel) => ({
                    channelId: channel.id,
                    requestModes: channel.requestModes,
                    requestModePriority: channel.requestModePriority
                })),
                effectiveRequestModesByChannel:
                    requestModeHealthSummary?.effectiveRequestModesByChannel ??
                    summary.channels.map((channel) => ({
                        channelId: channel.id,
                        requestModes: channel.requestModes,
                        requestModePriority: channel.requestModePriority
                    }))
            },
            upstreamProfile,
            imageTransport: summarizeOpenAIImageTransport(process.env),
            providerManifests,
            webuiImageCleanup: await getWebuiImageCleanupSummary(process.env),
            responsesImageBackend: {
                enabled: responsesImageBackendEnabled,
                featureEnabled: responsesImageBackendFeatureEnabled,
                mode: 'experimental',
                requiredEnv: [...RESPONSES_IMAGE_BACKEND_REQUIRED_ENV],
                optionalEnv: [...RESPONSES_IMAGE_BACKEND_OPTIONAL_ENV],
                hasDefaultModel: responsesImageBackendHasDefaultModel,
                missingEnv: responsesImageBackendMissingEnv,
                ...(responsesImageBackendIncompatibleConstraints.length > 0
                    ? { incompatibleConstraints: responsesImageBackendIncompatibleConstraints }
                    : {})
            }
        });
    } catch (error) {
        return NextResponse.json({ error: error instanceof Error ? error.message : '配置错误' }, { status: 500 });
    }
}

function readResponsesImageBackendIncompatibleConstraints(profile: Parameters<typeof getImageBackendCompatibility>[0]) {
    const incompatible: string[] = [];
    if (!getImageCountRangeCompatibilityForBackend(profile, 'generate', 'responses-image-generation').compatible) {
        incompatible.push('generate_images');
    }
    if (!getImageCountRangeCompatibilityForBackend(profile, 'edit', 'responses-image-generation').compatible) {
        incompatible.push('edit_images');
    }
    if (!getPartialImagesRangeCompatibilityForBackend(profile, 'responses-image-generation').compatible) {
        incompatible.push('partial_images');
    }
    return incompatible;
}

function readResponsesImageBackendMissingEnv(env: Record<string, string | undefined>): string[] {
    const missing: string[] = [];
    if (!readBooleanEnv(env, 'ENABLE_RESPONSES_IMAGE_BACKEND')) {
        missing.push('ENABLE_RESPONSES_IMAGE_BACKEND');
    }
    return missing;
}