Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import type { GoogleBatchRecord } from '@api/ai-providers/google/types';
import { createLineSplitter } from '@api/handlers/stream-handler-utils';
import type {
RequestHandlerFunction,
ResponseTransformFunction,
} from '@shared/types/ai-providers/config';
import { FunctionName } from '@shared/types/api/request';
import type { RetrieveBatchResponseBody } from '@shared/types/api/routes/batch-api';
import { AIProvider } from '@shared/types/constants';
import { responseTransformers } from '../open-ai-base';
import { vertexAPIConfig } from './api';
import {
vertexAnthropicChatCompleteResponseTransform,
vertexGoogleChatCompleteResponseTransform,
vertexLlamaChatCompleteResponseTransform,
} from './chat-complete';
import { getModelAndProvider } from './utils';
const responseTransforms = {
google: vertexGoogleChatCompleteResponseTransform,
anthropic: vertexAnthropicChatCompleteResponseTransform,
meta: vertexLlamaChatCompleteResponseTransform,
endpoints: responseTransformers(AIProvider.GOOGLE_VERTEX_AI, {
chatComplete: true,
})[FunctionName.CHAT_COMPLETE],
};
type TransformFunction = (response: unknown) => Record<string, unknown>;
const getOpenAIBatchRow = ({
row,
batchId,
transform,
}: {
row: Record<string, unknown>;
transform: TransformFunction;
batchId: string;
}): Record<string, unknown> => {
const response = (row.response ?? {}) as Record<string, unknown>;
const id = `batch-${batchId}-${response.responseId}`;
return {
id,
custom_id: response.responseId,
response: {
status_code: 200,
request_id: id,
body: transform(response),
},
error: null,
};
};
export const googleBatchOutputRequestHandler: RequestHandlerFunction = async ({
c,
saTarget,
saRequestData,
}) => {
const headers = await vertexAPIConfig.headers({
c,
saTarget,
saRequestData,
});
const options = {
method: 'GET',
headers,
};
// URL: <gateway>/v1/batches/<batchId>/output
const batchId = saRequestData.url.split('/').at(-2);
// const batchDetailsURL = saRequestData.url.replace(/\/output$/, ''); // TODO: Fix this
const baseURL = await vertexAPIConfig.getBaseURL({
c,
saTarget,
saRequestData,
});
const endpoint = vertexAPIConfig.getEndpoint({
c,
saTarget,
saRequestData,
});
const batchesURL = `${baseURL}${endpoint}`;
let modelName = '';
let outputURL = '';
try {
const response = await fetch(batchesURL, options);
if (!response.ok) {
const error = await response.text();
throw new Error(error);
}
const data = (await response.json()) as GoogleBatchRecord;
outputURL = data.outputInfo?.gcsOutputDirectory ?? '';
modelName = data.model;
} catch (error) {
const errorMessage =
(error as Error).message || 'Failed to retrieve batch output';
throw new Error(errorMessage);
}
if (!outputURL) {
throw new Error('Failed to retrieve batch details');
}
const { provider } = getModelAndProvider(modelName ?? '');
const responseTransform =
responseTransforms[provider as keyof typeof responseTransforms] ||
responseTransforms.endpoints;
outputURL = outputURL.replace('gs://', 'https://storage.googleapis.com/');
const outputResponse = await fetch(`${outputURL}/predictions.jsonl`, options);
const reader = outputResponse.body;
if (!reader) {
throw new Error('Failed to retrieve batch output');
}
const encoder = new TextEncoder();
// Prepare a transform stream to process complete lines.
const responseStream = new TransformStream({
transform(
chunk: Uint8Array,
controller: TransformStreamDefaultController,
): void {
let buffer = '';
try {
const json = JSON.parse(chunk.toString());
const row = getOpenAIBatchRow({
row: json,
batchId: batchId ?? '',
transform: responseTransform as unknown as TransformFunction,
});
buffer = JSON.stringify(row);
} catch {
return;
}
controller.enqueue(encoder.encode(`${buffer}\n`));
},
flush(controller: TransformStreamDefaultController): void {
controller.terminate();
},
});
const [safeStream] = responseStream.readable.tee();
// Pipe the node stream through the line splitter and then to the response stream.
const lineSplitter = createLineSplitter();
reader.pipeThrough(lineSplitter).pipeTo(responseStream.writable);
return new Response(safeStream, {
headers: { 'Content-Type': 'application/octet-stream' },
});
};
export const BatchOutputResponseTransform: ResponseTransformFunction = (
response,
) => {
return response as unknown as RetrieveBatchResponseBody;
};
|