|
| 1 | +package dev.langchain4j.community.model.oracle.oci.genai; |
| 2 | + |
| 3 | +import static dev.langchain4j.community.model.oracle.oci.genai.TestEnvProps.NON_EMPTY; |
| 4 | +import static dev.langchain4j.community.model.oracle.oci.genai.TestEnvProps.OCI_GENAI_COHERE_CHAT_MODEL_NAME_PROPERTY; |
| 5 | +import static dev.langchain4j.community.model.oracle.oci.genai.TestEnvProps.OCI_GENAI_COMPARTMENT_ID_PROPERTY; |
| 6 | +import static dev.langchain4j.community.model.oracle.oci.genai.TestEnvProps.OCI_GENAI_MODEL_REGION_PROPERTY; |
| 7 | +import static org.hamcrest.MatcherAssert.assertThat; |
| 8 | +import static org.hamcrest.Matchers.contains; |
| 9 | +import static org.hamcrest.Matchers.containsString; |
| 10 | +import static org.junit.jupiter.api.Assertions.fail; |
| 11 | + |
| 12 | +import com.oracle.bmc.Region; |
| 13 | +import com.oracle.bmc.auth.AuthenticationDetailsProvider; |
| 14 | +import com.oracle.bmc.generativeaiinference.GenerativeAiInferenceClient; |
| 15 | +import com.oracle.bmc.generativeaiinference.model.EmbedTextDetails; |
| 16 | +import com.oracle.bmc.generativeaiinference.model.OnDemandServingMode; |
| 17 | +import com.oracle.bmc.generativeaiinference.requests.EmbedTextRequest; |
| 18 | +import com.oracle.bmc.generativeaiinference.responses.EmbedTextResponse; |
| 19 | +import dev.langchain4j.agent.tool.P; |
| 20 | +import dev.langchain4j.agent.tool.Tool; |
| 21 | +import dev.langchain4j.agent.tool.ToolExecutionRequest; |
| 22 | +import dev.langchain4j.service.AiServices; |
| 23 | +import dev.langchain4j.service.Result; |
| 24 | +import dev.langchain4j.service.SystemMessage; |
| 25 | +import dev.langchain4j.service.UserMessage; |
| 26 | +import dev.langchain4j.service.V; |
| 27 | +import dev.langchain4j.service.tool.ToolExecution; |
| 28 | +import java.util.ArrayList; |
| 29 | +import java.util.List; |
| 30 | +import java.util.concurrent.CompletableFuture; |
| 31 | +import java.util.concurrent.ExecutionException; |
| 32 | +import java.util.concurrent.TimeUnit; |
| 33 | +import java.util.concurrent.TimeoutException; |
| 34 | +import java.util.concurrent.atomic.AtomicInteger; |
| 35 | +import java.util.stream.IntStream; |
| 36 | +import org.junit.jupiter.api.Test; |
| 37 | +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; |
| 38 | +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariables; |
| 39 | +import org.slf4j.Logger; |
| 40 | +import org.slf4j.LoggerFactory; |
| 41 | + |
| 42 | +@EnabledIfEnvironmentVariables({ |
| 43 | + @EnabledIfEnvironmentVariable(named = OCI_GENAI_MODEL_REGION_PROPERTY, matches = NON_EMPTY), |
| 44 | + @EnabledIfEnvironmentVariable(named = OCI_GENAI_COMPARTMENT_ID_PROPERTY, matches = NON_EMPTY), |
| 45 | + @EnabledIfEnvironmentVariable(named = OCI_GENAI_COHERE_CHAT_MODEL_NAME_PROPERTY, matches = NON_EMPTY) |
| 46 | +}) |
| 47 | +public class CohereToolHistoryTest { |
| 48 | + |
| 49 | + static final Logger LOGGER = LoggerFactory.getLogger(CohereToolHistoryTest.class); |
| 50 | + static final AuthenticationDetailsProvider authProvider = TestEnvProps.createAuthProvider(); |
| 51 | + static final List<List<Float>> EMBEDDINGS = new ArrayList<>(); |
| 52 | + static final AtomicInteger EMBEDDINGS_SEQ = new AtomicInteger(0); |
| 53 | + |
| 54 | + @Test |
| 55 | + public void sequentialToolCalls() throws ExecutionException, InterruptedException, TimeoutException { |
| 56 | + try (var model = OciGenAiCohereChatModel.builder() |
| 57 | + .modelName(TestEnvProps.OCI_GENAI_COHERE_CHAT_MODEL_NAME) |
| 58 | + .compartmentId(TestEnvProps.OCI_GENAI_COMPARTMENT_ID) |
| 59 | + .region(Region.fromRegionCodeOrId(TestEnvProps.OCI_GENAI_MODEL_REGION)) |
| 60 | + .authProvider(authProvider) |
| 61 | + .temperature(0.3) |
| 62 | + .seed(TestEnvProps.SEED) |
| 63 | + .maxTokens(4000) |
| 64 | + .build()) { |
| 65 | + |
| 66 | + var tools = new TestTools(); |
| 67 | + |
| 68 | + var embeddingAiService = AiServices.builder(TestEmbeddingAiService.class) |
| 69 | + .tools(tools) |
| 70 | + .toolExecutionErrorHandler((throwable, context) -> fail(throwable)) |
| 71 | + .chatModel(model) |
| 72 | + .build(); |
| 73 | + |
| 74 | + var result = embeddingAiService.embed("It's bucketing down", "It's raining cats and dogs"); |
| 75 | + LOGGER.info("Result> {}", result.content()); |
| 76 | + |
| 77 | + assertThat( |
| 78 | + result.toolExecutions().stream() |
| 79 | + .map(ToolExecution::request) |
| 80 | + .map(ToolExecutionRequest::name) |
| 81 | + .toList(), |
| 82 | + contains("storeEmbedding", "storeEmbedding", "calculateCosineSimilarity")); |
| 83 | + |
| 84 | + assertThat(result.content(), containsString(String.valueOf(tools.similarity.get(10, TimeUnit.SECONDS)))); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + interface TestEmbeddingAiService { |
| 89 | + |
| 90 | + @SystemMessage( |
| 91 | + """ |
| 92 | + You must use provided tool to calculate cosine similarity between the two embedding ids. |
| 93 | + You must never calculate cosine similarity yourself, always use tool. |
| 94 | + """) |
| 95 | + @UserMessage( |
| 96 | + """ |
| 97 | + Store embeddings of following two strings "{{firstEmbedString}}", "{{secondEmbedString}}".. |
| 98 | + When you have two resulting embedding ids use them to calculate cosine similarity, use tool for that. |
| 99 | + """) |
| 100 | + Result<String> embed( |
| 101 | + @V("firstEmbedString") String firstEmbedString, @V("secondEmbedString") String secondEmbedString); |
| 102 | + } |
| 103 | + |
| 104 | + static class TestTools { |
| 105 | + |
| 106 | + CompletableFuture<Double> similarity = new CompletableFuture<>(); |
| 107 | + EmbeddingClient embeddingClient = new EmbeddingClient(); |
| 108 | + |
| 109 | + @Tool("Store embedding of an input in the embedding database. Return the result id of the stored embedding.") |
| 110 | + int storeEmbedding(@P("String input for embeddings") String input) { |
| 111 | + LOGGER.info("Storing embedding \"{}\"", input); |
| 112 | + var nextId = EMBEDDINGS_SEQ.getAndIncrement(); |
| 113 | + EMBEDDINGS.add(nextId, embeddingClient.getEmbeddings(List.of(input)).get(0)); |
| 114 | + return nextId; |
| 115 | + } |
| 116 | + |
| 117 | + @Tool("Calculate cosine similarity between the two embeddings identified by provided ids.") |
| 118 | + double calculateCosineSimilarity(@P("First embedding id") int id1, @P("Second embedding id") int id2) { |
| 119 | + LOGGER.info("Computing similarity id1={} id2={}", id1, id2); |
| 120 | + var similarity = getCosineSimilarity(EMBEDDINGS.get(id1), EMBEDDINGS.get(id2)); |
| 121 | + LOGGER.info("Computed similarity is {}", similarity); |
| 122 | + this.similarity.complete(similarity); |
| 123 | + return similarity; |
| 124 | + } |
| 125 | + |
| 126 | + public static double[] getL2Normed(List<Float> vector) { |
| 127 | + var norm = (float) Math.sqrt(vector.stream().mapToDouble(e -> e * e).sum()); |
| 128 | + return vector.stream().mapToDouble(e -> e / norm).toArray(); |
| 129 | + } |
| 130 | + |
| 131 | + public static double getCosineSimilarity(List<Float> vector1, List<Float> vector2) { |
| 132 | + if (vector1.size() != vector2.size()) throw new RuntimeException("Vectors are having different size"); |
| 133 | + |
| 134 | + var vector1Normed = getL2Normed(vector1); |
| 135 | + var vector2Normed = getL2Normed(vector2); |
| 136 | + |
| 137 | + return IntStream.range(0, vector1.size()) |
| 138 | + .mapToDouble(i -> vector1Normed[i] * vector2Normed[i]) |
| 139 | + .sum(); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + public static class EmbeddingClient { |
| 144 | + public EmbeddingClient() {} |
| 145 | + |
| 146 | + public List<List<Float>> getEmbeddings(List<String> input) { |
| 147 | + var clientBuilder = GenerativeAiInferenceClient.builder() |
| 148 | + .region(Region.fromRegionCodeOrId(TestEnvProps.OCI_GENAI_MODEL_REGION)); |
| 149 | + |
| 150 | + try (var embedClient = clientBuilder.build(authProvider)) { |
| 151 | + EmbedTextDetails embedTextDetails = EmbedTextDetails.builder() |
| 152 | + .inputs(input) |
| 153 | + .compartmentId(TestEnvProps.OCI_GENAI_COMPARTMENT_ID) |
| 154 | + .servingMode(OnDemandServingMode.builder() |
| 155 | + .modelId("cohere.embed-v4.0") |
| 156 | + .build()) |
| 157 | + .build(); |
| 158 | + |
| 159 | + EmbedTextRequest request = EmbedTextRequest.builder() |
| 160 | + .embedTextDetails(embedTextDetails) |
| 161 | + .build(); |
| 162 | + EmbedTextResponse response = embedClient.embedText(request); |
| 163 | + return response.getEmbedTextResult().getEmbeddings(); |
| 164 | + } catch (Exception ex) { |
| 165 | + throw new RuntimeException(ex); |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | +} |
0 commit comments