|
| 1 | +package ai.koog.agents.utils |
| 2 | + |
| 3 | +import io.github.oshai.kotlinlogging.KLogger |
| 4 | +import io.ktor.client.HttpClientConfig |
| 5 | +import io.ktor.client.call.body |
| 6 | +import io.ktor.client.engine.HttpClientEngineConfig |
| 7 | +import io.ktor.client.plugins.sse.SSEClientException |
| 8 | +import io.ktor.client.plugins.sse.sse |
| 9 | +import io.ktor.client.request.accept |
| 10 | +import io.ktor.client.request.headers |
| 11 | +import io.ktor.client.request.post |
| 12 | +import io.ktor.client.request.setBody |
| 13 | +import io.ktor.client.statement.bodyAsText |
| 14 | +import io.ktor.client.statement.readRawBytes |
| 15 | +import io.ktor.http.ContentType |
| 16 | +import io.ktor.http.HttpHeaders |
| 17 | +import io.ktor.http.HttpMethod |
| 18 | +import io.ktor.http.isSuccess |
| 19 | +import io.ktor.util.reflect.TypeInfo |
| 20 | +import kotlinx.coroutines.Dispatchers |
| 21 | +import kotlinx.coroutines.flow.Flow |
| 22 | +import kotlinx.coroutines.flow.flow |
| 23 | +import kotlinx.coroutines.withContext |
| 24 | +import org.jetbrains.annotations.ApiStatus.Experimental |
| 25 | +import kotlin.jvm.JvmOverloads |
| 26 | +import kotlin.reflect.KClass |
| 27 | + |
| 28 | +/** |
| 29 | + * KtorHttpClient is an implementation of the KoogHttpClient interface, utilizing Ktor's HttpClient |
| 30 | + * to perform HTTP operations, including POST requests and Server-Sent Events (SSE) streaming. |
| 31 | + * |
| 32 | + * This client provides enhanced logging, flexible request and response handling, and supports |
| 33 | + * configurability for underlying Ktor HttpClient instances. |
| 34 | + * |
| 35 | + * @property clientName The name of the client, used for logging and traceability. |
| 36 | + * @property logger A logging instance of type KLogger for recording client-related events and errors. |
| 37 | + * @constructor Creates a KtorHttpClient instance with an optional base Ktor HttpClient and configuration block. |
| 38 | + * |
| 39 | + * @param baseClient The base Ktor HttpClient instance to be used. Default is a newly created instance. |
| 40 | + * @param configurer A lambda function to configure the base Ktor HttpClient instance. |
| 41 | + * The configuration is applied using the Ktor `HttpClient.config` method. |
| 42 | + */ |
| 43 | +@Experimental |
| 44 | +internal class KoogKtorHttpClient internal constructor( |
| 45 | + private val clientName: String, |
| 46 | + private val logger: KLogger, |
| 47 | + baseClient: io.ktor.client.HttpClient = io.ktor.client.HttpClient(), |
| 48 | + configurer: HttpClientConfig<out HttpClientEngineConfig>.() -> Unit |
| 49 | +) : KoogHttpClient { |
| 50 | + |
| 51 | + /** |
| 52 | + * A configured instance of the Ktor HTTP client used for making HTTP requests. |
| 53 | + * |
| 54 | + * This property is initialized with a base client configuration, extended using a custom |
| 55 | + * `configurer` function to adapt to specific requirements or settings. |
| 56 | + * |
| 57 | + * It is designed to interact with various endpoints to perform HTTP operations such as |
| 58 | + * POST requests and Server-Sent Events (SSE) streaming, supporting request and response |
| 59 | + * serialization and deserialization for different data types. |
| 60 | + */ |
| 61 | + val ktorClient: io.ktor.client.HttpClient = baseClient.config(configurer) |
| 62 | + |
| 63 | + override suspend fun <T : Any, R : Any> post( |
| 64 | + path: String, |
| 65 | + request: T, |
| 66 | + requestBodyType: KClass<T>, |
| 67 | + responseType: KClass<R> |
| 68 | + ): R = withContext(Dispatchers.SuitableForIO) { |
| 69 | + val response = ktorClient.post(path) { |
| 70 | + if (requestBodyType == String::class) { |
| 71 | + @Suppress("UNCHECKED_CAST") |
| 72 | + setBody(request as String) |
| 73 | + } else { |
| 74 | + setBody(request, TypeInfo(requestBodyType)) |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + if (response.status.isSuccess()) { |
| 79 | + if (responseType == String::class) { |
| 80 | + @Suppress("UNCHECKED_CAST") |
| 81 | + response.bodyAsText() as R |
| 82 | + } else { |
| 83 | + response.body(TypeInfo(responseType)) |
| 84 | + } |
| 85 | + } else { |
| 86 | + val errorBody = response.bodyAsText() |
| 87 | + logger.error { "Error from $clientName API: ${response.status}: $errorBody" } |
| 88 | + error("Error from $clientName API: ${response.status}: $errorBody") |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + override fun <T : Any, R : Any> sse( |
| 93 | + path: String, |
| 94 | + request: T, |
| 95 | + requestBodyType: KClass<T>, |
| 96 | + dataFilter: (String?) -> Boolean, |
| 97 | + decodeStreamingResponse: (String) -> R, |
| 98 | + processStreamingChunk: (R) -> String? |
| 99 | + ): Flow<String> = flow { |
| 100 | + @Suppress("TooGenericExceptionCaught") |
| 101 | + try { |
| 102 | + ktorClient.sse( |
| 103 | + urlString = path, |
| 104 | + request = { |
| 105 | + method = HttpMethod.Post |
| 106 | + accept(ContentType.Text.EventStream) |
| 107 | + headers { |
| 108 | + append(HttpHeaders.CacheControl, "no-cache") |
| 109 | + append(HttpHeaders.Connection, "keep-alive") |
| 110 | + } |
| 111 | + if (requestBodyType == String::class) { |
| 112 | + @Suppress("UNCHECKED_CAST") |
| 113 | + setBody(request as String) |
| 114 | + } else { |
| 115 | + setBody(request, TypeInfo(requestBodyType)) |
| 116 | + } |
| 117 | + } |
| 118 | + ) { |
| 119 | + incoming.collect { event -> |
| 120 | + event |
| 121 | + .takeIf { dataFilter.invoke(it.data) } |
| 122 | + ?.data?.trim() |
| 123 | + ?.let(decodeStreamingResponse) |
| 124 | + ?.let(processStreamingChunk) |
| 125 | + ?.let { emit(it) } |
| 126 | + } |
| 127 | + } |
| 128 | + } catch (e: SSEClientException) { |
| 129 | + e.response?.let { response -> |
| 130 | + val body = response.readRawBytes().decodeToString() |
| 131 | + logger.error(e) { "Error from $clientName API: ${response.status}: ${e.message}.\nBody:\n$body" } |
| 132 | + error("Error from $clientName API: ${response.status}: ${e.message}") |
| 133 | + } |
| 134 | + } catch (e: Exception) { |
| 135 | + logger.error { "Exception during streaming from $clientName: $e" } |
| 136 | + error(e.message ?: "Unknown error during streaming from $clientName: $e") |
| 137 | + } |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +/** |
| 142 | + * Creates a new instance of `KoogHttpClient` using a Ktor-based HTTP client for performing HTTP operations. |
| 143 | + * |
| 144 | + * This function allows configuring the underlying Ktor `HttpClient` through the provided configuration lambda |
| 145 | + * and enables enhanced logging, flexibility, and customization in HTTP interactions. |
| 146 | + * |
| 147 | + * @param clientName The name of the client instance, used for identifying or logging client operations. |
| 148 | + * @param logger A `KLogger` instance used for logging client events and errors. |
| 149 | + * @param baseClient The base Ktor `HttpClient` instance to be used. Defaults to a new Ktor `HttpClient` instance. |
| 150 | + * @param configurer A lambda function to configure the base Ktor `HttpClient` instance. It is applied using |
| 151 | + * Ktor’s `HttpClientConfig`. |
| 152 | + * @return An instance of `KoogHttpClient` configured with the provided parameters. |
| 153 | + */ |
| 154 | +@Experimental |
| 155 | +@JvmOverloads |
| 156 | +public fun KoogHttpClient.Companion.fromKtorClient( |
| 157 | + clientName: String, |
| 158 | + logger: KLogger, |
| 159 | + baseClient: io.ktor.client.HttpClient = io.ktor.client.HttpClient(), |
| 160 | + configurer: HttpClientConfig<out HttpClientEngineConfig>.() -> Unit |
| 161 | +): KoogHttpClient = KoogKtorHttpClient(clientName, logger, baseClient, configurer) |
0 commit comments