|
| 1 | +import {ChatWrapper, ChatWrapperJinjaMatchConfiguration} from "../ChatWrapper.js"; |
| 2 | +import { |
| 3 | + ChatModelFunctionCall, ChatModelFunctions, ChatModelResponse, ChatWrapperGenerateContextStateOptions, ChatWrapperGeneratedContextState, |
| 4 | + ChatWrapperSettings |
| 5 | +} from "../types.js"; |
| 6 | +import {LlamaText, SpecialToken, SpecialTokensText} from "../utils/LlamaText.js"; |
| 7 | +import {jsonDumps} from "./utils/jsonDumps.js"; |
| 8 | + |
| 9 | +// source: https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4 |
| 10 | +export class Gemma4ChatWrapper extends ChatWrapper { |
| 11 | + public readonly wrapperName: string = "Gemma 4"; |
| 12 | + |
| 13 | + public readonly reasoning: boolean; |
| 14 | + public readonly keepOnlyLastThought: boolean; |
| 15 | + |
| 16 | + public override readonly settings: ChatWrapperSettings = { |
| 17 | + supportsSystemMessages: true, |
| 18 | + functions: { |
| 19 | + call: { |
| 20 | + optionalPrefixSpace: false, |
| 21 | + prefix: LlamaText(new SpecialTokensText("<|tool_call>call:")), |
| 22 | + paramsPrefix: "{", |
| 23 | + suffix: LlamaText(new SpecialTokensText("}<tool_call|>")), |
| 24 | + emptyCallParamsPlaceholder: undefined |
| 25 | + }, |
| 26 | + result: { |
| 27 | + prefix: LlamaText(new SpecialTokensText("<tool_response>response:"), "{{functionName}}", "{"), |
| 28 | + suffix: LlamaText(new SpecialTokensText("}</tool_response>")) |
| 29 | + } |
| 30 | + }, |
| 31 | + segments: { |
| 32 | + reiterateStackAfterFunctionCalls: true, |
| 33 | + thought: { |
| 34 | + prefix: LlamaText(new SpecialTokensText("<|channel>thought\n")), |
| 35 | + suffix: LlamaText(new SpecialTokensText("<channel|>")) |
| 36 | + } |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + public constructor(options: { |
| 41 | + /** |
| 42 | + * Whether to promote the model to perform reasoning. |
| 43 | + * |
| 44 | + * Defaults to `true`. |
| 45 | + */ |
| 46 | + reasoning?: boolean, |
| 47 | + |
| 48 | + /** |
| 49 | + * Whether to keep only the chain of thought from the last model response. |
| 50 | + * |
| 51 | + * Setting this to `false` will keep all the chain of thoughts from the model responses in the context state. |
| 52 | + * |
| 53 | + * Defaults to `true`. |
| 54 | + */ |
| 55 | + keepOnlyLastThought?: boolean |
| 56 | + } = {}) { |
| 57 | + super(); |
| 58 | + |
| 59 | + const { |
| 60 | + reasoning = true, |
| 61 | + keepOnlyLastThought = true |
| 62 | + } = options; |
| 63 | + |
| 64 | + this.reasoning = reasoning; |
| 65 | + this.keepOnlyLastThought = keepOnlyLastThought; |
| 66 | + } |
| 67 | + |
| 68 | + public override generateContextState({ |
| 69 | + chatHistory, availableFunctions, documentFunctionParams |
| 70 | + }: ChatWrapperGenerateContextStateOptions): ChatWrapperGeneratedContextState { |
| 71 | + const hasFunctions = Object.keys(availableFunctions ?? {}).length > 0; |
| 72 | + const modifiedChatHistory = chatHistory.slice(); |
| 73 | + |
| 74 | + let systemMessage: LlamaText = LlamaText(); |
| 75 | + if (modifiedChatHistory[0]?.type === "system") { |
| 76 | + systemMessage = LlamaText.fromJSON(modifiedChatHistory[0].text); |
| 77 | + modifiedChatHistory.shift(); |
| 78 | + } |
| 79 | + |
| 80 | + if (hasFunctions) |
| 81 | + systemMessage = LlamaText([ |
| 82 | + systemMessage, |
| 83 | + this.generateAvailableFunctionsSystemText(availableFunctions ?? {}, {documentParams: documentFunctionParams}) |
| 84 | + ]); |
| 85 | + |
| 86 | + if (this.reasoning) |
| 87 | + systemMessage = LlamaText([ |
| 88 | + new SpecialTokensText("<|think|>"), |
| 89 | + systemMessage |
| 90 | + ]); |
| 91 | + |
| 92 | + if (systemMessage.values.length > 0) |
| 93 | + modifiedChatHistory.unshift({ |
| 94 | + type: "system", |
| 95 | + text: systemMessage.toJSON() |
| 96 | + }); |
| 97 | + |
| 98 | + const contextContent: LlamaText[] = [ |
| 99 | + LlamaText(new SpecialToken("BOS")) |
| 100 | + ]; |
| 101 | + |
| 102 | + for (let i = 0; i < modifiedChatHistory.length; i++) { |
| 103 | + const isLastItem = i === modifiedChatHistory.length - 1; |
| 104 | + const item = modifiedChatHistory[i]; |
| 105 | + |
| 106 | + if (item == null) |
| 107 | + continue; |
| 108 | + |
| 109 | + if (item.type === "system") |
| 110 | + contextContent.push( |
| 111 | + LlamaText([ |
| 112 | + new SpecialTokensText("<|turn>system\n"), |
| 113 | + LlamaText.fromJSON(item.text), |
| 114 | + isLastItem |
| 115 | + ? LlamaText([]) |
| 116 | + : new SpecialTokensText("<turn|>\n") |
| 117 | + ]) |
| 118 | + ); |
| 119 | + else if (item.type === "user") |
| 120 | + contextContent.push( |
| 121 | + LlamaText([ |
| 122 | + new SpecialTokensText("<|turn>user\n"), |
| 123 | + item.text, |
| 124 | + isLastItem |
| 125 | + ? LlamaText([]) |
| 126 | + : new SpecialTokensText("<turn|>\n") |
| 127 | + ]) |
| 128 | + ); |
| 129 | + else if (item.type === "model") |
| 130 | + contextContent.push(this._getModelResponse(item.response, true, isLastItem, this.keepOnlyLastThought)); |
| 131 | + else |
| 132 | + void (item satisfies never); |
| 133 | + } |
| 134 | + |
| 135 | + return { |
| 136 | + contextText: LlamaText(contextContent), |
| 137 | + stopGenerationTriggers: [ |
| 138 | + LlamaText(new SpecialToken("EOS")), |
| 139 | + LlamaText(new SpecialToken("EOT")), |
| 140 | + LlamaText(new SpecialTokensText("<turn|>")), |
| 141 | + LlamaText(new SpecialTokensText("<turn|>\n")), |
| 142 | + LlamaText("<|return|>") |
| 143 | + ] |
| 144 | + }; |
| 145 | + } |
| 146 | + |
| 147 | + public override generateAvailableFunctionsSystemText(availableFunctions: ChatModelFunctions, {documentParams = true}: { |
| 148 | + documentParams?: boolean |
| 149 | + }): LlamaText { |
| 150 | + return LlamaText( |
| 151 | + Object.entries(availableFunctions) |
| 152 | + .map(([name, definition]) => { |
| 153 | + return LlamaText([ |
| 154 | + new SpecialTokensText("<|tool>"), |
| 155 | + "declaration:", name, "{", |
| 156 | + jsonDumps({ |
| 157 | + description: definition.description || undefined, |
| 158 | + parameters: documentParams |
| 159 | + ? (definition.params || {}) |
| 160 | + : undefined |
| 161 | + }), |
| 162 | + "}", new SpecialTokensText("<tool|>") |
| 163 | + ]); |
| 164 | + }) |
| 165 | + ); |
| 166 | + } |
| 167 | + |
| 168 | + public override generateModelResponseText(modelResponse: ChatModelResponse["response"], useRawValues: boolean = true): LlamaText { |
| 169 | + return this._getModelResponse(modelResponse, useRawValues, false, false); |
| 170 | + } |
| 171 | + |
| 172 | + /** @internal */ |
| 173 | + private _getModelResponse( |
| 174 | + modelResponse: ChatModelResponse["response"], |
| 175 | + useRawValues: boolean, |
| 176 | + isLastItem: boolean, |
| 177 | + keepOnlyLastThought: boolean |
| 178 | + ) { |
| 179 | + const res: LlamaText[] = [ |
| 180 | + LlamaText(new SpecialTokensText("<|turn>model\n")) |
| 181 | + ]; |
| 182 | + const pendingFunctionCalls: ChatModelFunctionCall[] = []; |
| 183 | + |
| 184 | + const addPendingFunctions = () => { |
| 185 | + if (pendingFunctionCalls.length === 0) |
| 186 | + return; |
| 187 | + |
| 188 | + res.push(this.generateFunctionCallsAndResults(pendingFunctionCalls, useRawValues)); |
| 189 | + |
| 190 | + pendingFunctionCalls.length = 0; |
| 191 | + }; |
| 192 | + |
| 193 | + for (let index = 0; index < modelResponse.length; index++) { |
| 194 | + const isLastResponse = index === modelResponse.length - 1; |
| 195 | + const response = modelResponse[index]; |
| 196 | + |
| 197 | + if (response == null) |
| 198 | + continue; |
| 199 | + else if (response === "" && (!isLastResponse || !isLastItem)) |
| 200 | + continue; |
| 201 | + |
| 202 | + if (typeof response === "string") { |
| 203 | + addPendingFunctions(); |
| 204 | + res.push(LlamaText(response)); |
| 205 | + } else if (response.type === "segment") { |
| 206 | + addPendingFunctions(); |
| 207 | + |
| 208 | + if (response.ended && response.raw != null && useRawValues) |
| 209 | + res.push(LlamaText.fromJSON(response.raw)); |
| 210 | + else if (response.segmentType === "thought") { |
| 211 | + if (keepOnlyLastThought && !isLastItem) |
| 212 | + continue; |
| 213 | + |
| 214 | + res.push( |
| 215 | + LlamaText([ |
| 216 | + new SpecialTokensText("<|channel>thought"), |
| 217 | + response.text, |
| 218 | + (isLastItem && !response.ended) |
| 219 | + ? LlamaText([]) |
| 220 | + : new SpecialTokensText("<channel|>") |
| 221 | + ]) |
| 222 | + ); |
| 223 | + } else if (response.segmentType === "comment") |
| 224 | + continue; // unsupported |
| 225 | + else |
| 226 | + void (response.segmentType satisfies never); |
| 227 | + } else if (response.type === "functionCall") { |
| 228 | + if (response.startsNewChunk) |
| 229 | + addPendingFunctions(); |
| 230 | + |
| 231 | + pendingFunctionCalls.push(response); |
| 232 | + } else |
| 233 | + void (response satisfies never); |
| 234 | + } |
| 235 | + |
| 236 | + addPendingFunctions(); |
| 237 | + |
| 238 | + return LlamaText(res); |
| 239 | + } |
| 240 | + |
| 241 | + /** @internal */ |
| 242 | + public static override _getOptionConfigurationsToTestIfCanSupersedeJinjaTemplate(): ChatWrapperJinjaMatchConfiguration<typeof this> { |
| 243 | + return [ |
| 244 | + [{}, {}], |
| 245 | + [{reasoning: false}, {}], |
| 246 | + [ |
| 247 | + {reasoning: true}, |
| 248 | + {}, |
| 249 | + {additionalRenderParameters: {"enable_thinking": true}} |
| 250 | + ] |
| 251 | + ]; |
| 252 | + } |
| 253 | +} |
0 commit comments