From 81e2df9e512a5b635833e0b8987cd0f45186dfd2 Mon Sep 17 00:00:00 2001 From: Kazik Pogoda Date: Wed, 2 Oct 2024 11:57:08 +0200 Subject: [PATCH] add: Fibonacci tool example use case, documentation updated --- README.md | 39 +++++++++++++------------- src/commonTest/kotlin/AnthropicTest.kt | 37 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 041a8b8..64c3937 100644 --- a/README.md +++ b/README.md @@ -93,29 +93,28 @@ fun main() { It can also use tools: ```kotlin -fun main() { - - // our tool - @Serializable - data class Calculator( - val operation: Operation, - val a: Double, - val b: Double +@Serializable +data class Calculator( + val operation: Operation, + val a: Double, + val b: Double +) { + + @Suppress("unused") // will be used by Anthropic :) + enum class Operation( + val calculate: (a: Double, b: Double) -> Double ) { + ADD({ a, b -> a + b }), + SUBTRACT({ a, b -> a - b }), + MULTIPLY({ a, b -> a * b }), + DIVIDE({ a, b -> a / b }) + } - enum class Operation( - val calculate: (a: Double, b: Double) -> Double - ) { - ADD({ a, b -> a + b }), - SUBTRACT({ a, b -> a - b }), - MULTIPLY({ a, b -> a * b }), - DIVIDE({ a, b -> a / b }) - } - - fun calculate() = operation.calculate(a, b) + fun calculate() = operation.calculate(a, b) - } +} +fun main() { val client = Anthropic() val calculatorTool = Tool( @@ -134,7 +133,7 @@ fun main() { val toolUse = response.content[0] as ToolUse val calculator = toolUse.input() - val result = calculator.calculate() + val result = calculator.calculate() // we are doing the job for LLM here println(result) } ``` diff --git a/src/commonTest/kotlin/AnthropicTest.kt b/src/commonTest/kotlin/AnthropicTest.kt index 061e1c0..605b231 100644 --- a/src/commonTest/kotlin/AnthropicTest.kt +++ b/src/commonTest/kotlin/AnthropicTest.kt @@ -152,4 +152,41 @@ class AnthropicTest { } } + @Serializable + data class Fibonacci(val n: Int) + + tailrec fun fibonacci( + n: Int, a: Int = 0, b: Int = 1 + ): Int = when (n) { + 0 -> a; 1 -> b; else -> fibonacci(n - 1, b, a + b) + } + + @Test + fun shouldUseCalculatorToolForFibonacci() = runTest { + // given + val client = Anthropic() + val fibonacciTool = Tool( + description = "Calculates fibonacci number of a given n", + ) + + // when + val response = client.messages.create { + +Message { +"What's fibonacci number 42" } + tools = listOf(fibonacciTool) + toolChoice = ToolChoice.Any() + } + + // then + response.apply { + assertTrue(content.size == 1) + assertTrue(content[0] is ToolUse) + val toolUse = content[0] as ToolUse + assertTrue(toolUse.name == "com_xemantic_anthropic_AnthropicTest_Fibonacci") + val n = toolUse.input().n + assertTrue(n == 42) + val fibonacciNumber = fibonacci(n) // doing the job for Anthropic + assertTrue(fibonacciNumber == 267914296) + } + } + }