Skip to content

Commit

Permalink
Using MutableMap
Browse files Browse the repository at this point in the history
  • Loading branch information
javipacheco committed Jun 11, 2024
1 parent 2e2be8c commit a919acb
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ 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 cache: Atomic<MutableMap<Input, CachedToolInfo<Output>>>,
private val timeCachePolicy: Duration = 1.days
) : Tool<Input, Output> {

Expand All @@ -17,17 +17,17 @@ abstract class CachedTool<Input, Output>(
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 }
val cachedToolInfo = cache.get().get(input)
if (cachedToolInfo != null) {
val lastTimeInCache = timeInMillis() - timeCachePolicy.inWholeMilliseconds
if (lastTimeInCache > cachedToolInfo.timestamp) {
cache.get().remove(cachedToolInfo)
cache.get().remove(input)
} else {
return cachedToolInfo.response
}
}
val response = block()
cache.get().add(CachedToolInfo(input, response, timeInMillis()))
cache.get().put(input, CachedToolInfo(response, timeInMillis()))
return response
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
package com.xebia.functional.xef.llm.assistants

data class CachedToolInfo<Request, Response>(
val request: Request,
val response: Response,
val timestamp: Long
)
data class CachedToolInfo<Response>(val response: Response, val timestamp: Long)

0 comments on commit a919acb

Please sign in to comment.