File size: 3,722 Bytes
e81f4e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { RuntimeConfig } from "../config";
import type { CompletionProvider } from "./ports";
import { resolveModel } from "../models";
import type { ResolvedModel } from "../models";
import {
	googleFunctionCallingConfig,
	parseGoogleToolChoicePolicy,
	validateGoogleToolChoiceConfig,
} from "../toolcall/policy-google";
import {
	createToolBundle,
	filterToolBundleByPolicy,
} from "../toolcall/tool-bundle";
import { googleToolChoiceInstruction } from "../promptcompat/google";
import { log } from "../shared/logging";
import {
	upstreamErrorCode,
	upstreamErrorMessage,
	upstreamErrorStatus,
} from "../shared/errors";
import { prepareGoogleGeminiContext } from "./context";
import { ensureInlineToolPrompt } from "./tool-prompt-guard";
import type { ContextFileResult, FileRef, LooseRequest } from "./types";
import { hasCompletionError } from "./types";

export type GoogleCompletionPrepareError = {
	message: string;
	status: number;
	code?: string;
};

export type PreparedGoogleCompletion = {
	rm: Extract<ResolvedModel, { name: string }>;
	effectiveReq: LooseRequest;
	effectiveGoogleTools: LooseRequest[] | null;
	hasTools: boolean;
	prompt: string;
	fileRefs: FileRef[] | null;
	promptTokens: number;
	contextFiles: ContextFileResult | null;
};

export async function prepareGoogleCompletion(
	cfg: RuntimeConfig,
	provider: CompletionProvider,
	req: LooseRequest,
	path: string,
): Promise<PreparedGoogleCompletion | { error: GoogleCompletionPrepareError }> {
	const m = /\/v(?:1beta|1)\/models\/([^:?/]+)/.exec(path);
	const modelFromPath = m?.[1]
		? decodeURIComponent(m[1]).replace(/^models\//, "")
		: undefined;
	const rm = resolveModel(modelFromPath, cfg.default_model);
	if (rm.name === undefined) {
		log(
			cfg,
			`google completion model rejected model=${String(modelFromPath ?? "(default)")}`,
		);
		return {
			error: { message: rm.error, status: 400, code: "model_not_found" },
		};
	}

	const toolBundle = createToolBundle(req.tools);
	const toolConfigViolation = validateGoogleToolChoiceConfig(req, toolBundle);
	if (toolConfigViolation) {
		return {
			error: {
				message: toolConfigViolation.message,
				status: 400,
				code: "invalid_tool_choice",
			},
		};
	}

	const fcMode = String(googleFunctionCallingConfig(req).mode || "AUTO")
		.trim()
		.toUpperCase();
	const toolPolicy = parseGoogleToolChoicePolicy(req, toolBundle);
	const effectiveToolBundle = filterToolBundleByPolicy(toolBundle, toolPolicy);
	const effectiveGoogleTools = effectiveToolBundle.openAIFunctionTools.length
		? effectiveToolBundle.openAIFunctionTools
		: null;
	const effectiveReq = { ...req, tools: effectiveGoogleTools || [] };
	const hasTools = !!effectiveGoogleTools && fcMode !== "NONE";
	const toolChoiceInstruction = googleToolChoiceInstruction(effectiveReq);
	const ctx = await prepareGoogleGeminiContext(
		cfg,
		provider,
		effectiveReq,
		hasTools,
		effectiveToolBundle,
		toolChoiceInstruction,
	);
	if (hasCompletionError(ctx)) {
		const code = upstreamErrorCode(ctx.error) || "context_file_upload_failed";
		return {
			error: {
				message: upstreamErrorMessage(ctx.error),
				status: upstreamErrorStatus(ctx.error) || 502,
				code,
			},
		};
	}
	let { prompt } = ctx;
	const { fileRefs, promptTokens, contextFiles } = ctx;
	const promptToolSource = effectiveToolBundle.defs.length
		? effectiveToolBundle
		: toolBundle;
	prompt = ensureInlineToolPrompt(
		prompt,
		promptToolSource,
		toolChoiceInstruction,
		contextFiles,
		ctx.promptMetadata,
	);
	if (!String(prompt || "").trim())
		return { error: { message: "empty content", status: 400 } };

	return {
		rm,
		effectiveReq,
		effectiveGoogleTools,
		hasTools,
		prompt,
		fileRefs,
		promptTokens,
		contextFiles,
	};
}