Skip to content

Commit

Permalink
Cached Tool (#757)
Browse files Browse the repository at this point in the history
* Cached Tool

* Using MutableMap
  • Loading branch information
javipacheco authored Jun 11, 2024
1 parent 5621c97 commit ede4497
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
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
}
}
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)

0 comments on commit ede4497

Please sign in to comment.