fun sendMessageStream()

in generativeai/src/main/java/com/google/ai/client/generativeai/Chat.kt [99:143]


  fun sendMessageStream(prompt: Content): Flow<GenerateContentResponse> {
    prompt.assertComesFromUser()
    attemptLock()

    val flow = model.generateContentStream(*history.toTypedArray(), prompt)
    val bitmaps = LinkedList<Bitmap>()
    val blobs = LinkedList<BlobPart>()
    val text = StringBuilder()

    /**
     * TODO: revisit when images and blobs are returned. This will cause issues with how things are
     *   structured in the response. eg; a text/image/text response will be (incorrectly)
     *   represented as image/text
     */
    return flow
      .onEach {
        for (part in it.candidates.first().content.parts) {
          when (part) {
            is TextPart -> text.append(part.text)
            is ImagePart -> bitmaps.add(part.image)
            is BlobPart -> blobs.add(part)
          }
        }
      }
      .onCompletion {
        lock.release()
        if (it == null) {
          val content =
            content("model") {
              for (bitmap in bitmaps) {
                image(bitmap)
              }
              for (blob in blobs) {
                blob(blob.mimeType, blob.blob)
              }
              if (text.isNotBlank()) {
                text(text.toString())
              }
            }

          history.add(prompt)
          history.add(content)
        }
      }
  }