-
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.
- Loading branch information
1 parent
5621c97
commit 2e2be8c
Showing
2 changed files
with
40 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<MutableList<CachedToolInfo<Input, 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().find { it.request == input } | ||
if (cachedToolInfo != null) { | ||
val lastTimeInCache = timeInMillis() - timeCachePolicy.inWholeMilliseconds | ||
if (lastTimeInCache > cachedToolInfo.timestamp) { | ||
cache.get().remove(cachedToolInfo) | ||
} else { | ||
return cachedToolInfo.response | ||
} | ||
} | ||
val response = block() | ||
cache.get().add(CachedToolInfo(input, response, timeInMillis())) | ||
return response | ||
} | ||
} |
7 changes: 7 additions & 0 deletions
7
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,7 @@ | ||
package com.xebia.functional.xef.llm.assistants | ||
|
||
data class CachedToolInfo<Request, Response>( | ||
val request: Request, | ||
val response: Response, | ||
val timestamp: Long | ||
) |