Skip to content

Commit

Permalink
Cached Tool
Browse files Browse the repository at this point in the history
  • Loading branch information
javipacheco committed Jun 11, 2024
1 parent 5621c97 commit 2e2be8c
Show file tree
Hide file tree
Showing 2 changed files with 40 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<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
}
}
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
)

0 comments on commit 2e2be8c

Please sign in to comment.