File size: 3,604 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
import { streamBufferedToolTextCompletionEvents } from "./runtime";
import type { CompletionProvider } from "./ports";
import type { ResolvedModel } from "../models";
import {
	combinedTokenCount,
	createTokenCounter,
	emptyTokenCounts,
} from "../shared/tokens";
import { parseGoogleFunctionCalls } from "../toolcall/google";
import { validateGoogleFunctionCalls } from "../toolcall/policy-google";
import type { ToolPolicyViolation } from "../toolcall/policy-openai";
import type { GoogleFunctionCall } from "../toolcall/google";
import type { GoogleResponsePart } from "./google-turn";
import type { FileRef, LooseRequest } from "./types";
import { EMPTY_UPSTREAM_MSG } from "./turn";

export type GoogleToolCompletionEvent =
	| {
			type: "candidate";
			parts: GoogleResponsePart[] | null;
			finishReason: string | null;
	  }
	| { type: "warning"; error: unknown; message?: string }
	| { type: "error"; error: unknown }
	| { type: "tool_policy_violation"; violation: ToolPolicyViolation }
	| {
			type: "done";
			usageMetadata: {
				promptTokenCount: number;
				candidatesTokenCount: number;
				totalTokenCount: number;
			};
	  };

type GoogleToolCompletionParams = {
	prompt: string;
	rm: Extract<ResolvedModel, { name: string }>;
	fileRefs: FileRef[] | null;
	tools: LooseRequest[] | null;
	effectiveReq: LooseRequest;
	promptTokens: number;
	signal: AbortSignal;
};

export async function* streamGoogleToolCompletionEvents(
	provider: CompletionProvider,
	params: GoogleToolCompletionParams,
): AsyncIterable<GoogleToolCompletionEvent> {
	const { prompt, rm, fileRefs, tools, effectiveReq, promptTokens, signal } =
		params;
	const extraTokenCounter = createTokenCounter();
	let completionCounts = emptyTokenCounts();
	let buffered = "";
	let emittedText = false;
	let issue: { error: unknown } | null = null;

	for await (const event of streamBufferedToolTextCompletionEvents(
		provider,
		{ prompt, rm, fileRefs },
		{ signal },
	)) {
		if (event.type === "text_delta") {
			emittedText = true;
			yield {
				type: "candidate",
				parts: [{ text: event.text }],
				finishReason: null,
			};
		} else if (event.type === "buffered_text") {
			buffered += event.text;
		} else if (event.type === "warning" || event.type === "stream_error") {
			issue = event;
		} else if (event.type === "done") {
			completionCounts = event.completionCounts;
		}
	}

	const [clean, functionCalls]: [string, GoogleFunctionCall[]] =
		parseGoogleFunctionCalls(buffered, tools);
	if (clean) {
		extraTokenCounter.append(clean);
		yield { type: "candidate", parts: [{ text: clean }], finishReason: null };
	}

	const violation = validateGoogleFunctionCalls(effectiveReq, functionCalls);
	if (violation) {
		yield { type: "tool_policy_violation", violation };
		return;
	}
	if (functionCalls?.length) {
		if (issue) yield { type: "warning", error: issue.error };
		yield {
			type: "candidate",
			parts: functionCalls.map((fc) => ({
				functionCall: { name: fc.name, args: fc.args || {} },
			})),
			finishReason: null,
		};
	} else if (!emittedText && !clean) {
		yield {
			type: "error",
			error: issue?.error || {
				message: EMPTY_UPSTREAM_MSG,
				code: "upstream_empty",
			},
		};
		return;
	} else if (issue) {
		yield { type: "warning", error: issue.error };
	}
	const candidateTokens = combinedTokenCount(
		completionCounts,
		extraTokenCounter,
	);
	const promptTokenCount = Math.max(0, Number(promptTokens) || 0);
	yield {
		type: "done",
		usageMetadata: {
			promptTokenCount,
			candidatesTokenCount: candidateTokens,
			totalTokenCount: promptTokenCount + candidateTokens,
		},
	};
}