Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cached Tool #757

Merged
merged 2 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>>>,
javipacheco marked this conversation as resolved.
Show resolved Hide resolved
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
)
Loading