createModel method

Model createModel(
  1. String modelName,
  2. SchemanticType customOptions
)

Implementation

Model createModel(String modelName, SchemanticType customOptions) {
  return Model(
    name: '$name/$modelName',
    customOptions: customOptions,
    metadata: {'model': modelInfoFor(modelName).toJson()},
    fn: (req, ctx) async {
      if (usesInteractions(modelName)) {
        return generateWithInteractions(this, modelName, req, ctx);
      }

      gcl.GenerationConfig generationConfig;
      List<gcl.SafetySetting>? safetySettings;
      List<gcl.Tool>? tools;
      gcl.ToolConfig? toolConfig;
      GeminiRetrievalConfig? retrievalConfig;
      String? serviceTier;
      bool? storeFromConfig;
      String? previousInteractionId;

      final isJsonMode =
          req.output?.format == 'json' ||
          req.output?.contentType == 'application/json';

      if (customOptions == GeminiTtsOptions.$schema) {
        final options = req.config == null
            ? GeminiTtsOptions()
            : GeminiTtsOptions.$schema.parse(req.config!);
        serviceTier = options.serviceTier;
        storeFromConfig = options.store;
        previousInteractionId = options.previousInteractionId;
        generationConfig = toGeminiTtsSettings(
          options,
          req.output?.schema,
          isJsonMode,
          constrained: req.output?.constrained ?? false,
        );
        safetySettings = toGeminiSafetySettings(options.safetySettings);
        tools = toGeminiTools(
          req.tools,
          codeExecution: options.codeExecution,
          configTools: options.tools,
          googleSearch: options.googleSearch,
          urlContext: options.urlContext,
        );
        toolConfig = toGeminiToolConfig(
          options.functionCallingConfig,
          toolChoice: req.toolChoice,
          hasFunctionTools: req.tools?.isNotEmpty ?? false,
        );
        retrievalConfig = options.retrievalConfig;
      } else {
        final options = req.config == null
            ? GeminiOptions()
            : GeminiOptions.$schema.parse(req.config!);
        serviceTier = options.serviceTier;
        storeFromConfig = options.store;
        previousInteractionId = options.previousInteractionId;
        generationConfig = toGeminiSettings(
          options,
          req.output?.schema,
          isJsonMode,
          constrained: req.output?.constrained ?? false,
        );
        safetySettings = toGeminiSafetySettings(options.safetySettings);
        tools = toGeminiTools(
          req.tools,
          codeExecution: options.codeExecution,
          configTools: options.tools,
          googleSearch: options.googleSearch,
          urlContext: options.urlContext,
        );
        toolConfig = toGeminiToolConfig(
          options.functionCallingConfig,
          toolChoice: req.toolChoice,
          hasFunctionTools: req.tools?.isNotEmpty ?? false,
        );
        retrievalConfig = options.retrievalConfig;
      }

      if (retrievalConfig != null) {
        toolConfig ??= gcl.ToolConfig();
        toolConfig.toJson()['retrievalConfig'] = retrievalConfig.toJson();
      }

      warnDroppedVertexOptions(this, modelName, req.config);

      // Family fields (see model.dart), read from the config whatever the
      // model's family, as in JS.
      final config = req.config ?? const <String, dynamic>{};

      // vertexAI-only fields (the vertexAI fields are the same on every
      // Gemini option type).
      final vertexOptions = GeminiOptions.$schema.parse(config);
      final labels = supportsVertexOptions
          ? toGeminiLabels(vertexOptions.labels)
          : null;
      final vertexRetrieval = vertexOptions.vertexRetrieval;
      if (supportsVertexOptions && vertexRetrieval != null) {
        // After the other tools, as in JS.
        tools = [
          ...tools,
          gcl.Tool.fromJson({
            'retrieval': {
              'vertexAiSearch': {
                'datastore': vertexSearchDatastore(vertexRetrieval.datastore),
              },
              'disableAttribution': ?vertexRetrieval.disableAttribution,
            },
          }),
        ];
      }
      final imageConfig = GeminiImageOptions.$schema
          .parse(config)
          .imageConfig;
      if (imageConfig != null) {
        generationConfig.toJson()['imageConfig'] = imageConfig.toJson();
      }
      // TTS models on vertexAI: audioFormat is the generateContent
      // `responseFormat`, and audio is asked for by default (as in JS).
      final isTts = GeminiModelFamily.of(modelName) == .tts;
      final audioFormat = GeminiTtsOptions.$schema.parse(config).audioFormat;
      if (generateContentTtsFormats) {
        final responseFormat = toGeminiAudioResponseFormat(audioFormat);
        if (responseFormat != null) {
          generationConfig.toJson()['responseFormat'] = responseFormat;
        }
        if (isTts && generationConfig.responseModalities == null) {
          generationConfig.responseModalities = ['AUDIO'];
        }
      } else if (audioFormat != null) {
        // generateContent rejects unknown generationConfig fields with a
        // 400 (googleAI's generateContent TTS models have no such field).
        warnDroppedConfigField(modelName, 'audioFormat');
      }
      // No equivalent on generateContent for these Interactions-only
      // fields. JS forwards videoConfig; it's dropped here too, for the
      // same reason.
      final videoOptions = GeminiVideoOptions.$schema.parse(config);
      if (videoOptions.videoFormat != null) {
        warnDroppedConfigField(modelName, 'videoFormat');
      }
      if (videoOptions.videoConfig != null) {
        warnDroppedConfigField(modelName, 'videoConfig');
      }

      // There's no stored conversation to continue on generateContent.
      if (previousInteractionId?.isNotEmpty ?? false) {
        logger.warning(
          'previousInteractionId is not supported for this model and will '
          'be ignored.',
        );
      }
      // On generateContent, `store` only controls whether the server logs
      // this request for the API key's project (viewable in AI Studio's
      // Logs and Datasets); there's nothing to continue. Sent only when
      // set; otherwise the project's logging setting applies. Where the
      // API has no `store` (the Gemini Enterprise Agent Platform), nothing
      // is stored for later anyway, so only a request's own `store: true`
      // asks for something that can't happen. A plugin-wide `store: true`
      // is meant for the Interactions models and isn't warned about here
      // (JS warns for it too; JS TODO).
      final generateContentStore = storeFromConfig ?? store;
      if (storeFromConfig == true && !supportsGenerateContentStore) {
        warnDroppedConfigField(modelName, 'store');
      }
      if (serviceTier != null && !supportsServiceTier) {
        warnDroppedConfigField(modelName, 'serviceTier');
      }

      final service = await getApiClientForRequest(req.config);

      // Aborts the in-flight request on a plugin-owned client; an injected
      // client's close() is a no-op, so cancellation there only lands at
      // the next throwIfCancelled checkpoint.
      final disposeCancel = ctx.cancel?.onCancel(service.client.close);

      try {
        ctx.cancel?.throwIfCancelled();

        final systemMessage = req.messages
            .where((m) => m.role == Role.system)
            .firstOrNull;
        final messages = req.messages
            .where((m) => m.role != Role.system)
            .toList();

        final generateRequest = gcl.GenerateContentRequest(
          contents: toGeminiContent(messages),
          tools: tools.isEmpty ? null : tools,
          toolConfig: toolConfig,
          generationConfig: generationConfig,
          safetySettings: safetySettings?.isEmpty ?? true
              ? null
              : safetySettings,
          systemInstruction: systemMessage == null
              ? null
              : gcl.Content(
                  parts: systemMessage.content.map(toGeminiPart).toList(),
                  role: 'system',
                ),
        );
        if (serviceTier != null && supportsServiceTier) {
          // The generated request type has no serviceTier field. toJson()
          // returns its live backing map (extension type), so this adds
          // the key to the request body.
          generateRequest.toJson()['serviceTier'] = serviceTier;
        }
        if (generateContentStore != null && supportsGenerateContentStore) {
          generateRequest.toJson()['store'] = generateContentStore;
        }
        if (labels != null) {
          generateRequest.toJson()['labels'] = labels;
        }

        if (ctx.streamingRequested) {
          final stream = service.streamGenerateContent(
            generateRequest,
            model: 'models/$modelName',
          );
          final chunks = <gcl.GenerateContentResponse>[];
          await for (final chunk in stream) {
            ctx.cancel?.throwIfCancelled();

            chunks.add(chunk);
            if (chunk.candidates?.isNotEmpty == true) {
              final (message, finishReason) = fromGeminiCandidate(
                chunk.candidates!.first,
              );
              ctx.sendChunk(
                ModelResponseChunk(index: 0, content: message.content),
              );
            }
          }
          ctx.cancel?.throwIfCancelled();
          final aggregated = aggregateResponses(chunks);
          if (aggregated.candidates?.isEmpty ?? true) {
            final blockReason = aggregated.promptFeedback?.blockReason;
            throw Exception(
              'No candidates returned from generative stream. Block reason: $blockReason',
            );
          }
          final candidate = aggregated.candidates!.first;
          var (message, finishReason) = fromGeminiCandidate(candidate);
          if (isTts && generateContentTtsFormats) {
            // Streamed audio arrives as many headerless chunks (audio/l16
            // by default); join them into one part, like a non-streamed
            // response (JS vertexAI).
            message = Message(
              role: message.role,
              content: mergeStreamedAudio(message.content),
              metadata: message.metadata,
            );
          }
          return ModelResponse(
            finishReason: finishReason,
            finishMessage: candidate.finishMessage,
            message: message,
            raw: aggregated.toJson(),
            usage: extractUsage(aggregated.usageMetadata),
          );
        } else {
          final response = await service.generateContent(
            generateRequest,
            model: 'models/$modelName',
          );
          ctx.cancel?.throwIfCancelled();
          if (response.candidates?.isEmpty ?? true) {
            final blockReason = response.promptFeedback?.blockReason;
            throw Exception(
              'No candidates returned from generateContent. Block reason: $blockReason',
            );
          }
          final candidate = response.candidates!.first;
          final (message, finishReason) = fromGeminiCandidate(candidate);
          return ModelResponse(
            finishReason: finishReason,
            finishMessage: candidate.finishMessage,
            message: message,
            raw: response?.toJson(),
            usage: extractUsage(response.usageMetadata),
          );
        }
      } catch (e, stack) {
        throw handleException(e, stack);
      } finally {
        disposeCancel?.call();
        service.client.close();
      }
    },
  );
}