-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
2 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
core/src/commonMain/kotlin/com/xebia/functional/xef/llm/assistants/CachedTool.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package com.xebia.functional.xef.llm.assistants | ||
|
||
import arrow.fx.coroutines.Atomic | ||
import arrow.fx.coroutines.timeInMillis | ||
import kotlin.time.Duration | ||
import kotlin.time.Duration.Companion.days | ||
|
||
abstract class CachedTool<Input, Output>( | ||
private val cache: Atomic<MutableMap<Input, CachedToolInfo<Output>>>, | ||
private val timeCachePolicy: Duration = 1.days | ||
) : Tool<Input, Output> { | ||
|
||
override suspend fun invoke(input: Input): Output { | ||
return cache(input) { onCacheMissed(input) } | ||
} | ||
|
||
abstract suspend fun onCacheMissed(input: Input): Output | ||
|
||
private suspend fun cache(input: Input, block: suspend () -> Output): Output { | ||
val cachedToolInfo = cache.get().get(input) | ||
if (cachedToolInfo != null) { | ||
val lastTimeInCache = timeInMillis() - timeCachePolicy.inWholeMilliseconds | ||
if (lastTimeInCache > cachedToolInfo.timestamp) { | ||
cache.get().remove(input) | ||
} else { | ||
return cachedToolInfo.response | ||
} | ||
} | ||
val response = block() | ||
cache.get().put(input, CachedToolInfo(response, timeInMillis())) | ||
return response | ||
} | ||
} |
3 changes: 3 additions & 0 deletions
3
core/src/commonMain/kotlin/com/xebia/functional/xef/llm/assistants/CachedToolInfo.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
package com.xebia.functional.xef.llm.assistants | ||
|
||
data class CachedToolInfo<Response>(val response: Response, val timestamp: Long) |