index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/driftkit/driftkit-clients-spring-ai-starter/0.8.1/ai/driftkit/clients/springai
java-sources/ai/driftkit/driftkit-clients-spring-ai-starter/0.8.1/ai/driftkit/clients/springai/autoconfigure/DriftKitClientsSpringAIProperties.java
package ai.driftkit.clients.springai.autoconfigure; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Configuration properties for DriftKit Clients Spring AI integration. */ @Data @ConfigurationProperties(prefix = "driftkit.clients.spring-ai") public class DriftKitClientsSpringAIProperties { /** * Enable Spring AI model client bean creation */ private boolean enabled = true; /** * Default model name to use if not specified in requests */ private String defaultModel; /** * Default temperature for model requests */ private Double defaultTemperature; /** * Default max tokens for model requests */ private Integer defaultMaxTokens; /** * Default top-p value for model requests */ private Double defaultTopP; /** * Enable request/response logging */ private boolean loggingEnabled = false; /** * Model-specific configuration */ private ModelProperties model = new ModelProperties(); @Data public static class ModelProperties { /** * Bean name of the Spring AI ChatModel to use */ private String beanName; /** * Whether to register as primary ModelClient */ private boolean primary = false; } }
0
java-sources/ai/driftkit/driftkit-clients-spring-boot-starter/0.8.1/ai/driftkit/clients
java-sources/ai/driftkit/driftkit-clients-spring-boot-starter/0.8.1/ai/driftkit/clients/autoconfigure/ModelClientAutoConfiguration.java
package ai.driftkit.clients.autoconfigure; import ai.driftkit.clients.core.ModelClientFactory; import ai.driftkit.common.domain.client.ModelClient; import ai.driftkit.config.EtlConfig; import ai.driftkit.config.EtlConfig.VaultConfig; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import java.util.List; /** * Auto-configuration for model client services. * * This configuration automatically creates ModelClient beans * from the EtlConfig.vault configurations when available. */ @Slf4j @AutoConfiguration @ConditionalOnBean(EtlConfig.class) @ConditionalOnProperty(name = "driftkit.vault[0].name") public class ModelClientAutoConfiguration { @Bean("primaryModelClient") @ConditionalOnMissingBean(name = "primaryModelClient") public ModelClient primaryModelClient(EtlConfig config) { try { List<VaultConfig> vaultConfigs = config.getVault(); if (vaultConfigs == null || vaultConfigs.isEmpty()) { log.warn("No vault configurations found in EtlConfig"); return null; } // Use the first vault config as primary VaultConfig primaryConfig = vaultConfigs.get(0); log.info("Initializing primary model client: {}", primaryConfig.getName()); ModelClient modelClient = ModelClientFactory.fromConfig(primaryConfig); log.info("Successfully initialized primary model client: {}", primaryConfig.getName()); return modelClient; } catch (Exception e) { log.error("Failed to initialize primary model client from configuration", e); throw new RuntimeException("Failed to initialize primary model client", e); } } @Bean @ConditionalOnMissingBean(ModelClient.class) public ModelClient modelClient(EtlConfig config) { // Fallback to primary model client return primaryModelClient(config); } }
0
java-sources/ai/driftkit/driftkit-clients-spring-boot-starter/0.8.1/ai/driftkit/clients/spring
java-sources/ai/driftkit/driftkit-clients-spring-boot-starter/0.8.1/ai/driftkit/clients/spring/streaming/SpringStreamingAdapter.java
package ai.driftkit.clients.spring.streaming; import ai.driftkit.common.domain.streaming.StreamingResponse; import ai.driftkit.common.domain.streaming.StreamingCallback; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; /** * Spring adapter for converting between DriftKit's framework-agnostic * StreamingResponse and Spring WebFlux's Flux. */ public class SpringStreamingAdapter { /** * Convert a StreamingResponse to a Flux. * * @param streamingResponse The framework-agnostic streaming response * @param <T> Type of items in the stream * @return A Flux that emits the same items */ public static <T> Flux<T> toFlux(StreamingResponse<T> streamingResponse) { return Flux.create(sink -> { streamingResponse.subscribe(new StreamingCallback<T>() { @Override public void onNext(T item) { if (!sink.isCancelled()) { sink.next(item); } } @Override public void onError(Throwable error) { if (!sink.isCancelled()) { sink.error(error); } } @Override public void onComplete() { if (!sink.isCancelled()) { sink.complete(); } } }); // Handle cancellation sink.onDispose(() -> streamingResponse.cancel()); }, FluxSink.OverflowStrategy.BUFFER); } /** * Convert a Flux to a StreamingResponse. * * @param flux The Spring WebFlux Flux * @param <T> Type of items in the stream * @return A framework-agnostic streaming response */ public static <T> StreamingResponse<T> fromFlux(Flux<T> flux) { return new StreamingResponse<T>() { private volatile boolean active = false; private volatile boolean cancelled = false; private reactor.core.Disposable disposable; @Override public void subscribe(StreamingCallback<T> callback) { if (active) { callback.onError(new IllegalStateException("Stream already subscribed")); return; } active = true; disposable = flux.subscribe( item -> { if (!cancelled) { callback.onNext(item); } }, error -> { active = false; if (!cancelled) { callback.onError(error); } }, () -> { active = false; if (!cancelled) { callback.onComplete(); } } ); } @Override public void cancel() { cancelled = true; active = false; if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); } } @Override public boolean isActive() { return active; } }; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/annotation/JsonSchemaStrict.java
package ai.driftkit.common.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to indicate that a JSON schema should use strict mode. * In strict mode, all properties are required and additionalProperties is false. */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface JsonSchemaStrict { /** * Whether to enable strict mode for this schema. * @return true if strict mode should be enabled */ boolean value() default true; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/AITask.java
package ai.driftkit.common.domain; import ai.driftkit.common.domain.client.ResponseFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; import java.util.List; import java.util.Map; @Data @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) public class AITask { // @Id @NotNull private String messageId; @NotNull private String chatId; @NotNull private String message; private String systemMessage; private String gradeComment; @NotNull private Grade grade = Grade.FAIR; @NotNull private long createdTime; @NotNull private long responseTime; private String workflow; private String contextJson; private String workflowStopEvent; private Language language = Language.GENERAL; private boolean jsonRequest; private boolean jsonResponse; private ResponseFormat responseFormat; private String modelId; private List<String> promptIds; private Map<String, Object> variables; private Boolean logprobs; private Integer topLogprobs; private String purpose; private List<String> imageBase64; private String imageMimeType; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/Chat.java
package ai.driftkit.common.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class Chat { @NotNull private String chatId; @NotNull private String name; private String systemMessage; @NotNull private Language language = Language.ENGLISH; @NotNull private int memoryLength; private ModelRole modelRole = ModelRole.ABTEST; @NotNull private long createdTime; @NotNull private boolean hidden; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/ChatItem.java
package ai.driftkit.common.domain; public interface ChatItem { String getMessage(); String getMessageId(); long getCreatedTime(); Grade getGrade(); String getGradeComment(); MessageType getMessageType(); ChatMessageType type(); String text(); }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/ChatMessageType.java
package ai.driftkit.common.domain; public enum ChatMessageType { SYSTEM, USER, AI, TOOL_EXECUTION_RESULT }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/ChatRequest.java
package ai.driftkit.common.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ChatRequest { private String id; @NotNull private String name; private String systemMessage; @NotNull private Language language; @NotNull private int memoryLength; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/CreatePromptRequest.java
package ai.driftkit.common.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * Unified CreatePromptRequest used across all DriftKit modules. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder @JsonIgnoreProperties(ignoreUnknown = true) public class CreatePromptRequest { private String method; private String message; private String systemMessage; private String workflow; @Builder.Default private boolean jsonResponse = false; @Builder.Default private Language language = Language.GENERAL; @Builder.Default private Boolean forceRepoVersion = false; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/DictionaryGroup.java
package ai.driftkit.common.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * Unified DictionaryGroup domain object used across all DriftKit modules. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class DictionaryGroup { private String id; private String name; private Language language; private Long createdAt; private Long updatedAt; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/DictionaryItem.java
package ai.driftkit.common.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; /** * Unified DictionaryItem domain object used across all DriftKit modules. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class DictionaryItem { private String id; private int index; private String groupId; private String name; private Language language; private List<String> markers; private List<String> samples; private Long createdAt; private Long updatedAt; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/Grade.java
package ai.driftkit.common.domain; public enum Grade { EXCELLENT, GOOD, FAIR, POOR, UNACCEPTABLE }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/ImageMessageTask.java
package ai.driftkit.common.domain; import ai.driftkit.common.domain.client.ResponseFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.*; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Data @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) @EqualsAndHashCode(callSuper = true) public class ImageMessageTask extends AITask { List<GeneratedImage> images; @Builder public ImageMessageTask( String messageId, String chatId, String message, String systemMessage, String gradeComment, Grade grade, long createdTime, long responseTime, String modelId, List<String> promptIds, boolean jsonRequest, boolean jsonResponse, ResponseFormat responseFormat, Map<String, Object> variables ) { super(messageId, chatId, message, systemMessage, gradeComment, grade, createdTime, responseTime, null, null, null, Language.GENERAL, jsonRequest, jsonResponse, responseFormat, modelId, promptIds, variables, null, null, null, null, null); } @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) public static class GeneratedImage { String url; byte[] data; String mimeType; String revisedPrompt; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/LLMRequest.java
package ai.driftkit.common.domain; import ai.driftkit.common.domain.client.ResponseFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; import java.util.List; import java.util.Map; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class LLMRequest { private String chatId; @NotNull private String message; private List<String> promptIds; private String systemMessage; private String workflow; private boolean jsonResponse; private ResponseFormat responseFormat; private Language language; private Map<String, Object> variables; private Boolean logprobs; private Integer topLogprobs; private String purpose; private String model; private List<String> imagesBase64; private String imageMimeType; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/Language.java
package ai.driftkit.common.domain; /** * Enumeration of supported language codes. * Unified language enum used across all DriftKit modules. */ public enum Language { GENERAL("general"), ENGLISH("en"), SPANISH("es"), FRENCH("fr"), GERMAN("de"), ITALIAN("it"), PORTUGUESE("pt"), DUTCH("nl"), RUSSIAN("ru"), CHINESE("zh"), JAPANESE("ja"), KOREAN("ko"), ARABIC("ar"), HINDI("hi"), TURKISH("tr"), POLISH("pl"), SWEDISH("sv"), NORWEGIAN("no"), DANISH("da"), FINNISH("fi"), CZECH("cs"), HUNGARIAN("hu"), ROMANIAN("ro"), BULGARIAN("bg"), CROATIAN("hr"), SLOVAK("sk"), SLOVENIAN("sl"), ESTONIAN("et"), LATVIAN("lv"), LITHUANIAN("lt"), UKRAINIAN("uk"), VIETNAMESE("vi"), THAI("th"), INDONESIAN("id"), MALAY("ms"), TAMIL("ta"), BENGALI("bn"), GUJARATI("gu"), MARATHI("mr"), TELUGU("te"), KANNADA("kn"), MALAYALAM("ml"), PUNJABI("pa"), URDU("ur"), HEBREW("he"), PERSIAN("fa"), GREEK("el"), CATALAN("ca"), BASQUE("eu"), GALICIAN("gl"), WELSH("cy"), IRISH("ga"), SCOTTISH_GAELIC("gd"), ICELANDIC("is"), MALTESE("mt"), AFRIKAANS("af"), SWAHILI("sw"), YORUBA("yo"), HAUSA("ha"), IGBO("ig"), AMHARIC("am"), SOMALI("so"), MULTI("multi"); private final String value; Language(String value) { this.value = value; } public String getValue() { return value; } public static Language fromValue(String value) { if (value == null) { return GENERAL; // Default } for (Language language : values()) { if (language.value.equals(value)) { return language; } } throw new IllegalArgumentException("Unknown language code: " + value); } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/MessageTask.java
package ai.driftkit.common.domain; import ai.driftkit.common.domain.client.LogProbs; import ai.driftkit.common.domain.client.ModelTextResponse; import ai.driftkit.common.domain.client.ResponseFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.List; import java.util.Map; @Data @NoArgsConstructor @JsonInclude(Include.NON_NULL) @EqualsAndHashCode(callSuper = true) @JsonIgnoreProperties(ignoreUnknown = true) public class MessageTask extends AITask { protected String result; protected String imageTaskId; protected Double temperature; protected LogProbs logProbs; @Builder public MessageTask( String messageId, String chatId, String message, String systemMessage, String gradeComment, Grade grade, long createdTime, long responseTime, String modelId, String result, String imageTaskId, List<String> promptIds, Double temperature, String workflow, String context, Language language, Map<String, Object> variables, boolean jsonRequest, boolean jsonResponse, ResponseFormat responseFormat, String workflowStopEvent, Boolean logprobs, Integer topLogprobs, LogProbs logProbs, String purpose, List<String> imageBase64, String imageMimeType ) { super(messageId, chatId, message, systemMessage, gradeComment, grade, createdTime, responseTime, workflow, context, workflowStopEvent, language, jsonRequest, jsonResponse, responseFormat, modelId, promptIds, variables, logprobs, topLogprobs, purpose, imageBase64, imageMimeType); this.result = result; this.imageTaskId = imageTaskId; this.temperature = temperature; this.logProbs = logProbs; } /** * Extract and save token logprobs from a model response if available. * * @param response The model response potentially containing logprobs */ public void updateWithResponseLogprobs(ModelTextResponse response) { if (Boolean.TRUE.equals(this.getLogprobs()) && response != null && !response.getChoices().isEmpty() && response.getChoices().get(0).getLogprobs() != null) { if (logProbs == null) { this.logProbs = new LogProbs(new ArrayList<>()); } this.logProbs.getContent().addAll(response.getChoices().get(0).getLogprobs().getContent()); } } /** * Extract logprobs parameters from a potential MessageTask object. * * @param taskObj an object that might be a MessageTask * @return LogProbsParams object containing logprobs parameters */ public static LogProbsParams extractLogProbsParams(Object taskObj) { LogProbsParams params = new LogProbsParams(); if (taskObj instanceof MessageTask task) { params.setLogprobs(task.getLogprobs()); params.setTopLogprobs(task.getTopLogprobs()); } return params; } /** * Contains parameters for token logprobs functionality */ @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor public static class LogProbsParams { private Boolean logprobs; private Integer topLogprobs; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/MessageType.java
package ai.driftkit.common.domain; public enum MessageType { TEXT, IMAGE, AUDIO, VIDEO, FILE }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/ModelRole.java
package ai.driftkit.common.domain; public enum ModelRole { MAIN, ABTEST, CHECKER, NONE }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/ModelTrace.java
package ai.driftkit.common.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * Common trace information for model client operations */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ModelTrace { // Request execution time private long executionTimeMs; // Error information private boolean hasError; private String errorMessage; // Token counts private int promptTokens; private int completionTokens; // Model information private String model; private Double temperature; private String responseFormat; }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/Prompt.java
package ai.driftkit.common.domain; import ai.driftkit.common.domain.client.ResponseFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Map; /** * Unified Prompt domain object used across all DriftKit modules. */ @Data @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class Prompt { private String id; private String method; private String message; private String systemMessage; private State state; private String modelId; private ResolveStrategy resolveStrategy = ResolveStrategy.LAST_VERSION; private String workflow; private Language language = Language.GENERAL; private Double temperature; private boolean jsonRequest; private boolean jsonResponse; private ResponseFormat responseFormat; private long createdTime; private long updatedTime; private long approvedTime; public Language getLanguage() { if (language == null) { return Language.GENERAL; } return language; } /** * Apply variables to the message template. * Note: Full template engine functionality requires context-engineering module. */ public String applyVariables(Map<String, Object> variables) { if (variables == null || variables.isEmpty()) { return getMessage(); } String result = getMessage(); for (Map.Entry<String, Object> entry : variables.entrySet()) { String placeholder = "{{" + entry.getKey() + "}}"; String value = entry.getValue() != null ? entry.getValue().toString() : ""; result = result.replace(placeholder, value); } return result; } public enum ResolveStrategy { LAST_VERSION, CURRENT, } public enum State { MODERATION, MANUAL_TESTING, AUTO_TESTING, CURRENT, REPLACED } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/PromptRequest.java
package ai.driftkit.common.domain; import ai.driftkit.common.domain.client.ResponseFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class PromptRequest { private String chatId; private List<PromptIdRequest> promptIds; private Map<String, Object> variables; private String workflow; private String modelId; private String checkerPrompt; private Language language; private boolean savePrompt; private Boolean logprobs; private Integer topLogprobs; private String purpose; private List<String> imageBase64; private String imageMimeType; private Boolean jsonResponse; private ResponseFormat responseFormat; public PromptRequest(List<String> promptIds, String chatId, Map<String, Object> variables, Language language) { this(promptIds, null, "reasoning-lite", null, chatId, variables, language, null, true, null); } public PromptRequest(PromptIdRequest idRequest, String chatId, Map<String, Object> variables, Language language) { this(null, List.of(idRequest), "reasoning-lite", null, chatId, variables, language, null, true, null); } public PromptRequest(List<String> promptIds, String chatId, Map<String, Object> variables, Language language, String purpose) { this(promptIds, null, "reasoning-lite", null, chatId, variables, language, purpose, true, null); } public PromptRequest(PromptIdRequest idRequest, String chatId, Map<String, Object> variables, Language language, String purpose) { this(null, List.of(idRequest), "reasoning-lite", null, chatId, variables, language, purpose, true, null); } @Builder public PromptRequest(List<String> promptIds, List<PromptIdRequest> idRequests, String workflow, String modelId, String chatId, Map<String, Object> variables, Language language, String purpose, Boolean jsonResponse, ResponseFormat responseFormat) { this.workflow = workflow; this.modelId = modelId; this.chatId = chatId; this.jsonResponse = jsonResponse; this.responseFormat = responseFormat; this.promptIds = idRequests == null ? promptIds.stream() .map(promptId -> new PromptIdRequest(promptId, null, null)) .collect(Collectors.toList()) : idRequests; this.variables = variables; this.language = language; this.purpose = purpose; } @Data @NoArgsConstructor @AllArgsConstructor public static class PromptIdRequest { private String promptId; private String prompt; private Double temperature; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/RestResponse.java
package ai.driftkit.common.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; @Data @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) public class RestResponse<T> { @NotNull private boolean success; private T data; private String message; private String error; public RestResponse(boolean success) { this.success = success; } public RestResponse(boolean success, T data) { this.success = success; this.data = data; } public RestResponse(boolean success, T data, String message) { this.success = success; this.data = data; this.message = message; } public RestResponse(boolean success, T data, String message, String error) { this.success = success; this.data = data; this.message = message; this.error = error; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/chat/ChatMessage.java
package ai.driftkit.common.domain.chat; import ai.driftkit.common.domain.Language; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Base chat message class. * Ported from workflow-engine-core to be shared across modules. */ @Data @NoArgsConstructor @AllArgsConstructor @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true ) @JsonSubTypes({ @JsonSubTypes.Type(value = ChatRequest.class, name = "USER"), @JsonSubTypes.Type(value = ChatResponse.class, name = "AI"), }) @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_DEFAULT) @Slf4j public class ChatMessage implements Serializable { /** * Standard property key for message text content. */ public static final String PROPERTY_MESSAGE = "message"; protected String id; protected String chatId; protected MessageType type; protected Language language; protected Long timestamp; protected List<DataProperty> properties = new ArrayList<>(); protected String userId; public ChatMessage(String id, String chatId, MessageType type) { this.id = id; this.chatId = chatId; this.type = type; this.timestamp = System.currentTimeMillis(); } public ChatMessage(String id, String chatId, MessageType type, String userId) { this(id, chatId, type); this.userId = userId; } @JsonIgnore public Map<String, String> getPropertiesMap() { Map<String, String> propsMap = new HashMap<>(); for (DataProperty prop : properties) { if (prop.getValue() == null) { continue; } propsMap.put(prop.getName(), prop.getValue()); } return propsMap; } @JsonIgnore public void setPropertiesMap(Map<String, String> map) { if (map == null) { return; } for (Map.Entry<String, String> entry : map.entrySet()) { updateOrAddProperty(entry.getKey(), entry.getValue()); } } public void updateOrAddProperty(String name, String value) { if (name == null) { return; } for (DataProperty prop : properties) { if (name.equals(prop.getName())) { prop.setValue(value); return; } } DataProperty newProp = new DataProperty(); newProp.setName(name); newProp.setValue(value); newProp.setType(PropertyType.STRING); properties.add(newProp); } public enum PropertyType { STRING, INTEGER, DOUBLE, BOOLEAN, LITERAL, ENUM, OBJECT, ARRAY_OBJECT, ARRAY, MAP } /** * Message type enumeration. */ public enum MessageType { USER, AI, CONTEXT, SYSTEM } /** * Data property for flexible message content. */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_DEFAULT) public static class DataProperty implements Serializable { private String name; private String nameId; private String dataNameId; private String value; private String data; private Boolean multiSelect; private PropertyType type; private boolean valueAsNameId; public DataProperty(String name, String value, String nameId, PropertyType type) { this(name, value, type); this.nameId = nameId; } public DataProperty(String name, String value, PropertyType type) { this.name = name; this.value = value; this.type = type; } public boolean isValueAsNameId() { return valueAsNameId; } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/chat/ChatRequest.java
package ai.driftkit.common.domain.chat; import ai.driftkit.common.domain.Language; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.JsonNode; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.function.Consumer; /** * Chat request message from user. * Ported from workflow-engine-core to be shared across modules. */ @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @Slf4j public class ChatRequest extends ChatMessage { private String requestSchemaName; private String workflowId; private Boolean composable; public ChatRequest(String chatId, Map<String, String> properties, Language language, String workflowId) { this(chatId, properties, language, workflowId, null); } public ChatRequest(String chatId, Map<String, String> properties, Language language, String workflowId, String requestSchemaName) { super(UUID.randomUUID().toString(), chatId, MessageType.USER); this.language = language; this.workflowId = workflowId; this.requestSchemaName = requestSchemaName; if (properties != null) { setPropertiesMap(properties); } } @JsonIgnore public String getMessage() { Map<String, String> propsMap = getPropertiesMap(); return propsMap.get(ChatMessage.PROPERTY_MESSAGE); } @JsonIgnore public void setMessage(String message) { Map<String, String> propsMap = getPropertiesMap(); propsMap.put(ChatMessage.PROPERTY_MESSAGE, message); setPropertiesMap(propsMap); } private static final Map<String, Consumer<PropertyContext>> PROPERTY_HANDLERS = Map.of( "name", ctx -> ctx.prop.setName(ctx.node.asText()), "value", ctx -> ctx.prop.setValue(ctx.node.asText()), "nameId", ctx -> ctx.prop.setNameId(ctx.node.asText()), "dataNameId", ctx -> ctx.prop.setDataNameId(ctx.node.asText()), "data", ctx -> ctx.prop.setData(ctx.node.asText()), "multiSelect", ctx -> ctx.prop.setMultiSelect(ctx.node.asBoolean()), "type", ctx -> ctx.prop.setType(PropertyType.valueOf(ctx.node.asText())), "valueAsNameId", ctx -> ctx.prop.setValueAsNameId(ctx.node.asBoolean()) ); private record PropertyContext(DataProperty prop, JsonNode node) {} @JsonSetter("properties") public void setPropertiesFromJson(JsonNode node) { if (node == null) { return; } if (node.isArray()) { // Handle array format (default) this.properties = new ArrayList<>(); for (JsonNode propNode : node) { DataProperty prop = new DataProperty(); PROPERTY_HANDLERS.forEach((fieldName, handler) -> { if (propNode.has(fieldName)) { handler.accept(new PropertyContext(prop, propNode.get(fieldName))); } }); this.properties.add(prop); } } else if (node.isObject()) { // Handle object format (backward compatibility) this.properties = new ArrayList<>(); Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); DataProperty prop = new DataProperty(); prop.setName(field.getKey()); prop.setValue(field.getValue().asText()); prop.setType(PropertyType.STRING); this.properties.add(prop); } } } public void resolveDataNameIdReferences(List<ChatMessage> previousMessages) { if (properties == null || properties.isEmpty() || previousMessages == null || previousMessages.isEmpty()) { return; } for (DataProperty property : properties) { if (property.getDataNameId() == null) { continue; } String dataNameId = property.getDataNameId(); for (ChatMessage message : previousMessages) { if (id.equals(message.getId())) { continue; } for (DataProperty historicalProp : message.getProperties()) { if (historicalProp.getNameId() == null || historicalProp.getValue() == null) { continue; } if (!dataNameId.equals(historicalProp.getNameId())) { continue; } property.setData(historicalProp.getValue()); log.debug("Resolved dataNameId '{}' to value '{}' from message {}", dataNameId, historicalProp.getValue(), message.getId()); break; } } } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/chat/ChatResponse.java
package ai.driftkit.common.domain.chat; import ai.driftkit.common.domain.Language; import ai.driftkit.common.domain.chat.ChatMessage.PropertyType; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.*; /** * Chat response message from AI. * Ported from workflow-engine-core to be shared across modules. */ @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class ChatResponse extends ChatMessage { private String workflowId; private NextSchema nextSchema; private boolean completed = true; private Integer percentComplete; private boolean required = true; public ChatResponse(String responseId, String chatId, String workflowId, Language language, boolean completed, Integer percentComplete, String userId, Map<String, String> props) { this(responseId, chatId, workflowId, language, completed, percentComplete, true, userId, props); } public ChatResponse(String responseId, String chatId, String workflowId, Language language, boolean completed, Integer percentComplete, boolean required, String userId, Map<String, String> props) { super(responseId, chatId, MessageType.AI, userId); this.workflowId = workflowId; this.language = language; this.completed = completed; this.percentComplete = percentComplete != null ? percentComplete : 100; this.required = required; if (props != null) { setPropertiesMap(props); } } public ChatResponse(String responseId, String chatId, String workflowId, Language language, String userId, Map<String, String> props) { this(responseId, chatId, workflowId, language, true, 100, userId, props); } @Data @NoArgsConstructor @AllArgsConstructor public static class NextSchema implements Serializable { String schemaName; List<NextProperties> properties; } @Data @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_DEFAULT) public static class NextProperties implements Serializable { private String name; private String nameId; private PropertyType type; private List<String> values; private boolean isMultiSelect; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/client/LogProbs.java
package ai.driftkit.common.domain.client; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) public class LogProbs { private List<TokenLogProb> content; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) public static class TokenLogProb { private String token; private double logprob; private byte[] bytes; private List<TopLogProb> topLogprobs; } @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(Include.NON_NULL) public static class TopLogProb { private String token; private double logprob; private byte[] bytes; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/client/ModelClient.java
package ai.driftkit.common.domain.client; import ai.driftkit.common.domain.client.ModelTextResponse.ResponseMessage; import ai.driftkit.common.domain.streaming.StreamingResponse; import ai.driftkit.common.domain.streaming.BasicStreamingResponse; import ai.driftkit.common.utils.ModelUtils; import ai.driftkit.config.EtlConfig.VaultConfig; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.commons.collections4.CollectionUtils; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @Data @NoArgsConstructor @AllArgsConstructor public abstract class ModelClient<T> { private T workflow; private String model; private List<String> systemMessages; /* What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or top_p but not both. */ private Double temperature = 0.2; /* An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. */ private Double topP; //Up to 4 sequences where the API will stop generating further tokens. private List<String> stop; protected boolean jsonObjectSupport = true; // Whether to enable log probabilities for token generation private Boolean logprobs = false; // Number of most likely tokens to return at each step (1-20) private Integer topLogprobs = 2; private Integer maxTokens; private Integer maxCompletionTokens; /* Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. */ private Double presencePenalty; /* Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. */ private Double frequencyPenalty; /* Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. */ private Map<String, Integer> logitBias; /* This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result. Determinism is not guaranteed, and you should refer to the system_fingerprint response parameter to monitor changes in the backend. */ private Integer seed; /* A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. */ private List<Tool> tools; public ModelClient( String model, List<String> systemMessages, Double temperature, Double topP, List<String> stop, Integer maxTokens, Integer maxCompletionTokens, Double presencePenalty, Double frequencyPenalty, Map<String, Integer> logitBias, Integer seed, List<Method> functions, List<Tool> tools, boolean jsonObjectSupport, Boolean logprobs, Integer topLogprobs, T workflow ) { this.model = model; this.systemMessages = systemMessages; this.temperature = temperature; this.topP = topP; this.stop = stop; this.maxTokens = maxTokens; this.maxCompletionTokens = maxCompletionTokens; this.presencePenalty = presencePenalty; this.frequencyPenalty = frequencyPenalty; this.logitBias = logitBias; this.seed = seed; this.workflow = workflow; this.jsonObjectSupport = jsonObjectSupport; this.logprobs = logprobs; this.topLogprobs = topLogprobs; this.tools = tools == null ? new ArrayList<>() : tools; if (CollectionUtils.isNotEmpty(functions)) { this.tools.addAll( functions.stream() .map(ModelUtils::parseFunction) .toList() ); } } public abstract Set<Capability> getCapabilities(); public ModelTextResponse textToText(ModelTextRequest prompt) throws UnsupportedCapabilityException { checkCapability(Capability.TEXT_TO_TEXT); return null; } public ModelImageResponse textToImage(ModelImageRequest prompt) throws UnsupportedCapabilityException { checkCapability(Capability.TEXT_TO_IMAGE); return null; } public ModelTextResponse imageToText(ModelTextRequest image) throws UnsupportedCapabilityException { checkCapability(Capability.IMAGE_TO_TEXT); return null; } /** * Stream text-to-text response token by token. * Default implementation converts synchronous response to streaming. * * @param prompt The text request * @return Streaming response that emits tokens */ public StreamingResponse<String> streamTextToText(ModelTextRequest prompt) throws UnsupportedCapabilityException { checkCapability(Capability.TEXT_TO_TEXT); ModelTextResponse response = textToText(prompt); if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) { ResponseMessage message = response.getChoices().get(0); if (message != null && message.getMessage() != null && message.getMessage().getContent() != null) { // Default implementation: return the whole response at once return new BasicStreamingResponse<>(Collections.singletonList(message.getMessage().getContent())); } } return new BasicStreamingResponse<>(Collections.emptyList()); } private void checkCapability(Capability capability) throws UnsupportedCapabilityException { if (!getCapabilities().contains(capability)) { throw new UnsupportedCapabilityException("Capability [%s] is not supported".formatted(capability)); } } public static class UnsupportedCapabilityException extends RuntimeException { public UnsupportedCapabilityException(String message) { super(message); } } @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class Tool { @JsonProperty("type") private ResponseFormatType type; @JsonProperty("function") private ToolFunction function; } @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class ToolFunction { @JsonProperty("name") private String name; @JsonProperty("description") private String description; @JsonProperty("parameters") private FunctionParameters parameters; @Data @NoArgsConstructor @AllArgsConstructor public static class FunctionParameters { @JsonProperty("type") private ResponseFormatType type; @JsonProperty("properties") private Map<String, Property> properties; @JsonProperty("required") private List<String> required; } } @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class Property { @JsonProperty("type") private ResponseFormatType type; @JsonProperty("description") private String description; @JsonProperty("enum") private List<String> enumValues; @JsonProperty("properties") private Map<String, Property> properties; @JsonProperty("required") private List<String> required; @JsonProperty("items") private Property items; public Property(ResponseFormatType type) { this.type = type; } } public enum ResponseFormatType { String("string"), Number("number"), Boolean("boolean"), Integer("integer"), Object("object"), Array("array"), Enum("enum"), anyOf("anyOf"), function("function"); private String type; ResponseFormatType(String type) { this.type = type; } @JsonValue public String getType() { return type; } @JsonCreator public static ResponseFormatType fromType(String type) { for (ResponseFormatType formatType : ResponseFormatType.values()) { if (formatType.type.equals(type)) { return formatType; } } throw new IllegalArgumentException("Unknown type: " + type); } } public interface ModelClientInit { ModelClient init(VaultConfig config); } public enum Capability { TEXT_TO_TEXT, TEXT_TO_IMAGE, IMAGE_TO_TEXT, FUNCTION_CALLING, JSON_SCHEMA, JSON_OBJECT, TOOLS; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/client/ModelImageRequest.java
package ai.driftkit.common.domain.client; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class ModelImageRequest { // Model to use, e.g., "dall-e-3" private String model; private String prompt; // Number of images to generate, default is 1 private Integer n = 1; // Size of the image, e.g., "1024x1024" private String size = "1024x1024"; // Quality as string to support different models with different quality enums private String quality; public enum Quality { standard, hd, low, high, medium; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/client/ModelImageResponse.java
package ai.driftkit.common.domain.client; import ai.driftkit.common.domain.ModelTrace; import ai.driftkit.common.domain.client.ModelImageResponse.ModelContentMessage.ModelContentElement.ImageData; import ai.driftkit.common.domain.client.ModelTextRequest.MessageType; import ai.driftkit.common.tools.ToolCall; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Collections; import java.util.List; import java.util.stream.Stream; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ModelImageResponse { private Long createdTime; private String model; private String revisedPrompt; private List<ImageData> bytes; private ModelTrace trace; @Data @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public static class ModelContentMessage { private List<ModelContentElement> content; private Role role; private String name; @Builder public ModelContentMessage(Role role, String name, List<ModelContentElement> content) { this.role = role; this.name = name; this.content = content; } public static ModelContentMessage create(Role role, String str) { return create(role, List.of(str), Collections.emptyList()); } public static ModelContentMessage create(Role role, String str, ImageData image) { return create(role, List.of(str), List.of(image)); } public static ModelContentMessage create(Role role, List<String> str, List<ImageData> images) { return ModelContentMessage.builder() .role(role) .content(Stream.concat( str.stream().map(ModelContentElement::create), images.stream().map(e -> ModelContentElement.create(e.getImage(), e.getMimeType())) ).toList()) .build(); } @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) // Exclude null fields for cleaner serialization public static class ModelContentElement { private MessageType type; private ImageData image; private String text; public static ModelContentElement create(byte[] image, String mimeType) { return new ModelContentElement( MessageType.image, new ImageData(image, mimeType), null ); } public static ModelContentElement create(String str) { return new ModelContentElement( MessageType.text, null, str ); } @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) // Exclude null fields for cleaner serialization public static class ImageData { private byte[] image; private String mimeType; } } } @Data @Builder public static class ModelMessage { private Role role; private String content; private List<ToolCall> toolCalls; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/client/ModelTextRequest.java
package ai.driftkit.common.domain.client; import ai.driftkit.common.domain.client.ModelImageResponse.ModelContentMessage; import ai.driftkit.common.domain.client.ModelImageResponse.ModelContentMessage.ModelContentElement.ImageData; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Collections; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) // Exclude null fields for cleaner serialization public class ModelTextRequest { private List<ModelContentMessage> messages; private Double temperature; private String model; private ReasoningEffort reasoningEffort = ReasoningEffort.medium; // Whether to enable log probabilities for token generation private Boolean logprobs; // Number of most likely tokens to return at each step (1-20) private Integer topLogprobs; /* Setting to { "type": "json_schema", "json_schema": {...} } enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the Structured Outputs guide. Setting to { "type": "json_object" } enables JSON mode, which ensures the message the model generates is valid JSON. Important: when using JSON mode, you must also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if finish_reason="length", which indicates the generation exceeded max_tokens or the conversation exceeded the max context length. */ private ResponseFormat responseFormat; /* Controls which (if any) tool is called by the model. none means the model will not call any tool and instead generates a message. auto means the model can pick between generating a message or calling one or more tools. */ private ToolMode toolMode; /* A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. */ private List<ModelClient.Tool> tools; private PredictionContentItem prediction; public static ModelTextRequestBuilder create(Role role, String model, String str) { return create(role, model, List.of(str), Collections.emptyList()); } public static ModelTextRequestBuilder create(Role role, String model, String str, ImageData image) { return create(role, model, List.of(str), List.of(image)); } public static ModelTextRequestBuilder create(Role role, String model, List<String> str, List<ImageData> images) { return ModelTextRequest.builder() .messages(List.of(ModelContentMessage.create(role, str, images))) .model(model); } public enum ToolMode { none, auto, } @Data @NoArgsConstructor @AllArgsConstructor public static class PredictionContentItem { private String text; } public enum ReasoningEffort { medium, high, low, none, dynamic } public enum MessageType { image, image_url, text } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/client/ModelTextResponse.java
package ai.driftkit.common.domain.client; import ai.driftkit.common.domain.ModelTrace; import ai.driftkit.common.domain.client.ModelImageResponse.ModelMessage; import ai.driftkit.common.utils.JsonUtils; import ai.driftkit.common.utils.ModelUtils; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ModelTextResponse { private String id; //openai.object private String method; private Long createdTime; private String model; private List<ResponseMessage> choices; private Usage usage; private ModelTrace trace; public JsonNode getResponseJson() throws JsonProcessingException { String resp = getResponseJsonString(); if (resp == null) { return null; } return ModelUtils.parseJsonMessage(resp); } public <T> T getResponseJson(Class<T> cls) throws JsonProcessingException { String resp = getResponseJsonString(); if (resp == null) { return null; } return JsonUtils.fromJson(resp, cls); } public String getResponseJsonString() { String resp = getResponse(); if (StringUtils.isBlank(resp)) { return null; } if (!JsonUtils.isValidJSON(resp)) { resp = JsonUtils.fixIncompleteJSON(resp); } return resp; } public String getResponse() { if (CollectionUtils.isEmpty(choices)) { return null; } if (choices.size() > 1) { throw new RuntimeException("Unexpected response messages number [%s]".formatted(choices.size())); } return choices.getFirst().getMessage().getContent(); } @Data @Builder public static class ResponseMessage { private Integer index; private ModelMessage message; private String finishReason; private LogProbs logprobs; } @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class Usage { @JsonProperty("prompt_tokens") private Integer promptTokens; @JsonProperty("completion_tokens") private Integer completionTokens; @JsonProperty("total_tokens") private Integer totalTokens; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/client/ResponseFormat.java
package ai.driftkit.common.domain.client; import ai.driftkit.common.utils.JsonSchemaGenerator; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Map; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ResponseFormat { private ResponseType type; private JsonSchema jsonSchema; public enum ResponseType { IMAGE("image"), TEXT("text"), JSON_OBJECT("json_object"), JSON_SCHEMA("json_schema"); private final String value; ResponseType(String value) { this.value = value; } public String getValue() { return value; } @JsonValue public String toString() { return value; } @JsonCreator public static ResponseType fromValue(String value) { for (ResponseType type : values()) { if (type.value.equals(value)) { return type; } } throw new IllegalArgumentException("Unknown ResponseType: " + value); } } public static <T> ResponseFormat jsonObject(T obj) { if (obj == null) { return new ResponseFormat(ResponseType.JSON_OBJECT, null); } Class<?> clazz; if (obj instanceof Class<?>) { clazz = (Class<?>) obj; } else { clazz = obj.getClass(); } return new ResponseFormat(ResponseType.JSON_SCHEMA, JsonSchemaGenerator.generateSchema(clazz)); } public static <T> ResponseFormat jsonSchema(Class<T> clazz) { return new ResponseFormat(ResponseType.JSON_SCHEMA, JsonSchemaGenerator.generateSchema(clazz)); } public static ResponseFormat jsonObject() { return new ResponseFormat(ResponseType.JSON_OBJECT, null); } public static ResponseFormat text() { return new ResponseFormat(ResponseType.TEXT, null); } public static ResponseFormat image() { return new ResponseFormat(ResponseType.IMAGE, null); } @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class JsonSchema { @JsonProperty("title") private String title; @JsonProperty("type") private String type; @JsonProperty("properties") private Map<String, SchemaProperty> properties; @JsonProperty("required") private List<String> required; @JsonProperty("additionalProperties") private Boolean additionalProperties; @JsonProperty("strict") private Boolean strict; } @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class SchemaProperty { @JsonProperty("type") private String type; @JsonProperty("description") private String description; @JsonProperty("enum") private List<String> enumValues; @JsonProperty("properties") private Map<String, SchemaProperty> properties; @JsonProperty("required") private List<String> required; @JsonProperty("items") private SchemaProperty items; @JsonProperty("additionalProperties") private Object additionalProperties; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/client/Role.java
package ai.driftkit.common.domain.client; public enum Role { user, assistant, system }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/streaming/BasicStreamingResponse.java
package ai.driftkit.common.domain.streaming; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; /** * Basic implementation of StreamingResponse for synchronous data. * Useful for converting non-streaming responses to streaming format. * * @param <T> Type of items in the stream */ public class BasicStreamingResponse<T> implements StreamingResponse<T> { private final List<T> items; private final AtomicBoolean active = new AtomicBoolean(false); private final AtomicBoolean cancelled = new AtomicBoolean(false); private final ExecutorService executor = Executors.newSingleThreadExecutor(); public BasicStreamingResponse(List<T> items) { this.items = items; } @Override public void subscribe(StreamingCallback<T> callback) { if (active.compareAndSet(false, true)) { CompletableFuture.runAsync(() -> { try { for (T item : items) { if (cancelled.get()) { break; } callback.onNext(item); } if (!cancelled.get()) { callback.onComplete(); } } catch (Exception e) { callback.onError(e); } finally { active.set(false); } }, executor); } else { callback.onError(new IllegalStateException("Stream already subscribed")); } } @Override public void cancel() { cancelled.set(true); active.set(false); executor.shutdown(); } @Override public boolean isActive() { return active.get(); } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/streaming/StreamingCallback.java
package ai.driftkit.common.domain.streaming; /** * Callback interface for handling streaming events. * * @param <T> Type of items in the stream */ public interface StreamingCallback<T> { /** * Called when a new item is available in the stream. * * @param item The next item in the stream */ void onNext(T item); /** * Called when an error occurs in the stream. * * @param error The error that occurred */ void onError(Throwable error); /** * Called when the stream completes normally. */ void onComplete(); }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/domain/streaming/StreamingResponse.java
package ai.driftkit.common.domain.streaming; /** * Framework-agnostic interface for streaming responses. * Implementations can be created for different frameworks (Spring WebFlux, RxJava, etc.) * * @param <T> Type of items in the stream */ public interface StreamingResponse<T> { /** * Subscribe to the stream with a callback. * * @param callback Callback to receive stream events */ void subscribe(StreamingCallback<T> callback); /** * Cancel the streaming response. */ void cancel(); /** * Check if the stream is active. * * @return true if streaming is active, false otherwise */ boolean isActive(); }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/service/ChatStore.java
package ai.driftkit.common.service; import ai.driftkit.common.domain.chat.ChatMessage; import ai.driftkit.common.domain.chat.ChatMessage.MessageType; import java.util.List; import java.util.Map; /** * Unified chat storage interface that combines: * - Message persistence * - Token-based memory management * - Simple storage operations * * Replaces ChatMemory, ChatMemoryStore, ChatHistoryRepository and adapters. */ public interface ChatStore { /** * Add a simple text message to the chat. */ void add(String chatId, String content, MessageType type); /** * Add a message with properties to the chat. */ void add(String chatId, Map<String, String> properties, MessageType type); /** * Add a ChatMessage object to the chat. */ void add(ChatMessage message); /** * Update an existing message. */ void update(ChatMessage message); /** * Get recent messages within token limit. * Returns a sliding window of the most recent messages that fit within the token limit. * Does not delete any messages, only limits what is returned. */ List<ChatMessage> getRecentWithinTokens(String chatId, int maxTokens); /** * Get recent messages with default token limit (4096). * Returns a sliding window of the most recent messages. * Does not delete any messages, only limits what is returned. */ List<ChatMessage> getRecent(String chatId); /** * Get recent messages with count limit. * Returns the last N messages. * Does not delete any messages, only limits what is returned. */ List<ChatMessage> getRecent(String chatId, int limit); /** * Get all messages for a chat. */ List<ChatMessage> getAll(String chatId); /** * Delete a specific message. */ void delete(String messageId); /** * Delete all messages for a chat. */ void deleteAll(String chatId); /** * Get total token count for a chat. */ int getTotalTokens(String chatId); /** * Check if chat exists. */ boolean chatExists(String chatId); /** * Get a message by ID. */ ChatMessage getById(String messageId); }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/service/TextTokenizer.java
package ai.driftkit.common.service; /** * Simple text tokenizer for estimating token counts. */ public interface TextTokenizer { int DEFAULT_TOKEN_COST = 4; /** * Estimate token count for a text string. */ int estimateTokens(String text); }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/service
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/service/impl/InMemoryChatStore.java
package ai.driftkit.common.service.impl; import ai.driftkit.common.domain.chat.ChatMessage; import ai.driftkit.common.domain.chat.ChatMessage.MessageType; import ai.driftkit.common.domain.chat.ChatRequest; import ai.driftkit.common.domain.chat.ChatResponse; import ai.driftkit.common.service.ChatStore; import ai.driftkit.common.service.TextTokenizer; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * In-memory implementation of ChatStore. * Thread-safe implementation using ConcurrentHashMap. */ @Slf4j @RequiredArgsConstructor public class InMemoryChatStore implements ChatStore { private final TextTokenizer tokenizer; private final int defaultMaxTokens; // Storage: chatId -> list of messages private final Map<String, List<ChatMessage>> storage = new ConcurrentHashMap<>(); // Message index: messageId -> message private final Map<String, ChatMessage> messageIndex = new ConcurrentHashMap<>(); public InMemoryChatStore(TextTokenizer tokenizer) { this(tokenizer, 4096); } @Override public void add(String chatId, String content, MessageType type) { ChatMessage message = createMessage(chatId, type); message.updateOrAddProperty("message", content); add(message); } @Override public void add(String chatId, Map<String, String> properties, MessageType type) { ChatMessage message = createMessage(chatId, type); message.setPropertiesMap(properties); add(message); } @Override public void add(ChatMessage message) { if (message == null || message.getChatId() == null) { throw new IllegalArgumentException("Message and chatId cannot be null"); } // Ensure message has an ID if (message.getId() == null) { message.setId(UUID.randomUUID().toString()); } // Ensure timestamp if (message.getTimestamp() == null) { message.setTimestamp(System.currentTimeMillis()); } // Add to storage storage.computeIfAbsent(message.getChatId(), k -> Collections.synchronizedList(new ArrayList<>())) .add(message); // Add to index messageIndex.put(message.getId(), message); log.debug("Added message {} to chat {}", message.getId(), message.getChatId()); } @Override public void update(ChatMessage message) { if (message == null || message.getId() == null) { throw new IllegalArgumentException("Message and messageId cannot be null"); } ChatMessage existing = messageIndex.get(message.getId()); if (existing == null) { throw new IllegalArgumentException("Message not found: " + message.getId()); } // Update in index messageIndex.put(message.getId(), message); // Update in storage List<ChatMessage> messages = storage.get(message.getChatId()); if (messages != null) { for (int i = 0; i < messages.size(); i++) { if (messages.get(i).getId().equals(message.getId())) { messages.set(i, message); break; } } } log.debug("Updated message {} in chat {}", message.getId(), message.getChatId()); } @Override public List<ChatMessage> getRecentWithinTokens(String chatId, int maxTokens) { List<ChatMessage> allMessages = getAll(chatId); if (allMessages.isEmpty()) { return allMessages; } List<ChatMessage> result = new ArrayList<>(); int totalTokens = 0; // Iterate from most recent to oldest for (int i = allMessages.size() - 1; i >= 0; i--) { ChatMessage message = allMessages.get(i); int messageTokens = estimateTokens(message); if (totalTokens + messageTokens > maxTokens) { break; } result.add(0, message); // Add to beginning to maintain order totalTokens += messageTokens; } return result; } @Override public List<ChatMessage> getRecent(String chatId) { return getRecentWithinTokens(chatId, defaultMaxTokens); } @Override public List<ChatMessage> getRecent(String chatId, int limit) { List<ChatMessage> allMessages = getAll(chatId); if (allMessages.size() <= limit) { return new ArrayList<>(allMessages); } // Return last 'limit' messages return new ArrayList<>(allMessages.subList(allMessages.size() - limit, allMessages.size())); } @Override public List<ChatMessage> getAll(String chatId) { List<ChatMessage> messages = storage.get(chatId); return messages != null ? new ArrayList<>(messages) : new ArrayList<>(); } @Override public void delete(String messageId) { ChatMessage message = messageIndex.remove(messageId); if (message != null) { List<ChatMessage> messages = storage.get(message.getChatId()); if (messages != null) { messages.removeIf(m -> messageId.equals(m.getId())); } log.debug("Deleted message {}", messageId); } } @Override public void deleteAll(String chatId) { List<ChatMessage> messages = storage.remove(chatId); if (messages != null) { messages.forEach(m -> messageIndex.remove(m.getId())); log.debug("Deleted all {} messages from chat {}", messages.size(), chatId); } } @Override public int getTotalTokens(String chatId) { return getAll(chatId).stream() .mapToInt(this::estimateTokens) .sum(); } @Override public boolean chatExists(String chatId) { return storage.containsKey(chatId) && !storage.get(chatId).isEmpty(); } @Override public ChatMessage getById(String messageId) { return messageIndex.get(messageId); } private int estimateTokens(ChatMessage message) { // Get all text content from properties String content = message.getPropertiesMap().values().stream() .filter(Objects::nonNull) .collect(Collectors.joining(" ")); return tokenizer.estimateTokens(content); } private ChatMessage createMessage(String chatId, MessageType type) { switch (type) { case USER: ChatRequest request = new ChatRequest(); request.setId(UUID.randomUUID().toString()); request.setChatId(chatId); request.setType(type); request.setTimestamp(System.currentTimeMillis()); return request; case AI: ChatResponse response = new ChatResponse(); response.setId(UUID.randomUUID().toString()); response.setChatId(chatId); response.setType(MessageType.AI); // Always use AI for responses response.setTimestamp(System.currentTimeMillis()); return response; default: ChatMessage message = new ChatMessage(); message.setId(UUID.randomUUID().toString()); message.setChatId(chatId); message.setType(type); message.setTimestamp(System.currentTimeMillis()); return message; } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/service
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/service/impl/SimpleTextTokenizer.java
package ai.driftkit.common.service.impl; import ai.driftkit.common.service.TextTokenizer; /** * Simple implementation of TextTokenizer using character count approximation. * Estimates ~4 characters per token on average. */ public class SimpleTextTokenizer implements TextTokenizer { private static final int CHARS_PER_TOKEN = 4; @Override public int estimateTokens(String text) { if (text == null || text.isEmpty()) { return 0; } // Simple approximation: ~4 characters per token return text.length() / CHARS_PER_TOKEN; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/tools/Tool.java
package ai.driftkit.common.tools; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to mark methods as tool functions that can be called by language models. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Tool { /** * Function name. If not specified, method name is used. */ String name() default ""; /** * Function description for the language model. */ String description(); }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/tools/ToolAnalyzer.java
package ai.driftkit.common.tools; import ai.driftkit.common.domain.client.ModelClient; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Analyzes methods and builds tool definitions for language models. * Similar to WorkflowAnalyzer but focused on function calling. */ @Slf4j public class ToolAnalyzer { // Mapping of primitive types to their wrapper classes private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER = new HashMap<>(); private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE = new HashMap<>(); static { PRIMITIVE_TO_WRAPPER.put(int.class, Integer.class); PRIMITIVE_TO_WRAPPER.put(long.class, Long.class); PRIMITIVE_TO_WRAPPER.put(double.class, Double.class); PRIMITIVE_TO_WRAPPER.put(float.class, Float.class); PRIMITIVE_TO_WRAPPER.put(boolean.class, Boolean.class); PRIMITIVE_TO_WRAPPER.put(char.class, Character.class); PRIMITIVE_TO_WRAPPER.put(byte.class, Byte.class); PRIMITIVE_TO_WRAPPER.put(short.class, Short.class); // Reverse mapping for (Map.Entry<Class<?>, Class<?>> entry : PRIMITIVE_TO_WRAPPER.entrySet()) { WRAPPER_TO_PRIMITIVE.put(entry.getValue(), entry.getKey()); } } /** * Analyzes a method and creates a ToolInfo with complete signature information. * * @param method The method to analyze * @param instance The instance to invoke method on (null for static methods) * @param functionName Optional function name (uses method name if null) * @param description Function description * @return ToolInfo with complete method analysis */ public static ToolInfo analyzeMethod(Method method, Object instance, String functionName, String description) { if (functionName == null || functionName.isEmpty()) { functionName = method.getName(); } // Get parameter information Parameter[] parameters = method.getParameters(); List<String> parameterNames = new ArrayList<>(); List<Type> parameterTypes = new ArrayList<>(); for (Parameter parameter : parameters) { parameterNames.add(parameter.getName()); parameterTypes.add(parameter.getType()); } Type returnType = method.getGenericReturnType(); // Generate tool definition ModelClient.Tool toolDefinition = generateToolDefinition(functionName, description, parameters); boolean isStatic = instance == null; return new ToolInfo( functionName, description, method, instance, parameterNames, parameterTypes, returnType, isStatic, toolDefinition ); } /** * Analyzes all methods with @ToolFunction annotation in a class. * Supports both static methods and instance methods. * * @param clazz The class to analyze * @param instance The instance (null for static methods only) * @return List of ToolInfo for annotated methods */ public static List<ToolInfo> analyzeClass(Class<?> clazz, Object instance) { List<ToolInfo> tools = new ArrayList<>(); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { // Only process methods with @ToolFunction annotation if (method.isAnnotationPresent(Tool.class)) { Tool annotation = method.getAnnotation(Tool.class); String functionName = annotation.name().isEmpty() ? method.getName() : annotation.name(); String description = annotation.description(); boolean isStatic = Modifier.isStatic(method.getModifiers()); Object methodInstance = isStatic ? null : instance; // Validate that we have instance for non-static methods if (!isStatic && instance == null) { log.warn("Skipping non-static method {} because no instance provided", method.getName()); continue; } ToolInfo toolInfo = analyzeMethod(method, methodInstance, functionName, description); tools.add(toolInfo); log.debug("Found {} tool function: {} in class {}", isStatic ? "static" : "instance", functionName, clazz.getSimpleName()); } } return tools; } /** * Analyzes only static methods with @ToolFunction annotation in a class. * * @param clazz The class to analyze * @return List of ToolInfo for static annotated methods */ public static List<ToolInfo> analyzeStaticMethods(Class<?> clazz) { return analyzeClass(clazz, null); } /** * Generates a ModelClient.Tool definition from method parameters. */ private static ModelClient.Tool generateToolDefinition(String functionName, String description, Parameter[] parameters) { ModelClient.Tool tool = new ModelClient.Tool(); tool.setType(ModelClient.ResponseFormatType.function); ModelClient.ToolFunction toolFunction = new ModelClient.ToolFunction(); toolFunction.setName(functionName); toolFunction.setDescription(description); // Create parameters schema ModelClient.ToolFunction.FunctionParameters functionParameters = new ModelClient.ToolFunction.FunctionParameters(); functionParameters.setType(ModelClient.ResponseFormatType.Object); Map<String, ModelClient.Property> properties = new ConcurrentHashMap<>(); List<String> required = new ArrayList<>(); // Process each parameter for (Parameter parameter : parameters) { String paramName = parameter.getName(); Class<?> paramType = parameter.getType(); ModelClient.Property property = createPropertyFromType(paramType); properties.put(paramName, property); // All parameters are required by default required.add(paramName); } functionParameters.setProperties(properties); functionParameters.setRequired(required); toolFunction.setParameters(functionParameters); tool.setFunction(toolFunction); log.debug("Generated tool definition for function: {}", functionName); return tool; } /** * Creates a ModelClient.Property from a Java type. * Supports recursive parsing for complex objects. */ private static ModelClient.Property createPropertyFromType(Class<?> type) { return createPropertyFromType(type, new HashSet<>()); } /** * Creates a ModelClient.Property from a Java type with cycle detection. */ private static ModelClient.Property createPropertyFromType(Class<?> type, Set<Class<?>> visitedTypes) { ModelClient.Property property = new ModelClient.Property(); if (String.class.equals(type)) { property.setType(ModelClient.ResponseFormatType.String); } else if (Integer.class.equals(type) || int.class.equals(type) || Long.class.equals(type) || long.class.equals(type)) { property.setType(ModelClient.ResponseFormatType.Integer); } else if (Double.class.equals(type) || double.class.equals(type) || Float.class.equals(type) || float.class.equals(type)) { property.setType(ModelClient.ResponseFormatType.Number); } else if (Boolean.class.equals(type) || boolean.class.equals(type)) { property.setType(ModelClient.ResponseFormatType.Boolean); } else if (type.isEnum()) { property.setType(ModelClient.ResponseFormatType.String); // Add enum values List<String> enumValues = new ArrayList<>(); for (Object enumConstant : type.getEnumConstants()) { enumValues.add(enumConstant.toString()); } property.setEnumValues(enumValues); } else if (type.isArray()) { property.setType(ModelClient.ResponseFormatType.Array); Class<?> componentType = type.getComponentType(); ModelClient.Property itemProperty = createPropertyFromType(componentType, visitedTypes); property.setItems(itemProperty); } else if (Collection.class.isAssignableFrom(type)) { property.setType(ModelClient.ResponseFormatType.Array); // For collections, we can't determine the generic type at runtime without additional info ModelClient.Property itemProperty = new ModelClient.Property(); itemProperty.setType(ModelClient.ResponseFormatType.Object); property.setItems(itemProperty); } else if (Map.class.isAssignableFrom(type)) { property.setType(ModelClient.ResponseFormatType.Object); property.setDescription("Map with string keys"); } else { // For complex objects, recursively parse fields property.setType(ModelClient.ResponseFormatType.Object); // Prevent infinite recursion if (visitedTypes.contains(type)) { property.setDescription("Recursive reference to " + type.getSimpleName()); return property; } visitedTypes.add(type); Map<String, ModelClient.Property> properties = new HashMap<>(); // Parse all declared fields Field[] fields = type.getDeclaredFields(); for (Field field : fields) { // Skip static and transient fields if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) { continue; } String fieldName = field.getName(); Class<?> fieldType = field.getType(); ModelClient.Property fieldProperty = createPropertyFromType(fieldType, new HashSet<>(visitedTypes)); properties.put(fieldName, fieldProperty); } property.setProperties(properties); // Don't set required for nested object fields - only top-level parameters are required by default property.setDescription(type.getSimpleName()); } return property; } /** * Invokes a tool function with strongly typed arguments. * Handles both static and instance methods. * * @param toolInfo The tool information * @param arguments Arguments in the order of method parameters * @return Method execution result */ public static Object invokeToolFunction(ToolInfo toolInfo, Object... arguments) { try { Method method = toolInfo.getMethod(); Object instance = toolInfo.getInstance(); // Validate argument count if (arguments.length != toolInfo.getParameterTypes().size()) { throw new IllegalArgumentException("Argument count mismatch for function " + toolInfo.getFunctionName() + ": expected " + toolInfo.getParameterTypes().size() + ", got " + arguments.length); } // Type check arguments for (int i = 0; i < arguments.length; i++) { Type expectedType = toolInfo.getParameterTypes().get(i); Object arg = arguments[i]; if (arg != null && expectedType instanceof Class<?>) { Class<?> expectedClass = (Class<?>) expectedType; if (!isAssignableFrom(expectedClass, arg.getClass())) { throw new IllegalArgumentException("Type mismatch for parameter " + i + " in function " + toolInfo.getFunctionName() + ": expected " + expectedClass.getSimpleName() + ", got " + arg.getClass().getSimpleName()); } } } // Invoke method (instance will be null for static methods) return method.invoke(instance, arguments); } catch (Exception e) { log.error("Error invoking tool function {}: {}", toolInfo.getFunctionName(), e.getMessage(), e); throw new RuntimeException("Tool function execution failed: " + toolInfo.getFunctionName(), e); } } /** * Checks if a class is assignable from another class, handling primitives. */ private static boolean isAssignableFrom(Class<?> expected, Class<?> actual) { if (expected.isAssignableFrom(actual)) { return true; } // Check primitive to wrapper conversions Class<?> wrapper = PRIMITIVE_TO_WRAPPER.get(expected); if (wrapper != null && wrapper.equals(actual)) { return true; } // Check wrapper to primitive conversions Class<?> primitive = WRAPPER_TO_PRIMITIVE.get(expected); if (primitive != null && primitive.equals(actual)) { return true; } return false; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/tools/ToolCall.java
package ai.driftkit.common.tools; import ai.driftkit.common.utils.ModelUtils; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Map; /** * Represents a tool call from the language model. * Used in responses when the model decides to call a function. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ToolCall { @JsonProperty("id") private String id; @JsonProperty("type") private String type = "function"; @JsonProperty("function") private FunctionCall function; @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class FunctionCall { @JsonProperty("name") private String name; @JsonProperty("arguments") private Map<String, JsonNode> arguments; // Function arguments as JsonNode for flexible type handling /** * Parse argument value to the specified type */ public <T> T getArgumentAs(String argName, Class<T> type) { if (arguments == null || !arguments.containsKey(argName)) { return null; } JsonNode node = arguments.get(argName); if (node == null || node.isNull()) { return null; } try { // Use ModelUtils ObjectMapper for consistent parsing return ModelUtils.OBJECT_MAPPER.treeToValue(node, type); } catch (Exception e) { throw new IllegalArgumentException("Failed to parse argument '" + argName + "' to type " + type.getName(), e); } } /** * Get argument as a specific type with default value */ public <T> T getArgumentAs(String argName, Class<T> type, T defaultValue) { T value = getArgumentAs(argName, type); return value != null ? value : defaultValue; } /** * Check if argument exists */ public boolean hasArgument(String argName) { return arguments != null && arguments.containsKey(argName); } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/tools/ToolInfo.java
package ai.driftkit.common.tools; import ai.driftkit.common.domain.client.ModelClient; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.List; /** * Information about a tool function including method signature analysis. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ToolInfo { private String functionName; // Function name private String description; // Function description private Method method; // The actual method to invoke private Object instance; // Instance to invoke method on (null for static methods) private List<String> parameterNames; // Parameter names private List<Type> parameterTypes; // Parameter types private Type returnType; // Return type private boolean isStatic; // Whether this is a static method private ModelClient.Tool toolDefinition; // Generated tool definition for LLM }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/tools/ToolRegistry.java
package ai.driftkit.common.tools; import ai.driftkit.common.domain.client.ModelClient; import ai.driftkit.common.utils.ModelUtils; import com.fasterxml.jackson.databind.JsonNode; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Registry for managing and executing tools (functions) that can be called by language models. */ @Slf4j public class ToolRegistry { private final Map<String, ToolInfo> tools = new ConcurrentHashMap<>(); /** * Registers a single method as a tool function. * * @param toolInfo The tool information from ToolAnalyzer */ public void registerTool(ToolInfo toolInfo) { String functionName = toolInfo.getFunctionName(); if (tools.containsKey(functionName)) { log.warn("Overwriting existing tool function: {}", functionName); } tools.put(functionName, toolInfo); log.info("Registered tool function: {}", functionName); } /** * Registers a specific method as a tool function. * Uses method name as function name. * * @param method The method to register * @param instance The instance to invoke method on (null for static methods) */ public void registerMethod(Method method, Object instance) { registerMethod(method, instance, null); } /** * Registers a specific method as a tool function with optional description. * * @param method The method to register * @param instance The instance to invoke method on (null for static methods) * @param description Optional function description (uses method name if null) */ public void registerMethod(Method method, Object instance, String description) { String functionName = method.getName(); if (description == null || description.isEmpty()) { description = "Function: " + functionName; } ToolInfo toolInfo = ToolAnalyzer.analyzeMethod(method, instance, functionName, description); registerTool(toolInfo); } /** * Registers a specific method by name from a class instance. * Uses method name as function name. * * @param instance The class instance * @param methodName The method name */ public void registerInstanceMethod(Object instance, String methodName) { registerInstanceMethod(instance, methodName, null); } /** * Registers a specific method by name from a class instance with optional description. * * @param instance The class instance * @param methodName The method name * @param description Optional function description */ public void registerInstanceMethod(Object instance, String methodName, String description) { try { Method method = findMethodByName(instance.getClass(), methodName); registerMethod(method, instance, description); } catch (NoSuchMethodException e) { throw new RuntimeException("Method not found: " + methodName + " in class " + instance.getClass().getSimpleName(), e); } } /** * Registers a static method by name from a class. * Uses method name as function name. * * @param clazz The class * @param methodName The method name */ public void registerStaticMethod(Class<?> clazz, String methodName) { registerStaticMethod(clazz, methodName, null); } /** * Registers a static method by name from a class with optional description. * * @param clazz The class * @param methodName The method name * @param description Optional function description */ public void registerStaticMethod(Class<?> clazz, String methodName, String description) { try { Method method = findMethodByName(clazz, methodName); registerMethod(method, null, description); } catch (NoSuchMethodException e) { throw new RuntimeException("Static method not found: " + methodName + " in class " + clazz.getSimpleName(), e); } } /** * Registers all @ToolFunction annotated methods from a class instance. * * @param instance The class instance containing tool methods */ public void registerClass(Object instance) { List<ToolInfo> classTools = ToolAnalyzer.analyzeClass(instance.getClass(), instance); for (ToolInfo toolInfo : classTools) { registerTool(toolInfo); } log.info("Registered {} tools from class: {}", classTools.size(), instance.getClass().getSimpleName()); } /** * Registers all static @ToolFunction annotated methods from a class. * * @param clazz The class containing static tool methods */ public void registerStaticClass(Class<?> clazz) { List<ToolInfo> staticTools = ToolAnalyzer.analyzeStaticMethods(clazz); for (ToolInfo toolInfo : staticTools) { registerTool(toolInfo); } log.info("Registered {} static tools from class: {}", staticTools.size(), clazz.getSimpleName()); } /** * Executes a tool function by name with the provided arguments. * * @param functionName Function name * @param arguments Function arguments in the order of method parameters * @return Function execution result */ public Object executeFunction(String functionName, Object... arguments) { ToolInfo toolInfo = tools.get(functionName); if (toolInfo == null) { throw new RuntimeException("Function not found: " + functionName); } return ToolAnalyzer.invokeToolFunction(toolInfo, arguments); } /** * Executes a tool function from a ToolCall with parsed arguments. * Converts the Map arguments to typed method parameters. * * @param toolCall The tool call with parsed arguments * @return Function execution result */ public Object executeToolCall(ToolCall toolCall) { String functionName = toolCall.getFunction().getName(); Map<String, JsonNode> argumentsMap = toolCall.getFunction().getArguments(); ToolInfo toolInfo = tools.get(functionName); if (toolInfo == null) { throw new RuntimeException("Function not found: " + functionName); } // Check if this is a tool with no method (e.g., AgentAsTool) if (toolInfo.getMethod() == null && toolInfo.getInstance() != null) { try { // For tools without methods, we expect the instance to have an execute method // Convert arguments to the tool's argument type Object arguments = convertArgumentsToToolType(toolInfo, argumentsMap); // Use reflection to call execute method Type paramType = toolInfo.getParameterTypes().get(0); Class<?> paramClass = (paramType instanceof Class<?>) ? (Class<?>) paramType : Object.class; Method executeMethod = toolInfo.getInstance().getClass().getMethod("execute", paramClass); return executeMethod.invoke(toolInfo.getInstance(), arguments); } catch (Exception e) { throw new RuntimeException("Failed to execute tool: " + functionName, e); } } else { // Standard method invocation Object[] methodArgs = convertArgumentsToArray(toolInfo, argumentsMap); return ToolAnalyzer.invokeToolFunction(toolInfo, methodArgs); } } /** * Converts Map arguments to typed array for method invocation. */ private Object[] convertArgumentsToArray(ToolInfo toolInfo, Map<String, JsonNode> argumentsMap) { List<String> parameterNames = toolInfo.getParameterNames(); List<Type> parameterTypes = toolInfo.getParameterTypes(); Object[] methodArgs = new Object[parameterNames.size()]; for (int i = 0; i < parameterNames.size(); i++) { Type type = parameterTypes.get(i); String paramName = parameterNames.get(i); JsonNode jsonNode = argumentsMap.get(paramName); if (jsonNode == null || jsonNode.isNull()) { methodArgs[i] = null; } else { try { // Convert JsonNode to the actual parameter type if (type instanceof Class<?>) { Class<?> paramClass = (Class<?>) type; methodArgs[i] = ModelUtils.OBJECT_MAPPER.treeToValue(jsonNode, paramClass); } else { // For generic types, use TypeReference methodArgs[i] = ModelUtils.OBJECT_MAPPER.convertValue(jsonNode, ModelUtils.OBJECT_MAPPER.constructType(type)); } } catch (Exception e) { throw new RuntimeException("Failed to convert argument '" + paramName + "' to type " + type.getTypeName() + " for function " + toolInfo.getFunctionName(), e); } } } return methodArgs; } /** * Converts Map arguments to tool's argument type. */ private Object convertArgumentsToToolType(ToolInfo toolInfo, Map<String, JsonNode> argumentsMap) { try { // Get the first parameter type which should be the argument type if (toolInfo.getParameterTypes() == null || toolInfo.getParameterTypes().isEmpty()) { throw new RuntimeException("No parameter types defined for tool: " + toolInfo.getFunctionName()); } Type argumentType = toolInfo.getParameterTypes().get(0); // Convert the entire argumentsMap to the tool's argument type if (argumentType instanceof Class<?>) { return ModelUtils.OBJECT_MAPPER.convertValue(argumentsMap, (Class<?>) argumentType); } else { return ModelUtils.OBJECT_MAPPER.convertValue(argumentsMap, ModelUtils.OBJECT_MAPPER.constructType(argumentType)); } } catch (Exception e) { throw new RuntimeException("Failed to convert arguments to type " + toolInfo.getParameterTypes().get(0).getTypeName() + " for tool " + toolInfo.getFunctionName(), e); } } /** * Gets all registered tools as ModelClient.Tool objects for LLM. * * @return Array of tool definitions */ public ModelClient.Tool[] getTools() { return tools.values().stream() .map(ToolInfo::getToolDefinition) .toArray(ModelClient.Tool[]::new); } /** * Gets tool information by function name. * * @param functionName Function name * @return ToolInfo or null if not found */ public ToolInfo getToolInfo(String functionName) { return tools.get(functionName); } /** * Checks if a function is registered. * * @param functionName Function name * @return true if function exists */ public boolean hasFunction(String functionName) { return tools.containsKey(functionName); } /** * Removes a tool function from registry. * * @param functionName Function name to remove * @return true if function was removed */ public boolean removeFunction(String functionName) { ToolInfo removed = tools.remove(functionName); if (removed != null) { log.info("Removed tool function: {}", functionName); return true; } return false; } /** * Clears all registered tools. */ public void clearAll() { int count = tools.size(); tools.clear(); log.info("Cleared {} tool functions from registry", count); } /** * Gets the number of registered tools. * * @return Number of registered tools */ public int size() { return tools.size(); } /** * Helper method to find a method by name in a class. * Handles method overloading by returning the first match. */ private Method findMethodByName(Class<?> clazz, String methodName) throws NoSuchMethodException { Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { return method; } } throw new NoSuchMethodException("Method " + methodName + " not found in class " + clazz.getSimpleName()); } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/util/Retrier.java
package ai.driftkit.common.util; import java.util.concurrent.Callable; import java.util.function.Consumer; /** * Utility class for retrying operations with exponential backoff */ public class Retrier { private static final int DEFAULT_TRIALS = 3; private static final int DEFAULT_DELAY = 3000; private Retrier() { } public static void retry(Runnable runnable) throws Exception { retry(runnable, 3L); } public static <R> R retry(Callable<R> callable) throws Exception { return retry(callable, 3L); } public static void retry(Runnable runnable, long delay) throws Exception { retry(runnable, 3, delay / 3L, 1); } public static <R> R retry(Callable<R> callable, long delay) throws Exception { return retry(callable, 3, delay / 3L, 1); } public static void retry(Runnable runnable, int trials, long delay) throws Exception { retry(runnable, trials, delay, 1); } public static <R> R retry(Callable<R> callable, int trials, long delay) throws Exception { return retry(callable, trials, delay, 1); } public static void retryQuietly(Runnable runnable, Consumer<Exception> log) { try { retry(runnable, 3L); } catch (Exception e) { log.accept(e); } } public static <R> R retryQuietly(Callable<R> callable, Consumer<Exception> log) { try { return retry(callable, 3000L); } catch (Exception e) { log.accept(e); return null; } } public static void retryQuietly(Runnable runnable, Consumer<Exception> log, int trials, long delay, int multiplier) { try { retry(runnable, trials, delay, multiplier); } catch (Exception e) { log.accept(e); } } public static <R> R retryQuietly(Callable<R> callable, Consumer<Exception> log, int trials, long delay, int multiplier) { try { return retry(callable, trials, delay, multiplier); } catch (Exception e) { log.accept(e); return null; } } public static <R> R retry(Callable<R> callable, int trials, long delay, int multiplier) throws Exception { for(int trial = 0; trial < trials; delay *= (long)multiplier) { ++trial; try { return callable.call(); } catch (Exception e) { if (trial >= trials) { throw e; } Thread.sleep(delay); } } return null; } public static void retry(Runnable runnable, int trials, long delay, int multiplier) throws Exception { for(int trial = 0; trial < trials; delay *= (long)multiplier) { ++trial; try { runnable.run(); return; } catch (Exception e) { if (trial >= trials) { throw e; } Thread.sleep(delay); } } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/AIUtils.java
package ai.driftkit.common.utils; import java.util.UUID; public class AIUtils { public static String generateId() { return UUID.randomUUID().toString(); } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/Counter.java
package ai.driftkit.common.utils; import lombok.Data; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @Data public class Counter<T> { Map<T, AtomicInteger> counters; public static class CounterNamed extends Counter<String> { public CounterNamed() { super(); } public Map<String, Integer> getMap() { return entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().intValue())); } } public Counter() { this.counters = new ConcurrentHashMap<>(); } public int increment(T name) { return getMutableInt(name).incrementAndGet(); } public int add(T name, int add) { return getMutableInt(name).addAndGet(add); } public int get(T name) { return getMutableInt(name).intValue(); } public Set<Entry<T, AtomicInteger>> entrySet() { return counters.entrySet(); } private AtomicInteger getMutableInt(T name) { return counters.computeIfAbsent(name, k -> new AtomicInteger()); } @Override public String toString() { return String.valueOf(counters); } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/DocumentSplitter.java
package ai.driftkit.common.utils; import java.text.BreakIterator; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class DocumentSplitter { public static List<String> splitDocumentIntoShingles(String text, int chunkSize, int overlap) { // Validate inputs if (chunkSize <= 0) { throw new IllegalArgumentException("chunkSize must be positive"); } if (overlap < 0) { throw new IllegalArgumentException("overlap cannot be negative"); } if (overlap >= chunkSize) { throw new IllegalArgumentException("overlap must be less than chunkSize"); } if (text == null || text.isEmpty()) { return new ArrayList<>(); } List<String> chunks = new ArrayList<>(); // Try to split text into sentences first List<String> tokens = splitTextIntoSentences(text); // If no sentences found, split into words if (tokens.isEmpty()) { tokens = splitTextIntoWords(text); } // Now group tokens into chunks int index = 0; while (index < tokens.size()) { int currentSize = 0; int startIdx = index; List<String> chunkTokens = new ArrayList<>(); while (index < tokens.size() && currentSize + tokens.get(index).length() <= chunkSize) { String token = tokens.get(index); chunkTokens.add(token); currentSize += token.length() + 1; // +1 for space or punctuation index++; } // If no tokens were added (token is longer than chunkSize), add it partially if (chunkTokens.isEmpty()) { String token = tokens.get(index); String partialToken = token.substring(0, Math.min(chunkSize, token.length())); chunks.add(partialToken); index++; } else { // Build the chunk string String chunk = String.join(" ", chunkTokens).trim(); if (!chunk.isEmpty()) { chunks.add(chunk); } } // Handle overlap index = startIdx + Math.max(1, chunkTokens.size() - overlap); } return chunks; } private static List<String> splitTextIntoSentences(String text) { List<String> sentences = new ArrayList<>(); BreakIterator sentenceIterator = BreakIterator.getSentenceInstance(Locale.getDefault()); sentenceIterator.setText(text); int start = sentenceIterator.first(); int end = sentenceIterator.next(); while (end != BreakIterator.DONE) { String sentence = text.substring(start, end).trim(); if (!sentence.isEmpty()) { sentences.add(sentence); } start = end; end = sentenceIterator.next(); } return sentences; } private static List<String> splitTextIntoWords(String text) { List<String> words = new ArrayList<>(); BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault()); wordIterator.setText(text); int start = wordIterator.first(); int end = wordIterator.next(); while (end != BreakIterator.DONE) { String word = text.substring(start, end).trim(); if (!word.isEmpty() && Character.isLetterOrDigit(word.codePointAt(0))) { words.add(word); } start = end; end = wordIterator.next(); } return words; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/JarResourceLister.java
package ai.driftkit.common.utils; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.*; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Utility class to locate and list resources within a JAR file or directory on the classpath. */ public class JarResourceLister { /** * Retrieves the absolute path to the JAR file or directory from which the specified class was loaded. * * @param clazz The class to locate the JAR file or directory for. * @return The absolute file system path to the JAR file or directory. * @throws URISyntaxException If the URL to URI conversion fails. */ public static String getJarOrDirectoryPath(Class<?> clazz) throws URISyntaxException { // Obtain the URL of the JAR file or directory URL resourceURL = clazz.getProtectionDomain().getCodeSource().getLocation(); // Convert URL to URI and then to a file system path return Paths.get(resourceURL.toURI()).toString(); } /** * Lists all resources within a specific folder inside the JAR or directory. * * @param jarOrDirPath The file system path to the JAR file or directory. * @param folderPath The folder path inside the JAR or directory (e.g., "resources/images/"). * Ensure it ends with a '/'. * @return A list of resource names relative to the folderPath. * @throws IOException If an I/O error occurs while reading the JAR file or directory. */ public static List<String> listResources(String jarOrDirPath, String folderPath) throws IOException { List<String> resources = new ArrayList<>(); File file = new File(jarOrDirPath); if (file.isDirectory()) { // Handle directory Path dirPath = Paths.get(jarOrDirPath, folderPath); if (Files.exists(dirPath) && Files.isDirectory(dirPath)) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(dirPath)) { for (Path entry : stream) { String currentInternalDir = entry.toString().replace(jarOrDirPath, ""); if (Files.isRegularFile(entry)) { resources.add(currentInternalDir); } else { resources.addAll(listResources(jarOrDirPath, currentInternalDir)); } } } } else { System.err.println("The specified folder path does not exist or is not a directory: " + dirPath); } } else { // Assume it's a JAR file try (JarFile jarFile = new JarFile(jarOrDirPath)) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); // Check if the entry is in the desired folder and is not a directory if (entryName.startsWith(folderPath)) { if (entry.isDirectory()) { resources.addAll(listResources(jarOrDirPath, entryName)); } else { // Extract the relative path String relativePath = entryName.substring(folderPath.length()); // Optionally, exclude files in subdirectories if (!relativePath.isEmpty() && !relativePath.contains("/")) { resources.add(relativePath); } } } } } catch (IOException e) { System.err.println("Failed to read JAR file: " + jarOrDirPath); throw e; } } return resources; } /** * Convenience method to list resources from a specific folder relative to the given class. * * @param clazz The class to locate the JAR or directory for. * @param folder The folder path inside the JAR or directory. * @return A list of resource names relative to the folder. * @throws URISyntaxException If the URL to URI conversion fails. * @throws IOException If an I/O error occurs while reading the JAR file or directory. */ public static List<String> listResources(Class<?> clazz, String folder) throws URISyntaxException, IOException { String jarOrDirPath = getJarOrDirectoryPath(clazz); return listResources(jarOrDirPath, folder); } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/JsonRepairer.java
package ai.driftkit.common.utils; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Deque; import java.util.List; @Slf4j public class JsonRepairer { public static String fixDoubleQuotesAndCommas(String json) { List<String> fixedJSON = new ArrayList<>(); String[] jsonByLines = json.split("\\n"); for (int i = 0; i < jsonByLines.length; i++) { String trimmedLine = jsonByLines[i].trim(); long noOfDoubleQuote = JsonUtils.countOccurrences(trimmedLine, '"'); long noOfColon = JsonUtils.countOccurrences(trimmedLine, ':'); if (isSingleBracket(trimmedLine)) { handleSingleBracket(fixedJSON, trimmedLine); } else if (isQuotedField(noOfDoubleQuote, noOfColon, trimmedLine)) { String fixedDoubleQuotes = getQuoteCorrectedLastField(trimmedLine, jsonByLines, i); fixedJSON.add(fixedDoubleQuotes); } else if (isIncompleteQuotedField(noOfDoubleQuote)) { processIncompleteQuotedField(fixedJSON, trimmedLine, jsonByLines, i); } } return String.join(System.lineSeparator(), fixedJSON); } private static boolean isSingleBracket(String line) { return (line.length() == 1 || line.length() == 2) && JsonUtils.isBracket(line.charAt(0)); } private static void handleSingleBracket(List<String> fixedJSON, String line) { if (JsonUtils.isCloseBracket(line.charAt(0))) { removeCommaFromPreviousField(fixedJSON); } fixedJSON.add(line); } private static boolean isQuotedField(long noOfDoubleQuote, long noOfColon, String line) { return noOfDoubleQuote == 4 && (noOfColon >= 1 || line.contains("://")); } private static boolean isIncompleteQuotedField(long noOfDoubleQuote) { return noOfDoubleQuote < 4 && noOfDoubleQuote > 1; } private static void processIncompleteQuotedField(List<String> fixedJSON, String trimmedLine, String[] jsonByLines, int i) { String fixedDoubleQuotes = fixDoubleQuote(trimmedLine); String correctedLastField = getQuoteCorrectedLastField(fixedDoubleQuotes, jsonByLines, i); String booleanCorrectedField = correctBooleanValues(correctedLastField); fixedJSON.add(booleanCorrectedField); } private static boolean handleClosingBracket(Deque<Character> characterStack, char closingBracket) { if (characterStack.isEmpty()) { return false; } char openingBracket = characterStack.pop(); return JsonUtils.isMatchingBracket(openingBracket, closingBracket); } static boolean handleOpenBrackets(char jc, Deque<Character> bracketStack) { if (JsonUtils.isOpenBracket(jc)) { bracketStack.push(jc); } else if (JsonUtils.isCloseBracket(jc)) { Character topChar = bracketStack.peek(); if (topChar == null) { return false; } if (JsonUtils.isMatchingBracket(topChar, jc)) { bracketStack.pop(); return true; } } return false; } public static void appendRemainingClosingBrackets(StringBuilder fixedJson, Deque<Character> bracketStack) { while (!bracketStack.isEmpty()) { char element = bracketStack.pop(); appendNewLineAndClosingBracket(fixedJson, element); } } private static void appendNewLineAndClosingBracket(StringBuilder fixedJson, char element) { if (JsonUtils.isOpenSquareBracket(element)) { fixedJson.append(System.lineSeparator()).append(']'); } else if (JsonUtils.isOpenCurlyBracket(element)) { fixedJson.append(System.lineSeparator()).append('}'); } } private static String correctBooleanValues(String boolString) { return boolString.replace("false\"", "false").replace("true\"", "true"); } private static String getQuoteCorrectedLastField(String fixedDoubleQuotes, String[] jsonByLines, int i) { String lastFieldCorrected = fixedDoubleQuotes; if (isLastField(jsonByLines, i)) { lastFieldCorrected = fixedDoubleQuotes.replace(",", ""); } return lastFieldCorrected; } private static boolean isLastField(String[] jsonByLines, int i) { return i < jsonByLines.length - 1 && !jsonByLines[i + 1].isEmpty() && JsonUtils.isCloseBracket(jsonByLines[i + 1].trim().charAt(0)); } private static void removeCommaFromPreviousField(List<String> fixedJSON) { int lastIndex = fixedJSON.size() - 1; if (lastIndex > 0) { String lastField = fixedJSON.get(lastIndex).trim(); if (!lastField.isEmpty()) { String prevField = fixedJSON.get(lastIndex).replace(",", ""); fixedJSON.set(lastIndex, prevField); } } } private static String fixDoubleQuote(String jsonField) { StringBuilder fixedQuote = new StringBuilder(jsonField); ensureLeadingDoubleQuote(fixedQuote); appendCommaIfTrailingDoubleQuote(fixedQuote); appendCommaIfNeeded(fixedQuote); return fixedQuote.toString(); } private static void ensureLeadingDoubleQuote(StringBuilder fixedQuote) { if (!startsWithDoubleQuote(fixedQuote)) { fixedQuote.insert(0, '"'); } } private static boolean startsWithDoubleQuote(StringBuilder fixedQuote) { return !fixedQuote.isEmpty() && JsonUtils.isDoubleQuote(fixedQuote.charAt(0)); } private static void appendCommaIfTrailingDoubleQuote(StringBuilder fixedQuote) { if (endsWithDoubleQuote(fixedQuote)) { fixedQuote.append(','); } } private static boolean endsWithDoubleQuote(StringBuilder fixedQuote) { return !fixedQuote.isEmpty() && JsonUtils.isDoubleQuote(fixedQuote.charAt(fixedQuote.length() - 1)); } private static void appendCommaIfNeeded(StringBuilder fixedQuote) { char lastChar = fixedQuote.charAt(fixedQuote.length() - 1); if (!JsonUtils.isDoubleQuote(lastChar) && !JsonUtils.isComma(lastChar)) { if (Character.isDigit(lastChar)) { fixedQuote.append(","); } else { appendCommaBeforeNonBracket(fixedQuote, lastChar); } } } private static void appendCommaBeforeNonBracket(StringBuilder fixedQuote, char lastChar) { if (!JsonUtils.isOpenBracket(lastChar)) { fixedQuote.append("\","); } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/JsonSchemaGenerator.java
package ai.driftkit.common.utils; import ai.driftkit.common.annotation.JsonSchemaStrict; import ai.driftkit.common.domain.client.ModelClient.ResponseFormatType; import ai.driftkit.common.domain.client.ResponseFormat; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import lombok.extern.slf4j.Slf4j; import javax.validation.constraints.NotNull; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; /** * Utility class for generating JSON schemas from Java classes. * Supports generating OpenAI-compatible structured output schemas. */ @Slf4j public class JsonSchemaGenerator { private static final Set<Class<?>> PRIMITIVE_TYPES = Set.of( String.class, Integer.class, Long.class, Double.class, Float.class, Boolean.class, int.class, long.class, double.class, float.class, boolean.class ); /** * Generates a JSON schema from a Java class. * * @param clazz The class to generate schema from * @return ResponseFormat.JsonSchema representing the class structure */ public static ResponseFormat.JsonSchema generateSchema(Class<?> clazz) { return generateSchema(clazz, clazz.getSimpleName()); } /** * Generates a JSON schema from a Java class with a custom title. * * @param clazz The class to generate schema from * @param title The title for the schema * @return ResponseFormat.JsonSchema representing the class structure */ public static ResponseFormat.JsonSchema generateSchema(Class<?> clazz, String title) { ResponseFormat.JsonSchema schema = new ResponseFormat.JsonSchema(); schema.setTitle(title); schema.setType(ResponseFormatType.Object.getType()); schema.setAdditionalProperties(false); // Check if class is marked as strict boolean isStrict = clazz.isAnnotationPresent(JsonSchemaStrict.class); Map<String, ResponseFormat.SchemaProperty> properties = new LinkedHashMap<>(); List<String> required = new ArrayList<>(); // Process all declared fields for (Field field : clazz.getDeclaredFields()) { // Skip static and transient fields if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) { continue; } String propertyName = getPropertyName(field); ResponseFormat.SchemaProperty property = generateProperty(field, isStrict); properties.put(propertyName, property); if (isStrict || isRequired(field)) { required.add(propertyName); } } schema.setProperties(properties); if (!required.isEmpty()) { schema.setRequired(required); } // Set strict flag if all properties are required if (!properties.isEmpty() && required.size() == properties.size()) { schema.setStrict(true); } return schema; } /** * Generates a property definition for a field. * * @param field The field to generate property for * @param isStrict Whether the parent class is in strict mode * @return ResponseFormat.SchemaProperty or null if field should be skipped */ private static ResponseFormat.SchemaProperty generateProperty(Field field, boolean isStrict) { ResponseFormat.SchemaProperty property = new ResponseFormat.SchemaProperty(); Class<?> fieldType = field.getType(); Type genericType = field.getGenericType(); // Set description from annotation if present JsonPropertyDescription descriptionAnnotation = field.getAnnotation(JsonPropertyDescription.class); if (descriptionAnnotation != null) { property.setDescription(descriptionAnnotation.value()); } // Handle different types if (String.class.equals(fieldType)) { property.setType(ResponseFormatType.String.getType()); } else if (Integer.class.equals(fieldType) || int.class.equals(fieldType) || Long.class.equals(fieldType) || long.class.equals(fieldType)) { property.setType(ResponseFormatType.Integer.getType()); } else if (Double.class.equals(fieldType) || double.class.equals(fieldType) || Float.class.equals(fieldType) || float.class.equals(fieldType)) { property.setType(ResponseFormatType.Number.getType()); } else if (Boolean.class.equals(fieldType) || boolean.class.equals(fieldType)) { property.setType(ResponseFormatType.Boolean.getType()); } else if (fieldType.isEnum()) { property.setType(ResponseFormatType.String.getType()); List<String> enumValues = new ArrayList<>(); for (Object enumConstant : fieldType.getEnumConstants()) { enumValues.add(enumConstant.toString()); } property.setEnumValues(enumValues); } else if (List.class.isAssignableFrom(fieldType) || Set.class.isAssignableFrom(fieldType)) { property.setType(ResponseFormatType.Array.getType()); // Handle generic type for array items if (genericType instanceof ParameterizedType paramType) { Type[] typeArgs = paramType.getActualTypeArguments(); if (typeArgs.length > 0 && typeArgs[0] instanceof Class<?> itemClass) { ResponseFormat.SchemaProperty itemSchema = generateItemSchema(itemClass); property.setItems(itemSchema); } } } else if (Map.class.isAssignableFrom(fieldType)) { property.setType(ResponseFormatType.Object.getType()); // For maps, we can add additional properties schema if needed if (genericType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) genericType; Type[] typeArgs = paramType.getActualTypeArguments(); if (typeArgs.length == 2 && typeArgs[1] instanceof Class) { Class<?> valueClass = (Class<?>) typeArgs[1]; if (PRIMITIVE_TYPES.contains(valueClass)) { property.setAdditionalProperties(Map.of("type", getTypeString(valueClass))); } } } } else if (!PRIMITIVE_TYPES.contains(fieldType)) { // Nested object property.setType(ResponseFormatType.Object.getType()); ResponseFormat.JsonSchema nestedSchema = generateSchema(fieldType); property.setProperties(nestedSchema.getProperties()); property.setRequired(nestedSchema.getRequired()); property.setAdditionalProperties(false); } return property; } /** * Generates an item schema for array elements. * * @param itemClass The class of array items * @return ResponseFormat.SchemaProperty for the item */ private static ResponseFormat.SchemaProperty generateItemSchema(Class<?> itemClass) { ResponseFormat.SchemaProperty itemSchema = new ResponseFormat.SchemaProperty(); if (String.class.equals(itemClass)) { itemSchema.setType(ResponseFormatType.String.getType()); } else if (Integer.class.equals(itemClass) || Long.class.equals(itemClass)) { itemSchema.setType(ResponseFormatType.Integer.getType()); } else if (Double.class.equals(itemClass) || Float.class.equals(itemClass)) { itemSchema.setType(ResponseFormatType.Number.getType()); } else if (Boolean.class.equals(itemClass)) { itemSchema.setType(ResponseFormatType.Boolean.getType()); } else if (itemClass.isEnum()) { itemSchema.setType(ResponseFormatType.String.getType()); List<String> enumValues = new ArrayList<>(); for (Object enumConstant : itemClass.getEnumConstants()) { enumValues.add(enumConstant.toString()); } itemSchema.setEnumValues(enumValues); } else if (!PRIMITIVE_TYPES.contains(itemClass)) { // Nested object in array ResponseFormat.JsonSchema nestedSchema = generateSchema(itemClass); itemSchema.setType(ResponseFormatType.Object.getType()); itemSchema.setProperties(nestedSchema.getProperties()); itemSchema.setRequired(nestedSchema.getRequired()); itemSchema.setAdditionalProperties(false); } return itemSchema; } /** * Gets the property name for a field, considering JsonProperty annotation. * * @param field The field to get property name for * @return The property name */ private static String getPropertyName(Field field) { JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class); if (jsonProperty != null && !jsonProperty.value().isEmpty()) { return jsonProperty.value(); } return field.getName(); } /** * Checks if a field is required (not nullable). * * @param field The field to check * @return true if field is required */ private static boolean isRequired(Field field) { // Check for @NotNull annotation if (field.isAnnotationPresent(NotNull.class)) { return true; } // Check for @JsonProperty(required = true) JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class); if (jsonProperty != null && jsonProperty.required()) { return true; } // Check for lombok @NonNull if (field.isAnnotationPresent(lombok.NonNull.class)) { return true; } // Primitive types are always required return field.getType().isPrimitive(); } /** * Gets the JSON type string for a Java class. * * @param clazz The class to get type for * @return The JSON type string */ private static String getTypeString(Class<?> clazz) { if (String.class.equals(clazz)) { return ResponseFormatType.String.getType(); } else if (Integer.class.equals(clazz) || Long.class.equals(clazz) || int.class.equals(clazz) || long.class.equals(clazz)) { return ResponseFormatType.Integer.getType(); } else if (Double.class.equals(clazz) || Float.class.equals(clazz) || double.class.equals(clazz) || float.class.equals(clazz)) { return ResponseFormatType.Number.getType(); } else if (Boolean.class.equals(clazz) || boolean.class.equals(clazz)) { return ResponseFormatType.Boolean.getType(); } else if (clazz.isEnum()) { return ResponseFormatType.String.getType(); } else { return ResponseFormatType.Object.getType(); } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/JsonUtils.java
package ai.driftkit.common.utils; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.StreamReadFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @Slf4j public class JsonUtils { private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectReader mapperRelaxed = mapper.reader() .with(Feature.ALLOW_COMMENTS) .with(Feature.ALLOW_MISSING_VALUES) .with(Feature.ALLOW_TRAILING_COMMA) .with(Feature.ALLOW_COMMENTS) .with(Feature.ALLOW_SINGLE_QUOTES) .with(Feature.ALLOW_YAML_COMMENTS) .with(Feature.ALLOW_UNQUOTED_FIELD_NAMES) .with(StreamReadFeature.AUTO_CLOSE_SOURCE) .with(StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION); private static final Pattern JSON_PATTERN = Pattern.compile("\\{[^\\{\\}]*\\}"); private static final Pattern EXTRACT_JSON_PATTERN = Pattern.compile("\\{"); public static final String JSON_PREFIX = "```json"; public static final String JSON_POSTFIX = "```"; private JsonUtils() { } public static boolean isContainJson(String text) { Matcher matcher = JSON_PATTERN.matcher(text); return matcher.find(); } public static String extractJsonFromText(String text) { if (StringUtils.isBlank(text)) { return null; } Matcher matcher = EXTRACT_JSON_PATTERN.matcher(text); Stack<Character> braceStack = new Stack<>(); int startIndex = -1; int endIndex = -1; // Search for the first curly brace that starts the JSON while (matcher.find()) { startIndex = matcher.start(); braceStack.push('{'); // Traverse through the text and balance the curly braces for (int i = startIndex + 1; i < text.length(); i++) { char currentChar = text.charAt(i); if (currentChar == '{') { braceStack.push('{'); } else if (currentChar == '}') { braceStack.pop(); } // When the stack is empty, we've found the matching closing brace if (braceStack.isEmpty()) { endIndex = i; break; } } // If we found a matching closing brace, extract the JSON if (endIndex != -1) { return text.substring(startIndex, endIndex + 1); } } return null; } public static boolean isOpenCurlyBracket(char c) { return c == '{'; } public static boolean isCloseCurlyBracket(char c) { return c == '}'; } public static boolean isOpenSquareBracket(char c) { return c == '['; } public static boolean isCloseSquareBracket(char c) { return c == ']'; } public static boolean isDoubleQuote(char c) { return c == '"'; } public static boolean isDoubleQuote(int c) { return c == '"'; } public static boolean isComma(char c) { return c == ','; } public static boolean isColon(int c) { return c == ':'; } public static boolean isMatchingBracket(char opening, char closing) { return (opening == '{' && closing == '}') || (opening == '[' && closing == ']'); } public static boolean isOpenBracket(char c) { return isOpenCurlyBracket(c) || isOpenSquareBracket(c); } public static boolean isCloseBracket(char c) { return isCloseCurlyBracket(c) || isCloseSquareBracket(c); } public static boolean isBracket(char c) { return isOpenBracket(c) || isCloseBracket(c); } public static long countOccurrences(String line, char character) { return line.chars().filter(c -> c == character).count(); } public static boolean isJSON(String jsonString) { return jsonString != null && (jsonString.startsWith("\"{") || jsonString.contains(JSON_PREFIX) || jsonString.startsWith("json") || jsonString.startsWith("{") || jsonString.startsWith("[")); } public static boolean isValidJSON(String jsonString) { try { mapper.readTree(jsonString); return true; } catch (Exception e) { return false; } } /** * 1. Add missing brackets * 2. Remove uncompleted fields * 3. Add correct double quotes * 4. Remove extra comma */ @SneakyThrows public static String fixIncompleteJSON(String jsonString) { if (isValidJSON(jsonString) && !jsonString.startsWith("\"{")) { return jsonString; } if (jsonString.contains(JSON_PREFIX)) { jsonString = jsonString.substring(jsonString.lastIndexOf(JSON_PREFIX)); } if (jsonString.startsWith("\"{") || jsonString.startsWith("\"[")) { jsonString = jsonString.replace("\\\"", "\"").substring(1); jsonString = jsonString.substring(0, jsonString.length() - 1); } jsonString = jsonString .replace(JSON_PREFIX, "") .replace(JSON_POSTFIX, ""); //.replace("\\\"", "\""); for (int i = 4; i > 0; i--) { String open = StringUtils.repeat('[', i); String close = StringUtils.repeat(']', i); if (jsonString.startsWith(open)) { jsonString = jsonString.substring(open.length()); } if (jsonString.endsWith(close)) { jsonString = jsonString.substring(0, jsonString.length() - close.length()); } } if (jsonString.startsWith("{") && !jsonString.endsWith("}")) { jsonString += "}"; } StringBuilder fixedJson = new StringBuilder(); Deque<Character> bracketStack = new ArrayDeque<>(); char[] jsonChars = jsonString.toCharArray(); for (char jc : jsonChars) { JsonRepairer.handleOpenBrackets(jc, bracketStack); //Fix absent ] in array if (jc == ':' && bracketStack.peek() != null && bracketStack.peek() == '[') { String arrayContent = fixedJson.substring(fixedJson.lastIndexOf("[")); if (!arrayContent.contains("\":")) { int commaIndex = fixedJson.lastIndexOf(","); if (commaIndex > 0) { fixedJson.replace(commaIndex, commaIndex + 1, "],"); bracketStack.pop(); } } } fixedJson.append(jc); } JsonRepairer.appendRemainingClosingBrackets(fixedJson, bracketStack); //String fixed = fixDoubleQuotesAndCommas(fixedJson.toString()); String result = fixedJson.toString().trim(); String fixed = null; if (JsonUtils.isValidJSON(result)) { fixed = result; } else { String[] lines = result.split("\n"); int startIdx = -1; int endIdx = -1; for (int i = 0; i < lines.length; i++) { String line = lines[i].trim(); if (endIdx < 0 && line.startsWith("{")) { startIdx = i; } if (startIdx > 0 && line.endsWith("}")) { endIdx = i; } } if (startIdx > 0 && endIdx > 0) { String currentResult = Arrays.asList(lines).subList(startIdx, endIdx + 1).stream().collect(Collectors.joining("\n")); if (JsonUtils.isValidJSON(currentResult)) { fixed = currentResult; } } if (fixed == null) { fixed = extractJsonFromText(fixed); } } try { JsonNode jsonNode = mapperRelaxed.readTree(fixed); return mapper.writeValueAsString(jsonNode); } catch (Exception e) { log.error("[json-repair] Failed json repair input: [%s], output: [%s]".formatted(jsonString, fixed), e); throw e; } } public static String toJson(Object context) throws JsonProcessingException { return mapper.writeValueAsString(context); } public static <T> T fromJson(String str, Class<T> cls) throws JsonProcessingException { return mapper.readValue(str, cls); } /** * Safely parse JSON regardless of its format * @param json String containing potential JSON * @param cls Class to parse into * @return Parsed object or null if parsing fails */ public static <T> T safeParse(String json, Class<T> cls) { try { if (isJSON(json)) { String fixedJson = fixIncompleteJSON(json); return fromJson(fixedJson, cls); } } catch (Exception e) { log.error("Failed to parse JSON: {}", e.getMessage()); } return null; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/ModelUtils.java
package ai.driftkit.common.utils; import ai.driftkit.common.domain.client.ModelClient.Property; import ai.driftkit.common.domain.client.ModelClient.ResponseFormatType; import ai.driftkit.common.domain.client.ModelClient.Tool; import ai.driftkit.common.domain.client.ModelClient.ToolFunction; import ai.driftkit.common.domain.client.ModelClient.ToolFunction.FunctionParameters; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.HashMap; import java.util.List; import java.util.Map; public class ModelUtils { public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Description { String value(); } public static JsonNode parseJsonMessage(String message) throws JsonProcessingException { return OBJECT_MAPPER.readTree(message); } public static Tool parseFunction(Method method) { String functionName = method.getName(); Description descriptionAnnotation = method.getAnnotation(Description.class); String description = descriptionAnnotation != null ? descriptionAnnotation.value() : ""; ResponseFormatType returnType = mapJavaTypeToResponseFormatType(method.getReturnType()); Map<String, Property> properties = new HashMap<>(); List<String> required = new java.util.ArrayList<>(); Parameter[] parameters = method.getParameters(); for (Parameter parameter : parameters) { String parameterName = parameter.getName(); ResponseFormatType parameterType = mapJavaTypeToResponseFormatType(parameter.getType()); properties.put(parameterName, new Property(parameterType)); required.add(parameterName); } FunctionParameters functionParameters = new FunctionParameters( ResponseFormatType.Object, properties, required ); ToolFunction function = new ToolFunction(functionName, description, functionParameters); return new Tool(returnType, function); } private static ResponseFormatType mapJavaTypeToResponseFormatType(Class<?> type) { if (type == String.class) { return ResponseFormatType.String; } else if (type == int.class || type == Integer.class) { return ResponseFormatType.Integer; } else if (type == boolean.class || type == Boolean.class) { return ResponseFormatType.Boolean; } else if (type == double.class || type == Double.class || type == float.class || type == Float.class) { return ResponseFormatType.Number; } else if (type == List.class || type.isArray()) { return ResponseFormatType.Array; } else if (type == Map.class) { return ResponseFormatType.Object; } else { return ResponseFormatType.Object; } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/TextSimilarityUtil.java
package ai.driftkit.common.utils; import java.text.Normalizer; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; /** * Utility class for text similarity operations */ public class TextSimilarityUtil { private static final Pattern DIACRITICS_AND_FRIENDS = Pattern.compile("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+"); private static final Set<String> STOP_WORDS = new HashSet<>(Arrays.asList( "a", "an", "the", "and", "but", "or", "for", "nor", "on", "at", "to", "from", "by", "with", "in", "out", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "do", "does", "did", "will", "would", "shall", "should", "can", "could", "may", "might", "must", "of", "that", "which", "who", "whom", "whose", "this", "these", "those", "i", "you", "he", "she", "it", "we", "they", "their", "our", "your", "my", "his", "her", "its" )); /** * Normalize text for comparison: * - Convert to lowercase * - Remove diacritics (accents) * - Remove punctuation * - Remove extra whitespace * - Remove stop words * * @param text Input text to normalize * @return Normalized text */ public static String normalizeText(String text) { if (text == null || text.isEmpty()) { return ""; } // Convert to lowercase String result = text.toLowerCase(); // Remove diacritical marks (accents) result = Normalizer.normalize(result, Normalizer.Form.NFD); result = DIACRITICS_AND_FRIENDS.matcher(result).replaceAll(""); // Remove punctuation and replace with space result = result.replaceAll("[^\\p{Alnum}\\s]", " "); // Remove extra whitespace result = result.replaceAll("\\s+", " ").trim(); // Remove stop words StringBuilder sb = new StringBuilder(); for (String word : result.split("\\s+")) { if (!STOP_WORDS.contains(word)) { sb.append(word).append(" "); } } return sb.toString().trim(); } /** * Calculate Levenshtein distance between two strings * * @param s1 First string * @param s2 Second string * @return Levenshtein distance */ public static int levenshteinDistance(String s1, String s2) { int[][] dp = new int[s1.length() + 1][s2.length() + 1]; for (int i = 0; i <= s1.length(); i++) { for (int j = 0; j <= s2.length(); j++) { if (i == 0) { dp[i][j] = j; } else if (j == 0) { dp[i][j] = i; } else { dp[i][j] = Math.min( Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + (s1.charAt(i - 1) == s2.charAt(j - 1) ? 0 : 1) ); } } } return dp[s1.length()][s2.length()]; } /** * Calculate Jaccard similarity between two strings * (size of intersection divided by size of union) * * @param s1 First string * @param s2 Second string * @return Jaccard similarity index (0-1) */ public static double jaccardSimilarity(String s1, String s2) { if (s1 == null || s2 == null) { return 0.0; } // Get normalized strings and tokenize Set<String> set1 = new HashSet<>(Arrays.asList(s1.split("\\s+"))); Set<String> set2 = new HashSet<>(Arrays.asList(s2.split("\\s+"))); // Calculate intersection size Set<String> intersection = new HashSet<>(set1); intersection.retainAll(set2); // Calculate union size Set<String> union = new HashSet<>(set1); union.addAll(set2); // Calculate Jaccard index return union.isEmpty() ? 1.0 : (double) intersection.size() / union.size(); } /** * Calculate cosine similarity between two strings * * @param s1 First string * @param s2 Second string * @return Cosine similarity (-1 to 1) */ public static double cosineSimilarity(String s1, String s2) { if (s1 == null || s2 == null || s1.isEmpty() || s2.isEmpty()) { return 0.0; } // Simple implementation using word vectors String[] tokens1 = s1.split("\\s+"); String[] tokens2 = s2.split("\\s+"); Set<String> allTokens = new HashSet<>(); for (String token : tokens1) allTokens.add(token); for (String token : tokens2) allTokens.add(token); // Create vectors based on token frequencies int[] vector1 = new int[allTokens.size()]; int[] vector2 = new int[allTokens.size()]; int i = 0; for (String token : allTokens) { vector1[i] = countOccurrences(tokens1, token); vector2[i] = countOccurrences(tokens2, token); i++; } // Calculate cosine similarity return calculateCosineSimilarity(vector1, vector2); } private static int countOccurrences(String[] tokens, String token) { int count = 0; for (String t : tokens) { if (t.equals(token)) count++; } return count; } private static double calculateCosineSimilarity(int[] vectorA, int[] vectorB) { double dotProduct = 0.0; double normA = 0.0; double normB = 0.0; for (int i = 0; i < vectorA.length; i++) { dotProduct += vectorA[i] * vectorB[i]; normA += Math.pow(vectorA[i], 2); normB += Math.pow(vectorB[i], 2); } if (normA == 0 || normB == 0) return 0.0; return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)); } /** * Calculate similarity between two strings using a combined approach * * @param s1 First string * @param s2 Second string * @return Similarity score (0-1) */ public static double calculateSimilarity(String s1, String s2) { if (s1 == null || s2 == null) { return 0.0; } if (s1.equals(s2)) { return 1.0; } // Normalize if not already normalized String ns1 = s1.trim(); String ns2 = s2.trim(); // Calculate different similarity metrics double jaccardScore = jaccardSimilarity(ns1, ns2); double cosineScore = cosineSimilarity(ns1, ns2); // Calculate Levenshtein distance based similarity (1 - normalized distance) int maxLength = Math.max(ns1.length(), ns2.length()); double levenshteinScore = maxLength > 0 ? 1.0 - ((double) levenshteinDistance(ns1, ns2) / maxLength) : 1.0; // Combined score with different weights return 0.4 * jaccardScore + 0.4 * cosineScore + 0.2 * levenshteinScore; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/ValidationUtils.java
package ai.driftkit.common.utils; /** * ValidationUtils provides simple validation helper methods. */ public class ValidationUtils { /** * Ensures that the given object is not null. * * @param obj The object to check. * @param name The name of the parameter. * @param <T> The type of the object. * @return The object if it is not null. * @throws IllegalArgumentException if the object is null. */ public static <T> T ensureNotNull(T obj, String name) { if (obj == null) { throw new IllegalArgumentException(name + " cannot be null"); } return obj; } /** * Ensures that the given integer is greater than zero. * * @param value The integer value to check. * @param name The name of the parameter. * @return The value if it is greater than zero. * @throws IllegalArgumentException if the value is null or not greater than zero. */ public static Integer ensureGreaterThanZero(Integer value, String name) { if (value == null || value <= 0) { throw new IllegalArgumentException(name + " must be greater than zero"); } return value; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/common/utils/VariableExtractor.java
package ai.driftkit.common.utils; import lombok.extern.slf4j.Slf4j; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Extracts variables from a template that follows TemplateEngine syntax. * Handles regular variables, conditional blocks (if), and list iterations. */ @Slf4j public class VariableExtractor { // Pattern for all template tags private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{\\{(.*?)\\}\\}"); // Patterns for conditional and list control tags private static final Pattern IF_PATTERN = Pattern.compile("^\\s*if\\s+(.+)$"); private static final Pattern LIST_PATTERN = Pattern.compile("^\\s*list\\s+(.+?)\\s+as\\s+(.+?)\\s*$"); private static final Pattern END_TAG_PATTERN = Pattern.compile("^\\s*/(if|list)\\s*$"); /** * Extracts variable names from the template, filtering out control structures. * * @param template The template containing variables. * @return A set of variable names that would need values for the template. */ public Set<String> extractVariables(String template) { Set<String> variables = new HashSet<>(); Matcher matcher = VARIABLE_PATTERN.matcher(template); while (matcher.find()) { String tag = matcher.group(1).trim(); // Skip if/endif and list/endlist tags Matcher ifMatcher = IF_PATTERN.matcher(tag); Matcher listMatcher = LIST_PATTERN.matcher(tag); Matcher endTagMatcher = END_TAG_PATTERN.matcher(tag); if (endTagMatcher.matches()) { // Skip end tags like {{/if}} and {{/list}} continue; } else if (ifMatcher.matches()) { // Extract variables from if conditions String condition = ifMatcher.group(1).trim(); extractVariablesFromCondition(condition, variables); } else if (listMatcher.matches()) { // Extract the collection variable from list tags String collection = listMatcher.group(1).trim(); // We don't add the item variable as it's defined within the loop variables.add(collection); } else { // Regular variable, but make sure it's not a nested property access if (!tag.contains(".")) { variables.add(tag); } else { // Handle dot notation by extracting the root variable String rootVariable = tag.split("\\.")[0].trim(); variables.add(rootVariable); } } } log.debug("Extracted variables: {}", variables); return variables; } /** * Extracts variables from conditional expressions. * * @param condition The condition string from an if tag. * @param variables The set to add variables to. */ private void extractVariablesFromCondition(String condition, Set<String> variables) { // Handle OR conditions String[] orClauses = condition.split("\\|\\|"); for (String orClause : orClauses) { // Handle AND conditions String[] andClauses = orClause.split("&&"); for (String clause : andClauses) { clause = clause.trim(); if (clause.contains("==")) { // Extract variable from equality checks (var == value) String[] parts = clause.split("=="); if (parts.length >= 1) { String varName = parts[0].trim(); if (!varName.isEmpty() && !varName.matches("^\".*\"$")) { variables.add(varName); } } } else if (clause.contains(".size")) { // Extract variable from size checks (var.size > 0) String[] parts = clause.split("\\."); if (parts.length >= 1) { String varName = parts[0].trim(); if (!varName.isEmpty()) { variables.add(varName); } } } else if (!clause.matches("^\\d+$") && !clause.equals("true") && !clause.equals("false")) { // It's likely a variable name used as a boolean check variables.add(clause); } } } } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/config/EtlConfig.java
package ai.driftkit.config; import lombok.*; import org.apache.commons.lang3.StringUtils; import java.util.List; import java.util.Map; import java.util.Optional; @Data public class EtlConfig { public static final String DIMENSION = "dimension"; public static final String API_KEY = "apiKey"; public static final String MODEL_NAME = "modelName"; public static final String MODEL_PATH = "modelPath"; public static final String TOKENIZER_PATH = "tokenizerPath"; public static final String ENDPOINT = "endpoint"; public static final String HOST = "host"; public static final String BASE_QUERY = "baseQuery"; public static final String VECTOR_STORE_STORING_THREADS = "threadsVectorStore"; private VectorStoreConfig vectorStore; private EmbeddingServiceConfig embedding; private PromptServiceConfig promptService; private YoutubeProxyConfig youtubeProxy; private List<VaultConfig> vault; public Optional<VaultConfig> getModelConfig(String name) { return vault.stream().filter(e -> e.getName().equals(name)).findAny(); } @Data @NoArgsConstructor @AllArgsConstructor public static class YoutubeProxyConfig { String host; int port; String username; String password; } public static class VectorStoreConfig extends GenericConfig { @Builder public VectorStoreConfig(String name, Map<String, String> config) { super(name, config); } } public static class PromptServiceConfig extends GenericConfig { @Builder public PromptServiceConfig(String name, Map<String, String> config) { super(name, config); } } public static class EmbeddingServiceConfig extends GenericConfig { @Builder public EmbeddingServiceConfig(String name, Map<String, String> config) { super(name, config); } } @Data @NoArgsConstructor @AllArgsConstructor public static class GenericConfig { private String name; private Map<String, String> config; public String get(String name) { return config.get(name); } public String get(String name, String def) { return config.getOrDefault(name, def); } public Integer getInt(String name) { return getInt(name, null); } public Integer getInt(String name, Integer def) { String val = get(name); if (StringUtils.isBlank(val)) { return def; } return Integer.parseInt(val); } } @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class VaultConfig { private String apiKey; private String name; private String type; private String model; private String modelMini; private String imageModel; private String imageQuality; private String imageSize; private String baseUrl; private List<String> stop; private Integer maxTokens; private double temperature; private boolean jsonObject; private boolean tracing; } }
0
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/config
java-sources/ai/driftkit/driftkit-common/0.8.1/ai/driftkit/config/autoconfigure/EtlConfigAutoConfiguration.java
package ai.driftkit.config.autoconfigure; import ai.driftkit.config.EtlConfig; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; /** * Base auto-configuration for EtlConfig. * This configuration MUST load first before any other DriftKit configurations. * * EtlConfig is the foundation of the entire DriftKit framework and contains * all necessary configuration for various services. */ @Slf4j @AutoConfiguration public class EtlConfigAutoConfiguration { /** * Creates EtlConfig bean from application properties. * * This bean can be configured in application.yml/properties: * <pre> * driftkit: * promptService: * name: mongodb * config: * collection: prompts * vectorStore: * name: mongodb * config: * collection: vectors * embedding: * name: openai * config: * apiKey: ${OPENAI_API_KEY} * </pre> * * If no configuration is provided, creates a default EtlConfig with * file-based prompt service as a fallback. */ @Bean @ConditionalOnMissingBean @ConfigurationProperties(prefix = "driftkit") public EtlConfig etlConfig() { log.info("Creating EtlConfig bean from configuration properties"); EtlConfig config = new EtlConfig(); // If no prompt service is configured, log a warning if (config.getPromptService() == null) { log.warn("========================================"); log.warn("WARNING: No prompt service configuration found!"); log.warn("DriftKit services that depend on prompt service may not work properly."); log.warn("Please configure driftkit.promptService in your application properties."); log.warn("========================================"); } return config; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/registry/PromptServiceRegistry.java
package ai.driftkit.context.core.registry; import ai.driftkit.context.core.service.PromptService; import lombok.extern.slf4j.Slf4j; /** * Global registry for PromptService instances. * * This registry allows components (like LLMAgent) to automatically discover and use PromptService * when available in the system without requiring explicit configuration. * * Usage: * - Spring Boot applications should register PromptService via auto-configuration * - Manual applications can register via PromptServiceRegistry.register() * - Components automatically use registered instance if available */ @Slf4j public class PromptServiceRegistry { private static volatile PromptService globalInstance; private static final Object lock = new Object(); /** * Register a PromptService instance globally. * * @param promptService The PromptService instance to register */ public static void register(PromptService promptService) { synchronized (lock) { if (globalInstance != null && globalInstance != promptService) { log.warn("Replacing existing PromptService registration. " + "Previous: {}, New: {}", globalInstance.getClass().getSimpleName(), promptService.getClass().getSimpleName()); } globalInstance = promptService; log.debug("Registered PromptService: {}", promptService.getClass().getSimpleName()); } } /** * Get the globally registered PromptService instance. * * @return The registered PromptService, or null if none is registered */ public static PromptService getInstance() { return globalInstance; } /** * Check if a PromptService is registered. * * @return true if a PromptService is registered, false otherwise */ public static boolean isRegistered() { return globalInstance != null; } /** * Unregister the current PromptService instance. * This is mainly useful for testing scenarios. */ public static void unregister() { synchronized (lock) { if (globalInstance != null) { log.debug("Unregistered PromptService: {}", globalInstance.getClass().getSimpleName()); globalInstance = null; } } } /** * Get the registered PromptService or throw an exception if none is available. * * @return The registered PromptService * @throws IllegalStateException if no PromptService is registered */ public static PromptService getRequiredInstance() { PromptService instance = getInstance(); if (instance == null) { throw new IllegalStateException("No PromptService is registered. " + "Please ensure PromptService is available in your application context " + "or register one manually via PromptServiceRegistry.register()"); } return instance; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/DictionaryGroupRepository.java
package ai.driftkit.context.core.service; import ai.driftkit.common.domain.DictionaryGroup; import ai.driftkit.common.domain.Language; import java.util.List; import java.util.Optional; /** * Repository interface for custom queries on dictionary groups. * This interface contains only custom query methods, not CRUD operations. * CRUD operations are handled by the DictionaryGroupService layer. */ public interface DictionaryGroupRepository<T extends DictionaryGroup> { /** * Finds dictionary groups by language * * @param language the language to filter by * @return a list of dictionary groups matching the language */ List<T> findDictionaryGroupsByLanguage(Language language); }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/DictionaryGroupService.java
package ai.driftkit.context.core.service; import ai.driftkit.common.domain.DictionaryGroup; import ai.driftkit.common.domain.Language; import java.util.List; import java.util.Optional; /** * Service interface for managing dictionary groups. * This interface defines business operations for dictionary groups, * independent of the underlying storage implementation. */ public interface DictionaryGroupService { /** * Finds a dictionary group by its ID * * @param id the ID of the dictionary group * @return an Optional containing the dictionary group if found, empty otherwise */ Optional<DictionaryGroup> findById(String id); /** * Finds dictionary groups by language * * @param language the language to filter by * @return a list of dictionary groups matching the language */ List<DictionaryGroup> findByLanguage(Language language); /** * Saves a dictionary group * * @param group the dictionary group to save * @return the saved dictionary group */ DictionaryGroup save(DictionaryGroup group); /** * Saves multiple dictionary groups * * @param groups the dictionary groups to save * @return the saved dictionary groups */ List<DictionaryGroup> saveAll(List<DictionaryGroup> groups); /** * Deletes a dictionary group by ID * * @param id the ID of the dictionary group to delete */ void deleteById(String id); /** * Checks if a dictionary group exists by ID * * @param id the ID to check * @return true if the group exists, false otherwise */ boolean existsById(String id); /** * Finds all dictionary groups * * @return a list of all dictionary groups */ List<DictionaryGroup> findAll(); }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/DictionaryItemRepository.java
package ai.driftkit.context.core.service; import ai.driftkit.common.domain.Language; import ai.driftkit.common.domain.DictionaryItem; import java.util.List; /** * Repository interface for custom queries on dictionary items. * This interface contains only custom query methods, not CRUD operations. * CRUD operations are handled by the DictionaryItemService layer. */ public interface DictionaryItemRepository<T extends DictionaryItem> { /** * Finds dictionary items by language * * @param language the language to filter by * @return a list of dictionary items matching the language */ List<T> findDictionaryItemsByLanguage(Language language); /** * Finds dictionary items by group ID * * @param groupId the group ID to filter by * @return a list of dictionary items belonging to the specified group */ List<T> findDictionaryItemsByGroupId(String groupId); }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/DictionaryItemService.java
package ai.driftkit.context.core.service; import ai.driftkit.common.domain.DictionaryItem; import ai.driftkit.common.domain.Language; import java.util.List; import java.util.Optional; /** * Service interface for managing dictionary items. * This interface defines business operations for dictionary items, * independent of the underlying storage implementation. */ public interface DictionaryItemService { /** * Finds a dictionary item by its ID * * @param id the ID of the dictionary item * @return an Optional containing the dictionary item if found, empty otherwise */ Optional<DictionaryItem> findById(String id); /** * Finds dictionary items by language * * @param language the language to filter by * @return a list of dictionary items matching the language */ List<DictionaryItem> findByLanguage(Language language); /** * Finds dictionary items by group ID * * @param groupId the group ID to filter by * @return a list of dictionary items belonging to the specified group */ List<DictionaryItem> findByGroupId(String groupId); /** * Saves a dictionary item * * @param item the dictionary item to save * @return the saved dictionary item */ DictionaryItem save(DictionaryItem item); /** * Saves multiple dictionary items * * @param items the dictionary items to save * @return the saved dictionary items */ List<DictionaryItem> saveAll(List<DictionaryItem> items); /** * Deletes a dictionary item by ID * * @param id the ID of the dictionary item to delete */ void deleteById(String id); /** * Checks if a dictionary item exists by ID * * @param id the ID to check * @return true if the item exists, false otherwise */ boolean existsById(String id); /** * Finds all dictionary items * * @return a list of all dictionary items */ List<DictionaryItem> findAll(); }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/FileSystemPromptService.java
package ai.driftkit.context.core.service; import ai.driftkit.common.domain.Prompt; import ai.driftkit.common.domain.Prompt.State; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.SneakyThrows; import java.io.File; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class FileSystemPromptService implements PromptServiceBase { private final Map<String, Prompt> promptsById = new HashMap<>(); private final Map<String, List<Prompt>> promptsByMethod = new HashMap<>(); private final ObjectMapper objectMapper = new ObjectMapper(); private File promptsFile; public FileSystemPromptService() throws IOException { } @SneakyThrows @Override public void configure(Map<String, String> config) { this.promptsFile = new File(config.get("promptsFilePath")); loadPrompts(); } @Override public boolean supportsName(String name) { return "filesystem".equals(name); } private void loadPrompts() throws IOException { if (promptsFile.exists()) { List<Prompt> prompts = objectMapper.readValue(promptsFile, new TypeReference<List<Prompt>>() {}); for (Prompt prompt : prompts) { promptsById.put(prompt.getId(), prompt); promptsByMethod.computeIfAbsent(prompt.getMethod(), k -> new ArrayList<>()).add(prompt); } } } private void savePrompts() throws IOException { List<Prompt> prompts = new ArrayList<>(promptsById.values()); objectMapper.writerWithDefaultPrettyPrinter().writeValue(promptsFile, prompts); } @Override public synchronized Prompt savePrompt(Prompt prompt) { if (prompt.getId() == null) { prompt.setId(UUID.randomUUID().toString()); prompt.setCreatedTime(System.currentTimeMillis()); } prompt.setUpdatedTime(System.currentTimeMillis()); promptsById.put(prompt.getId(), prompt); promptsByMethod.computeIfAbsent(prompt.getMethod(), k -> new ArrayList<>()).add(prompt); try { savePrompts(); } catch (IOException e) { throw new RuntimeException("Failed to save prompts to file system", e); } return prompt; } @SneakyThrows @Override public Prompt deletePrompt(String id) { Prompt removed = promptsById.remove(id); List<Prompt> prompts = promptsByMethod.get(removed.getMethod()); for (Iterator<Prompt> it = prompts.iterator(); it.hasNext(); ) { Prompt prompt = it.next(); if (id.equals(prompt.getId())) { it.remove(); } } savePrompts(); return removed; } @Override public Optional<Prompt> getPromptById(String id) { return Optional.ofNullable(promptsById.get(id)); } @Override public List<Prompt> getPromptsByIds(List<String> ids) { return ids.stream() .map(promptsById::get) .filter(Objects::nonNull) .collect(Collectors.toList()); } @Override public List<Prompt> getPromptsByMethods(List<String> methods) { return methods.stream() .flatMap(method -> promptsByMethod.getOrDefault(method, Collections.emptyList()).stream()) .collect(Collectors.toList()); } @Override public List<Prompt> getPromptsByMethodsAndState(List<String> methods, State state) { return getPromptsByMethods(methods).stream() .filter(prompt -> prompt.getState() == state) .collect(Collectors.toList()); } @Override public List<Prompt> getPrompts() { return new ArrayList<>(promptsById.values()); } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/InMemoryPromptService.java
package ai.driftkit.context.core.service; import ai.driftkit.common.domain.Prompt; import ai.driftkit.common.domain.Prompt.State; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; public class InMemoryPromptService implements PromptServiceBase { private final Map<String, Prompt> promptsById = new ConcurrentHashMap<>(); private final Map<String, List<Prompt>> promptsByMethod = new ConcurrentHashMap<>(); @Override public void configure(Map<String, String> config) { } @Override public boolean supportsName(String name) { return "in-memory".equals(name); } @Override public Optional<Prompt> getPromptById(String id) { return Optional.ofNullable(promptsById.get(id)); } @Override public List<Prompt> getPromptsByIds(List<String> ids) { return ids.stream() .map(promptsById::get) .filter(Objects::nonNull) .collect(Collectors.toList()); } @Override public List<Prompt> getPromptsByMethods(List<String> methods) { return methods.stream() .flatMap(method -> promptsByMethod.getOrDefault(method, Collections.emptyList()).stream()) .collect(Collectors.toList()); } @Override public List<Prompt> getPromptsByMethodsAndState(List<String> methods, State state) { return getPromptsByMethods(methods).stream() .filter(prompt -> prompt.getState() == state) .collect(Collectors.toList()); } @Override public List<Prompt> getPrompts() { return new ArrayList<>(promptsById.values()); } @Override public synchronized Prompt savePrompt(Prompt prompt) { if (prompt.getId() == null) { prompt.setId(UUID.randomUUID().toString()); prompt.setCreatedTime(System.currentTimeMillis()); } prompt.setUpdatedTime(System.currentTimeMillis()); promptsById.put(prompt.getId(), prompt); promptsByMethod.computeIfAbsent(prompt.getMethod(), k -> new ArrayList<>()).add(prompt); return prompt; } @Override public Prompt deletePrompt(String id) { Prompt removed = promptsById.remove(id); List<Prompt> prompts = promptsByMethod.get(removed.getMethod()); for (Iterator<Prompt> it = prompts.iterator(); it.hasNext(); ) { Prompt prompt = it.next(); if (id.equals(prompt.getId())) { it.remove(); } } return removed; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/PromptService.java
package ai.driftkit.context.core.service; import ai.driftkit.common.domain.*; import ai.driftkit.common.domain.PromptRequest.PromptIdRequest; import ai.driftkit.common.domain.client.ResponseFormat; import ai.driftkit.common.utils.AIUtils; import ai.driftkit.context.core.registry.PromptServiceRegistry; import ai.driftkit.common.domain.Prompt.ResolveStrategy; import ai.driftkit.common.domain.Prompt.State; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.stream.Collectors; @Slf4j public class PromptService implements PromptServiceBase { public static final String DEFAULT_STARTING_PROMPT = "default_starting_prompt"; public static final String PREFIX_DICT = "dict"; public static final String PREFIX_INDEX = "index:"; protected PromptServiceBase promptService; private DictionaryItemService dictionaryItemService; // Queue to hold prompts when the repository isn't initialized private final Queue<PromptInitializationTask> promptInitializationQueue = new ConcurrentLinkedQueue<>(); // Flag to indicate whether the service has been initialized private volatile boolean serviceInitialized; public PromptService(PromptServiceBase promptService, DictionaryItemService dictionaryItemService) { this.promptService = promptService; this.dictionaryItemService = dictionaryItemService; this.serviceInitialized = true; processQueuedPrompts(); PromptServiceRegistry.register(this); } @Override public void configure(Map<String, String> config) { } public Prompt createIfNotExists(String method, String prompt, String systemMessage, boolean jsonResponse) { return createIfNotExists(method, prompt, systemMessage, jsonResponse, Language.GENERAL, false); } public Prompt createIfNotExists(String method, String prompt, String systemMessage, boolean jsonResponse, Language language) { return createIfNotExists(method, prompt, systemMessage, jsonResponse, language, false, null); } public Prompt createIfNotExists(String method, String prompt, String systemMessage, boolean jsonResponse, Language language, String workflow) { return createIfNotExists(method, prompt, systemMessage, jsonResponse, language, false, workflow); } public Prompt createIfNotExists(String method, String prompt, String systemMessage, boolean jsonResponse, Language language, boolean forceRepoVersion) { return createIfNotExists(method, prompt, systemMessage, jsonResponse, language, forceRepoVersion, null); } public Prompt createIfNotExists(String method, String prompt, String systemMessage, boolean jsonResponse, Language language, boolean forceRepoVersion, String workflow) { method = method.replace(".prompt", ""); // If the service isn't initialized, queue the prompt for later processing if (!serviceInitialized || !promptService.isConfigured()) { promptInitializationQueue.add(new PromptInitializationTask(method, prompt, systemMessage, jsonResponse, forceRepoVersion, workflow)); return null; } List<Prompt> promptOpt = getPromptsByMethods(List.of(method)); if (CollectionUtils.isNotEmpty(promptOpt)) { Optional<Prompt> langFound = promptOpt.stream().filter(e -> e.getLanguage() == language).findAny(); if (langFound.isPresent()) { if (!forceRepoVersion || langFound.get().getMessage().equals(prompt)) { // If workflow is provided and different from the existing one, update it // if (workflow != null && !workflow.equals(langFound.get().getWorkflow())) { // Prompt updated = langFound.get(); // updated.setWorkflow(workflow); // return savePrompt(updated); // } return langFound.get(); } } } Prompt toSave = new Prompt( UUID.randomUUID().toString(), method, prompt, systemMessage, State.CURRENT, null, ResolveStrategy.LAST_VERSION, workflow, language, null, false, jsonResponse, null, // responseFormat System.currentTimeMillis(), System.currentTimeMillis(), System.currentTimeMillis() ); savePrompt(toSave); return toSave; } private void processQueuedPrompts() { PromptInitializationTask task; while ((task = promptInitializationQueue.poll()) != null) { // Process each queued prompt createIfNotExists(task.method, task.prompt, task.systemMessage, task.jsonResponse, Language.GENERAL, task.forceRepoVersion, task.workflow); } } @Override public boolean supportsName(String name) { return this.promptService.supportsName(name); } @Override public Optional<Prompt> getPromptById(String id) { return this.promptService.getPromptById(id); } @Override public List<Prompt> getPromptsByIds(List<String> ids) { return this.promptService.getPromptsByIds(ids); } @Override public List<Prompt> getPromptsByMethods(List<String> methods) { return this.promptService.getPromptsByMethods(methods); } @Override public List<Prompt> getPromptsByMethodsAndState(List<String> methods, State state) { return this.promptService.getPromptsByMethodsAndState(methods, state); } @Override public List<Prompt> getPrompts() { return this.promptService.getPrompts(); } @Override public Prompt savePrompt(Prompt prompt) { return this.promptService.savePrompt(prompt); } @Override public Prompt deletePrompt(String id) { return this.promptService.deletePrompt(id); } public MessageTask getTaskFromPromptRequest(PromptRequest request) { Map<String, PromptIdRequest> ids2req = request.getPromptIds() .stream() .collect(Collectors.toMap(PromptIdRequest::getPromptId, e -> e)); // Check that each PromptIdRequest has the required parameters for (PromptIdRequest promptIdRequest : request.getPromptIds()) { if (StringUtils.isBlank(promptIdRequest.getPromptId())) { throw new IllegalArgumentException("promptId cannot be null or empty in PromptIdRequest"); } } List<Prompt> prompts = getCurrentPromptsForMethodStateAndLanguage( new ArrayList<>(ids2req.keySet()), request.getLanguage() ); Double temperature = null; if (request.isSavePrompt() || prompts.isEmpty()) { prompts = new ArrayList<>(); for (String method : ids2req.keySet()) { List<Prompt> generalPrompts = getPromptsByMethodsAndState( List.of(method), State.CURRENT ); Optional<Prompt> generalPrompt = generalPrompts.stream().filter(e -> e.getLanguage() == Language.GENERAL).findAny(); if (generalPrompt.isEmpty()) { generalPrompt = Optional.ofNullable(generalPrompts.isEmpty() ? null : generalPrompts.getFirst()); } Prompt prompt; PromptIdRequest promptIdRequest = ids2req.get(method); if (generalPrompt.isPresent()) { // Use existing prompt as template prompt = generalPrompt.get(); prompt.setLanguage(request.getLanguage()); } else { // Create a new prompt if no existing one is found // Check that the request contains prompt text if (StringUtils.isBlank(promptIdRequest.getPrompt())) { throw new IllegalArgumentException("Prompt text is required when creating a new prompt for method: " + method); } log.info("Creating new prompt for method: {}, language: {}", method, request.getLanguage()); prompt = new Prompt( UUID.randomUUID().toString(), method, promptIdRequest.getPrompt(), null, // systemMessage State.CURRENT, request.getWorkflow(), ResolveStrategy.LAST_VERSION, null, request.getLanguage(), promptIdRequest.getTemperature(), false, false, // jsonResponse - can be parameterized in the future null, // responseFormat System.currentTimeMillis(), System.currentTimeMillis(), System.currentTimeMillis() ); } // If the request contains prompt text, update the existing prompt if (StringUtils.isNotBlank(promptIdRequest.getPrompt())) { prompt.setMessage(promptIdRequest.getPrompt()); } savePrompt(prompt); prompts.add(prompt); } } StringBuilder systemMessageBuilder = new StringBuilder(); StringBuilder messageBuilder = new StringBuilder(); String workflow = request.getWorkflow(); boolean skipWorkflow = "skip".equals(workflow); // If request explicitly sets jsonResponse, use that; otherwise default to false boolean jsonResponse = request.getJsonResponse() != null ? request.getJsonResponse() : false; ResponseFormat responseFormat = request.getResponseFormat(); for (Prompt prompt : prompts) { PromptIdRequest promptId = ids2req.get(prompt.getMethod()); if (temperature == null) { temperature = Optional.ofNullable(promptId.getTemperature()).orElse(prompt.getTemperature()); } // Only override jsonResponse from prompt if not explicitly set in request if (request.getJsonResponse() == null) { jsonResponse = jsonResponse || prompt.isJsonResponse(); } // Override responseFormat from prompt if not already set in request if (responseFormat == null && prompt.getResponseFormat() != null) { responseFormat = prompt.getResponseFormat(); } if (!skipWorkflow && workflow == null && prompt.getWorkflow() != null) { workflow = prompt.getWorkflow(); } messageBuilder.append(prompt.getMessage()).append(" "); if (prompt.getSystemMessage() != null) { systemMessageBuilder.append(prompt.getSystemMessage()).append(' '); } // Always save the prompt if the text is provided, regardless of the savePrompt flag if (StringUtils.isNotBlank(promptId.getPrompt())) { prompt.setLanguage(request.getLanguage()); prompt.setWorkflow(request.getWorkflow()); prompt.setMessage(promptId.getPrompt()); savePrompt(prompt); } else if (!request.isSavePrompt()) { // If no prompt text and savePrompt flag is not set, skip this prompt continue; } } if (skipWorkflow) { workflow = null; } String message = messageBuilder.toString(); Map<String, Object> variables = request.getVariables() == null ? new HashMap<>() : request.getVariables(); Map<String, String> specialVariables = variables.entrySet().stream() .filter(e -> e.getValue() instanceof String str && (str.startsWith(PREFIX_DICT) || str.startsWith(PREFIX_INDEX))) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString())); if (!specialVariables.isEmpty()) { for (Entry<String, String> name2value : specialVariables.entrySet()) { String key = name2value.getKey(); String value = name2value.getValue(); if (value.startsWith(PREFIX_DICT)) { putDictValues(name2value, value); } else if (value.startsWith(PREFIX_INDEX)) { name2value.setValue(""); } } // Combine all variables variables.putAll(specialVariables); } return MessageTask.builder() .messageId(AIUtils.generateId()) .message(message) .modelId(request.getModelId()) .language(request.getLanguage()) .promptIds(prompts.stream().map(Prompt::getId).toList()) .chatId(request.getChatId()) .workflow(workflow) .temperature(temperature) .jsonResponse(jsonResponse) .responseFormat(responseFormat) .systemMessage(systemMessageBuilder.isEmpty() ? null : systemMessageBuilder.toString()) .variables(variables) .logprobs(request.getLogprobs()) .topLogprobs(request.getTopLogprobs()) .purpose(request.getPurpose()) .imageBase64(request.getImageBase64()) .imageMimeType(request.getImageMimeType()) .createdTime(System.currentTimeMillis()) .build(); } private void putDictValues(Entry<String, String> name2value, String value) { String dictionaryId = value.substring(3); boolean samples = dictionaryId.contains("-samples:"); boolean markers = dictionaryId.contains("-markers:"); Optional<DictionaryItem> itemOpt = dictionaryItemService.findById(dictionaryId.split(":")[1]); if (itemOpt.isEmpty()) { log.warn("[prompt-processor] Dictionary item is not found for id [%s]".formatted(dictionaryId)); name2value.setValue(""); return; } DictionaryItem item = itemOpt.get(); if (samples) { if (CollectionUtils.isNotEmpty(item.getSamples())) { name2value.setValue(String.join(",", item.getSamples())); } } else if (markers) { if (CollectionUtils.isNotEmpty(item.getMarkers())) { name2value.setValue(String.join(",", item.getMarkers())); } } else { name2value.setValue(""); } } private static class PromptInitializationTask { String method; String prompt; String systemMessage; boolean jsonResponse; boolean forceRepoVersion; String workflow; public PromptInitializationTask(String method, String prompt, String systemMessage, boolean jsonResponse, boolean forceRepoVersion) { this(method, prompt, systemMessage, jsonResponse, forceRepoVersion, null); } public PromptInitializationTask(String method, String prompt, String systemMessage, boolean jsonResponse, boolean forceRepoVersion, String workflow) { this.method = method; this.prompt = prompt; this.systemMessage = systemMessage; this.jsonResponse = jsonResponse; this.forceRepoVersion = forceRepoVersion; this.workflow = workflow; } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/PromptServiceBase.java
package ai.driftkit.context.core.service; import ai.driftkit.common.domain.Language; import ai.driftkit.common.domain.Prompt; import ai.driftkit.common.domain.Prompt.State; import java.util.*; import java.util.stream.Collectors; public interface PromptServiceBase { void configure(Map<String, String> config); boolean supportsName(String name); Optional<Prompt> getPromptById(String id); List<Prompt> getPromptsByIds(List<String> ids); List<Prompt> getPromptsByMethods(List<String> methods); List<Prompt> getPromptsByMethodsAndState(List<String> methods, State state); List<Prompt> getPrompts(); Prompt savePrompt(Prompt prompt); Prompt deletePrompt(String id); default Prompt getCurrentPromptOrThrow(String method) { return getCurrentPromptOrThrow(method, Language.GENERAL); } default Prompt getCurrentPromptOrThrow(String method, Language language) { List<Prompt> prompts = getCurrentPromptsForMethodStateAndLanguage(List.of(method), language); if (prompts.isEmpty()) { throw new RuntimeException("Prompt is not found for methods [%s] and language [%s]".formatted(method, language)); } if (prompts.size() > 1) { throw new RuntimeException("Too many current prompts [%s] found for methods [%s] and language [%s]".formatted(prompts.size(), method, language)); } return prompts.getFirst(); } default Optional<Prompt> getCurrentPrompt(String method, Language language) { List<Prompt> prompts = getCurrentPromptsForMethodStateAndLanguage(List.of(method), language); if (prompts.isEmpty()) { return Optional.empty(); } if (prompts.size() > 1) { throw new RuntimeException("Too many current prompts [%s] found for methods [%s] and language [%s]".formatted(prompts.size(), method, language)); } return Optional.ofNullable(prompts.getFirst()); } default List<Prompt> getCurrentPromptsForMethodStateAndLanguage(List<String> methods, Language language) { List<Prompt> prompts = getPromptsByMethodsAndState( methods, State.CURRENT ); if (prompts.isEmpty()) { return Collections.emptyList(); } Map<String, List<Prompt>> methodToPrompts = prompts.stream().collect(Collectors.groupingBy(Prompt::getMethod)); return methodToPrompts.values().stream().map(e -> { if (e.size() == 1) { Language lang = e.getFirst().getLanguage(); if (lang == Language.GENERAL || lang.name().equalsIgnoreCase(language.name())) { return e.getFirst(); } return null; } else { Optional<Prompt> promptForRequestLanguage = e.stream().filter(k -> k.getLanguage().name().equalsIgnoreCase(language.name())).findAny(); return promptForRequestLanguage.orElseGet( () -> e.stream().filter(k -> k.getLanguage() == Language.GENERAL).findAny() .orElse(null) ); } }).filter(Objects::nonNull).collect(Collectors.toList()); } default boolean isConfigured() { return true; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/PromptServiceFactory.java
package ai.driftkit.context.core.service; import org.apache.commons.lang3.StringUtils; import java.util.Map; import java.util.ServiceLoader; public class PromptServiceFactory { public static PromptServiceBase fromName(String name, Map<String, String> config) throws Exception { if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("Name must not be null"); } ServiceLoader<PromptServiceBase> loader = ServiceLoader.load(PromptServiceBase.class); for (PromptServiceBase store : loader) { if (store.supportsName(name)) { store.configure(config); return store; } } throw new IllegalArgumentException("Unknown or unavailable prompt service: " + name); } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/service/TemplateEngine.java
package ai.driftkit.context.core.service; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class TemplateEngine { // Precompiled regex pattern for variable tags (control tags are parsed manually). private static final Pattern VAR_PATTERN = Pattern.compile("\\{\\{([^\\}]+)\\}\\}"); // Cache for parsed templates (AST) keyed by the original template string. private static final ConcurrentHashMap<String, Template> templateCache = new ConcurrentHashMap<>(); // Reflection cache: key format "ClassName.fieldName" private static final ConcurrentHashMap<String, Field> reflectionCache = new ConcurrentHashMap<>(); public static void clear() { templateCache.clear(); reflectionCache.clear(); } // **************** AST Node Definitions **************** interface TemplateNode { String render(Map<String, Object> variables); boolean isStatic(); } // Represents literal text. static class TextNode implements TemplateNode { private final String text; public TextNode(String text) { this.text = text; } @Override public String render(Map<String, Object> variables) { return text; } @Override public boolean isStatic() { return true; } } // Represents a variable substitution (e.g., {{variable}} or {{object.field}}). static class VariableNode implements TemplateNode { private final String key; public VariableNode(String key) { this.key = key; } @Override public String render(Map<String, Object> variables) { Object value = resolveValue(key, variables); return value != null ? value.toString() : ""; } @Override public boolean isStatic() { return false; } } // Represents an if-block. static class IfNode implements TemplateNode { private final String condition; private final List<TemplateNode> children; // For memoization if the block is static. private String memoized; public IfNode(String condition, List<TemplateNode> children) { this.condition = condition; this.children = children; this.memoized = null; } @Override public String render(Map<String, Object> variables) { if (isStatic() && memoized != null) { return memoized; } boolean result = evaluateCondition(condition, variables); StringBuilder sb = new StringBuilder(); if (result) { for (TemplateNode child : children) { sb.append(child.render(variables)); } } String output = sb.toString(); if (isStatic()) { memoized = output; } return output; } @Override public boolean isStatic() { boolean condStatic = !condition.matches(".*[a-zA-Z].*") || condition.trim().equalsIgnoreCase("true") || condition.trim().equalsIgnoreCase("false"); for (TemplateNode node : children) { if (!node.isStatic()) { return false; } } return condStatic; } } // Represents a list block. static class ListNode implements TemplateNode { private final String collectionKey; private final String itemName; private final List<TemplateNode> children; public ListNode(String collectionKey, String itemName, List<TemplateNode> children) { this.collectionKey = collectionKey; this.itemName = itemName; this.children = children; } @Override public String render(Map<String, Object> variables) { StringBuilder sb = new StringBuilder(); Object collectionObj = variables.get(collectionKey); Iterable<?> iterable = toIterable(collectionObj); if (iterable != null) { for (Object item : iterable) { Map<String, Object> tempVars = new HashMap<>(variables); tempVars.put(itemName, item); for (TemplateNode child : children) { sb.append(child.render(tempVars)); } } } return sb.toString(); } @Override public boolean isStatic() { return false; } } // Template holds the parsed AST nodes. static class Template { private final List<TemplateNode> nodes; public Template(List<TemplateNode> nodes) { this.nodes = nodes; } public String render(Map<String, Object> variables) { StringBuilder sb = new StringBuilder(); for (TemplateNode node : nodes) { sb.append(node.render(variables)); } return sb.toString(); } } // **************** Template Parsing (AST Generation) **************** // Public method to render a template string with variables using caching. public static String renderTemplate(String template, Map<String, Object> variables) { Template parsedTemplate = templateCache.get(template); if (parsedTemplate == null) { parsedTemplate = parseTemplate(template); templateCache.put(template, parsedTemplate); } return parsedTemplate.render(variables); } // Parse the template into an AST. private static Template parseTemplate(String template) { ParseResult result = parseNodes(template, 0, null); return new Template(result.nodes); } // Parsing result: list of nodes and the next index. private static class ParseResult { List<TemplateNode> nodes; int nextIndex; ParseResult(List<TemplateNode> nodes, int nextIndex) { this.nodes = nodes; this.nextIndex = nextIndex; } } // Recursively parse nodes until an optional endTag is encountered. private static ParseResult parseNodes(String template, int start, String endTag) { List<TemplateNode> nodes = new ArrayList<>(); int index = start; while (index < template.length()) { int open = template.indexOf("{{", index); if (open < 0) { nodes.add(new TextNode(template.substring(index))); index = template.length(); break; } if (open > index) { nodes.add(new TextNode(template.substring(index, open))); } int close = template.indexOf("}}", open); if (close < 0) { nodes.add(new TextNode(template.substring(open))); index = template.length(); break; } String tagContent = template.substring(open + 2, close).trim(); index = close + 2; if (tagContent.startsWith("if ") || tagContent.startsWith("#if ")) { String condition = tagContent.startsWith("#if ") ? tagContent.substring(4).trim() : tagContent.substring(3).trim(); ParseResult inner = parseNodes(template, index, "/if"); nodes.add(new IfNode(condition, inner.nodes)); index = inner.nextIndex; } else if (tagContent.equals("/if") || tagContent.equals("#/if")) { if (endTag != null && endTag.equals("/if")) { return new ParseResult(nodes, index); } // Don't add the end tag as a text node, it should never be in the output // Just ignore it - it's likely a mismatched close tag } else if (tagContent.startsWith("list ") || tagContent.startsWith("#list ")) { String listContent = tagContent.startsWith("#list ") ? tagContent.substring(6) : tagContent.substring(5); String[] parts = listContent.split("\\s+as\\s+"); if (parts.length != 2) { nodes.add(new TextNode("{{" + tagContent + "}}")); } else { String collectionKey = parts[0].trim(); String itemName = parts[1].trim(); ParseResult inner = parseNodes(template, index, "/list"); nodes.add(new ListNode(collectionKey, itemName, inner.nodes)); index = inner.nextIndex; } } else if (tagContent.equals("/list") || tagContent.equals("#/list")) { if (endTag != null && endTag.equals("/list")) { return new ParseResult(nodes, index); } // Don't add the end tag as a text node, it should never be in the output // Just ignore it - it's likely a mismatched close tag } else { nodes.add(new VariableNode(tagContent)); } } return new ParseResult(nodes, index); } // **************** Utility Methods **************** // Resolve dot notation keys (e.g., "user.name") from variables (supports maps and one-level POJOs). public static Object resolveValue(String key, Map<String, Object> variables) { String[] parts = key.split("\\."); Object current = variables.get(parts[0]); for (int i = 1; i < parts.length; i++) { if (current == null) return null; if (current instanceof Map) { current = ((Map<?, ?>) current).get(parts[i]); } else { String cacheKey = current.getClass().getName() + "." + parts[i]; Field field = reflectionCache.get(cacheKey); if (field == null) { try { field = getFieldFromClass(current.getClass(), parts[i]); field.setAccessible(true); reflectionCache.put(cacheKey, field); } catch (Exception e) { return null; } } try { current = field.get(current); } catch (IllegalAccessException e) { return null; } } } return current; } private static Field getFieldFromClass(Class<?> clazz, String fieldName) { while (clazz != null) { try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } return null; } // Evaluate conditions supporting both "&&" and "||". public static boolean evaluateCondition(String condition, Map<String, Object> variables) { String[] orClauses = condition.split("\\|\\|"); for (String orClause : orClauses) { orClause = orClause.trim(); String[] andClauses = orClause.split("&&"); boolean allAndTrue = true; for (String clause : andClauses) { clause = clause.trim(); if (clause.contains(".size")) { String[] parts = clause.split("\\."); if (parts.length < 2) { allAndTrue = false; break; } String varName = parts[0].trim(); String rest = parts[1].trim(); // e.g., "size > 0" Object obj = variables.get(varName); int size = getSize(obj); Pattern p = Pattern.compile("size\\s*(>|>=|<|<=|==)\\s*(\\d+)"); Matcher m = p.matcher(rest); if (m.find()) { String operator = m.group(1); int number = Integer.parseInt(m.group(2)); if (!compare(size, operator, number)) { allAndTrue = false; break; } } else { allAndTrue = false; break; } } else if (clause.contains("==")) { String[] parts = clause.split("=="); if (parts.length != 2) { allAndTrue = false; break; } String varName = parts[0].trim(); // Handle both normal and escaped quotes String expectedValue = parts[1].trim() .replaceAll("^\"|\"$", "") // Remove surrounding quotes if present .replaceAll("\\\\\"", "\""); // Replace escaped quotes with actual quotes Object actual = variables.get(varName); if (actual == null || !actual.toString().equals(expectedValue)) { allAndTrue = false; break; } } else { Object value = variables.get(clause); if (!isTruthy(value)) { allAndTrue = false; break; } } } if (allAndTrue) { return true; } } return false; } // Check if an object is "truthy". public static boolean isTruthy(Object value) { if (value == null) return false; if (value instanceof Boolean) return (Boolean) value; if (value instanceof Collection) return !((Collection<?>) value).isEmpty(); if (value instanceof Map) return !((Map<?, ?>) value).isEmpty(); if (value.getClass().isArray()) return Array.getLength(value) > 0; if (value instanceof String) return !((String) value).trim().isEmpty(); return true; } // Get the size of an object (Collection, array, or Map). public static int getSize(Object value) { if (value == null) return 0; if (value instanceof Collection) return ((Collection<?>) value).size(); if (value instanceof Map) return ((Map<?, ?>) value).size(); if (value.getClass().isArray()) return Array.getLength(value); return 0; } // Compare two integers using the given operator. public static boolean compare(int a, String operator, int b) { switch (operator) { case ">": return a > b; case ">=": return a >= b; case "<": return a < b; case "<=": return a <= b; case "==": return a == b; default: return false; } } // Convert an object to an Iterable (supports Collections and arrays). public static Iterable<?> toIterable(Object obj) { if (obj == null) return null; if (obj instanceof Iterable) return (Iterable<?>) obj; if (obj.getClass().isArray()) { int length = Array.getLength(obj); List<Object> list = new ArrayList<>(length); for (int i = 0; i < length; i++) { list.add(Array.get(obj, i)); } return list; } return null; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/util/DefaultPromptLoader.java
package ai.driftkit.context.core.util; import ai.driftkit.common.domain.Language; import ai.driftkit.common.domain.Prompt; import ai.driftkit.context.core.registry.PromptServiceRegistry; import ai.driftkit.context.core.service.PromptService; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Utility class to load default prompts from resources and register them with PromptService. */ @Slf4j public class DefaultPromptLoader { private static final String PROMPTS_RESOURCE_PATH = "/prompts/"; private static final Map<String, String> PROMPT_CACHE = new ConcurrentHashMap<>(); /** * Load a prompt from resources or PromptService. * * @param promptId The ID of the prompt (e.g., "loop.agent.structured.evaluation") * @param variables Variables to apply to the prompt template * @return The processed prompt text, or null if not found */ public static String loadPrompt(String promptId, Map<String, Object> variables) { // Try to get from PromptService first PromptService promptService = PromptServiceRegistry.getInstance(); if (promptService != null) { // Load default from resources if not cached String defaultTemplate = loadDefaultTemplate(promptId); if (defaultTemplate != null) { Prompt prompt = promptService.createIfNotExists( promptId, defaultTemplate, null, false, Language.GENERAL ); if (prompt != null && prompt.getMessage() != null) { return PromptUtils.applyVariables(prompt.getMessage(), variables); } } } // Fallback to loading directly from resources String template = loadDefaultTemplate(promptId); if (template != null) { return PromptUtils.applyVariables(template, variables); } return null; } /** * Load default template from resources. */ private static String loadDefaultTemplate(String promptId) { // Check cache first String cached = PROMPT_CACHE.get(promptId); if (cached != null) { return cached; } // Load from resources String resourcePath = PROMPTS_RESOURCE_PATH + promptId + ".prompt"; try (InputStream is = DefaultPromptLoader.class.getResourceAsStream(resourcePath)) { if (is != null) { String template = new String(is.readAllBytes(), StandardCharsets.UTF_8); PROMPT_CACHE.put(promptId, template); return template; } } catch (IOException e) { log.error("Failed to load prompt template: {}", resourcePath, e); } return null; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core
java-sources/ai/driftkit/driftkit-context-engineering-core/0.8.1/ai/driftkit/context/core/util/PromptUtils.java
package ai.driftkit.context.core.util; import ai.driftkit.context.core.service.TemplateEngine; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import ai.driftkit.common.utils.JsonUtils; import org.apache.commons.codec.digest.DigestUtils; import java.util.HashMap; import java.util.Map; public class PromptUtils { public static String applyVariables(String message, Map<String, Object> variables) { if (variables != null) { message = TemplateEngine.renderTemplate(message, variables); } return message; } public static String hashString(String input) { return DigestUtils.sha256Hex(input); } public static Map<String, String> convertVariables(Map<String, Object> variables) { Map<String, String> result = new HashMap<>(); if (variables != null) { for (Map.Entry<String, Object> entry : variables.entrySet()) { Object value = entry.getValue(); if (value instanceof JsonNode) { try { result.put(entry.getKey(), JsonUtils.toJson(value)); } catch (JsonProcessingException e) { // In case of exception, fallback to toString() result.put(entry.getKey(), String.valueOf(value)); } } else { result.put(entry.getKey(), String.valueOf(value)); } } } return result; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/MongodbPromptService.java
package ai.driftkit.context.services; import ai.driftkit.common.domain.Prompt; import ai.driftkit.common.domain.Prompt.State; import ai.driftkit.common.domain.Language; import ai.driftkit.context.core.service.PromptServiceBase; import ai.driftkit.context.services.config.ApplicationContextProvider; import ai.driftkit.context.services.repository.PromptRepository; import lombok.extern.slf4j.Slf4j; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; @Slf4j public class MongodbPromptService implements PromptServiceBase { private PromptRepository promptRepository; @Override public void configure(Map<String, String> config) { getPromptRepository(); } @Override public boolean supportsName(String name) { return "mongodb".equals(name); } private PromptRepository getPromptRepository() { if (this.promptRepository == null) { if (ApplicationContextProvider.getApplicationContext() != null) { this.promptRepository = ApplicationContextProvider.getApplicationContext().getBean(PromptRepository.class); } else { throw new IllegalStateException("ApplicationContext is not initialized yet."); } } return this.promptRepository; } @Override public Optional<Prompt> getPromptById(String id) { return getPromptRepository().findById(id); } @Override public List<Prompt> getPromptsByIds(List<String> ids) { return getPromptRepository().findAllById(ids); } @Override public List<Prompt> getPromptsByMethods(List<String> methods) { return getPromptRepository().findByMethodIsIn(methods); } @Override public List<Prompt> getPromptsByMethodsAndState(List<String> methods, State state) { return getPromptRepository().findByMethodIsInAndState(methods, state); } @Override public List<Prompt> getPrompts() { return getPromptRepository().findAll(); } @Override public Prompt savePrompt(Prompt prompt) { Optional<Prompt> currentPromptOpt = getCurrentPrompt(prompt.getMethod(), prompt.getLanguage()); if (currentPromptOpt.isEmpty() || prompt.getId() == null) { prompt.setId(UUID.randomUUID().toString()); prompt.setCreatedTime(System.currentTimeMillis()); } if (currentPromptOpt.isPresent()) { Prompt currentPrompt = currentPromptOpt.get(); if (prompt.getMessage().equals(currentPrompt.getMessage())) { prompt.setId(currentPrompt.getId()); } else { currentPrompt.setState(State.REPLACED); getPromptRepository().save(currentPrompt); } } if (prompt.getState() == null) { prompt.setState(State.CURRENT); } prompt.setUpdatedTime(System.currentTimeMillis()); return getPromptRepository().save(prompt); } @Override public Prompt deletePrompt(String id) { Optional<Prompt> prompt = getPromptById(id); getPromptRepository().deleteById(id); return prompt.orElse(null); } @Override public boolean isConfigured() { return promptRepository != null; } public Optional<Prompt> getCurrentPrompt(String method, Language language) { return getPromptRepository().findByMethodAndLanguageAndState(method, language, State.CURRENT); } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/PromptServiceSpringAdapter.java
package ai.driftkit.context.services; import ai.driftkit.config.EtlConfig; import ai.driftkit.config.EtlConfig.PromptServiceConfig; import ai.driftkit.context.core.service.DictionaryItemService; import ai.driftkit.context.core.service.PromptService; import ai.driftkit.context.core.service.PromptServiceBase; import ai.driftkit.context.core.service.PromptServiceFactory; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.annotation.Primary; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; @Slf4j @Service @Primary public class PromptServiceSpringAdapter extends PromptService { @Autowired private EtlConfig etlConfig; private volatile boolean initialized = false; public PromptServiceSpringAdapter(@Autowired DictionaryItemService dictionaryItemService) { super(null, dictionaryItemService); } @SneakyThrows @EventListener(ApplicationReadyEvent.class) public void init() { if (!initialized) { PromptServiceConfig promptServiceConfig = etlConfig.getPromptService(); PromptServiceBase actualPromptService = PromptServiceFactory.fromName( promptServiceConfig.getName(), promptServiceConfig.getConfig() ); this.promptService = actualPromptService; initialized = true; log.info("Initialized PromptServiceSpringAdapter with {} prompt service", promptServiceConfig.getName()); } } @Override public boolean isConfigured() { return initialized; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/SpringDictionaryGroupService.java
package ai.driftkit.context.services; import ai.driftkit.common.domain.DictionaryGroup; import ai.driftkit.common.domain.Language; import ai.driftkit.context.core.service.DictionaryGroupService; import ai.driftkit.context.services.domain.DictionaryGroupDocument; import ai.driftkit.context.services.repository.SpringDictionaryGroupRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * Spring implementation of DictionaryGroupService. * This service acts as an adapter between the core business layer * and the Spring Data MongoDB repository layer. */ @Service @RequiredArgsConstructor public class SpringDictionaryGroupService implements DictionaryGroupService { private final SpringDictionaryGroupRepository repository; @Override public Optional<DictionaryGroup> findById(String id) { return repository.findById(id).map(doc -> (DictionaryGroup) doc); } @Override public List<DictionaryGroup> findByLanguage(Language language) { return repository.findDictionaryGroupsByLanguage(language) .stream() .map(doc -> (DictionaryGroup) doc) .collect(Collectors.toList()); } @Override public DictionaryGroup save(DictionaryGroup group) { DictionaryGroupDocument document = convertToDocument(group); DictionaryGroupDocument saved = repository.save(document); return saved; } @Override public List<DictionaryGroup> saveAll(List<DictionaryGroup> groups) { List<DictionaryGroupDocument> documents = groups.stream() .map(this::convertToDocument) .collect(Collectors.toList()); List<DictionaryGroupDocument> saved = repository.saveAll(documents); return saved.stream() .map(doc -> (DictionaryGroup) doc) .collect(Collectors.toList()); } @Override public void deleteById(String id) { repository.deleteById(id); } @Override public boolean existsById(String id) { return repository.existsById(id); } @Override public List<DictionaryGroup> findAll() { return repository.findAll() .stream() .map(doc -> (DictionaryGroup) doc) .collect(Collectors.toList()); } private DictionaryGroupDocument convertToDocument(DictionaryGroup group) { if (group instanceof DictionaryGroupDocument) { return (DictionaryGroupDocument) group; } // If it's a plain DictionaryGroup, we need to convert it to a document DictionaryGroupDocument document = new DictionaryGroupDocument(); document.setId(group.getId()); document.setName(group.getName()); document.setLanguage(group.getLanguage()); document.setCreatedAt(group.getCreatedAt()); document.setUpdatedAt(group.getUpdatedAt()); return document; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/SpringDictionaryItemService.java
package ai.driftkit.context.services; import ai.driftkit.common.domain.DictionaryItem; import ai.driftkit.common.domain.Language; import ai.driftkit.context.core.service.DictionaryItemService; import ai.driftkit.context.services.domain.DictionaryItemDocument; import ai.driftkit.context.services.repository.SpringDictionaryItemRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * Spring implementation of DictionaryItemService. * This service acts as an adapter between the core business layer * and the Spring Data MongoDB repository layer. */ @Service @RequiredArgsConstructor public class SpringDictionaryItemService implements DictionaryItemService { private final SpringDictionaryItemRepository repository; @Override public Optional<DictionaryItem> findById(String id) { return repository.findById(id).map(doc -> (DictionaryItem) doc); } @Override public List<DictionaryItem> findByLanguage(Language language) { return repository.findDictionaryItemsByLanguage(language) .stream() .map(doc -> (DictionaryItem) doc) .collect(Collectors.toList()); } @Override public List<DictionaryItem> findByGroupId(String groupId) { return repository.findDictionaryItemsByGroupId(groupId) .stream() .map(doc -> (DictionaryItem) doc) .collect(Collectors.toList()); } @Override public DictionaryItem save(DictionaryItem item) { DictionaryItemDocument document = convertToDocument(item); DictionaryItemDocument saved = repository.save(document); return saved; } @Override public List<DictionaryItem> saveAll(List<DictionaryItem> items) { List<DictionaryItemDocument> documents = items.stream() .map(this::convertToDocument) .collect(Collectors.toList()); List<DictionaryItemDocument> saved = repository.saveAll(documents); return saved.stream() .map(doc -> (DictionaryItem) doc) .collect(Collectors.toList()); } @Override public void deleteById(String id) { repository.deleteById(id); } @Override public boolean existsById(String id) { return repository.existsById(id); } @Override public List<DictionaryItem> findAll() { return repository.findAll() .stream() .map(doc -> (DictionaryItem) doc) .collect(Collectors.toList()); } private DictionaryItemDocument convertToDocument(DictionaryItem item) { if (item instanceof DictionaryItemDocument) { return (DictionaryItemDocument) item; } // If it's a plain DictionaryItem, we need to convert it to a document DictionaryItemDocument document = new DictionaryItemDocument(); document.setId(item.getId()); document.setGroupId(item.getGroupId()); document.setLanguage(item.getLanguage()); document.setSamples(item.getSamples()); document.setMarkers(item.getMarkers()); document.setCreatedAt(item.getCreatedAt()); document.setUpdatedAt(item.getUpdatedAt()); return document; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/config/ApplicationContextProvider.java
package ai.driftkit.context.services.config; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component("promptContextProvider") public class ApplicationContextProvider implements ApplicationContextAware { private static ApplicationContext context; /** * Sets the ApplicationContext. Called by Spring during context initialization. * * @param applicationContext the Spring ApplicationContext */ @Override public void setApplicationContext(ApplicationContext applicationContext) { context = applicationContext; } /** * Retrieves the stored ApplicationContext. * * @return the Spring ApplicationContext */ public static ApplicationContext getApplicationContext() { if (context == null) { throw new IllegalStateException("ApplicationContext has not been initialized yet."); } return context; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/config/PromptServicesAutoConfiguration.java
package ai.driftkit.context.services.config; import ai.driftkit.context.core.registry.PromptServiceRegistry; import ai.driftkit.context.core.service.PromptService; import ai.driftkit.context.services.MongodbPromptService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; /** * Auto-configuration for DriftKit Context Engineering Services. * * This configuration automatically sets up: * - Core prompt services (PromptServiceSpringAdapter, MongodbPromptService) * - MongoDB repositories for prompt persistence * - Registration with global PromptServiceRegistry */ @Slf4j @AutoConfiguration @ComponentScan(basePackages = "ai.driftkit.context.services") @EnableMongoRepositories(basePackages = "ai.driftkit.context.services.repository") @ConditionalOnClass(PromptService.class) public class PromptServicesAutoConfiguration { @Autowired(required = false) private PromptService promptService; @Bean @ConditionalOnMissingBean(MongodbPromptService.class) public MongodbPromptService mongodbPromptService() { log.info("Creating MongodbPromptService bean"); return new MongodbPromptService(); } @PostConstruct public void registerPromptService() { if (promptService != null) { PromptServiceRegistry.register(promptService); log.info("Registered PromptService with global registry: {}", promptService.getClass().getSimpleName()); } } @PreDestroy public void unregisterPromptService() { if (promptService != null) { PromptServiceRegistry.unregister(); log.debug("Unregistered PromptService from global registry"); } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/domain/DictionaryGroupDocument.java
package ai.driftkit.context.services.domain; import ai.driftkit.common.domain.DictionaryGroup; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "dictionary_groups") public class DictionaryGroupDocument extends DictionaryGroup { @Id @Override public String getId() { return super.getId(); } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/domain/DictionaryItemDocument.java
package ai.driftkit.context.services.domain; import ai.driftkit.common.domain.DictionaryItem; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.index.Indexed; @Document(collection = "dictionary_items") public class DictionaryItemDocument extends DictionaryItem { @Id @Override public String getId() { return super.getId(); } @Override public String getGroupId() { return super.getGroupId(); } }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/repository/PromptRepository.java
package ai.driftkit.context.services.repository; import ai.driftkit.common.domain.Prompt; import ai.driftkit.common.domain.Language; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface PromptRepository extends MongoRepository<Prompt, String> { List<Prompt> findByMethod(String method); List<Prompt> findByMethodIsIn(List<String> method); List<Prompt> findByMethodIsInAndState(List<String> method, Prompt.State state); List<Prompt> findByState(Prompt.State state); List<Prompt> findByMethodAndState(String method, Prompt.State state); Optional<Prompt> findByMethodAndLanguageAndState(String method, Language language, Prompt.State state); }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/repository/SpringDictionaryGroupRepository.java
package ai.driftkit.context.services.repository; import ai.driftkit.common.domain.DictionaryGroup; import ai.driftkit.common.domain.Language; import ai.driftkit.context.core.service.DictionaryGroupRepository; import ai.driftkit.context.services.domain.DictionaryGroupDocument; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface SpringDictionaryGroupRepository extends MongoRepository<DictionaryGroupDocument, String>, DictionaryGroupRepository<DictionaryGroupDocument> { @Override List<DictionaryGroupDocument> findDictionaryGroupsByLanguage(Language language); }
0
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services
java-sources/ai/driftkit/driftkit-context-engineering-services/0.8.1/ai/driftkit/context/services/repository/SpringDictionaryItemRepository.java
package ai.driftkit.context.services.repository; import ai.driftkit.common.domain.Language; import ai.driftkit.context.core.service.DictionaryItemRepository; import ai.driftkit.context.services.domain.DictionaryItemDocument; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface SpringDictionaryItemRepository extends MongoRepository<DictionaryItemDocument, String>, DictionaryItemRepository<DictionaryItemDocument> { @Override List<DictionaryItemDocument> findDictionaryItemsByLanguage(Language language); @Override List<DictionaryItemDocument> findDictionaryItemsByGroupId(String groupId); }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai/0.8.1/ai/driftkit/context
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai/0.8.1/ai/driftkit/context/springai/DriftKitChatClient.java
package ai.driftkit.context.springai; import ai.driftkit.common.domain.Language; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.ChatClient.CallResponseSpec; import org.springframework.ai.chat.client.ChatClient.ChatClientRequestSpec; import org.springframework.ai.chat.model.ChatResponse; import org.springframework.ai.chat.prompt.ChatOptions; import java.util.Map; /** * Enhanced ChatClient that integrates DriftKit prompt management with Spring AI. * This wrapper provides convenient methods to use DriftKit prompts directly * with Spring AI ChatClient. * * Usage example: * <pre> * @Component * public class MyService { * private final DriftKitChatClient chatClient; * * public String analyzeSentiment(String review) { * // Use DriftKit prompt with variables * return chatClient.promptById("sentiment.analysis") * .withVariable("review", review) * .withLanguage(Language.ENGLISH) * .call() * .content(); * } * * public ProductInfo extractProductInfo(String description) { * // Use DriftKit prompt and map to entity * return chatClient.promptById("product.extraction") * .withVariable("description", description) * .call() * .entity(ProductInfo.class); * } * } * </pre> */ @Slf4j @RequiredArgsConstructor public class DriftKitChatClient { private final ChatClient chatClient; private final DriftKitPromptProvider promptProvider; /** * Start building a prompt from DriftKit prompt ID * * @param promptId The DriftKit prompt ID * @return DriftKitPromptSpec for fluent configuration */ public DriftKitPromptSpec promptById(String promptId) { return new DriftKitPromptSpec(promptId); } /** * Get the underlying Spring AI ChatClient for direct access */ public ChatClient getChatClient() { return chatClient; } /** * Get the prompt provider for direct access */ public DriftKitPromptProvider getPromptProvider() { return promptProvider; } /** * Fluent builder for DriftKit prompt execution */ public class DriftKitPromptSpec { private final String promptId; private final Map<String, Object> variables = new java.util.HashMap<>(); private Language language = Language.GENERAL; private DriftKitPromptSpec(String promptId) { this.promptId = promptId; } /** * Add a variable to the prompt */ public DriftKitPromptSpec withVariable(String name, Object value) { this.variables.put(name, value); return this; } /** * Add multiple variables to the prompt */ public DriftKitPromptSpec withVariables(Map<String, Object> vars) { this.variables.putAll(vars); return this; } /** * Set the language for the prompt */ public DriftKitPromptSpec withLanguage(Language language) { this.language = language; return this; } /** * Execute the prompt and return response spec */ public CallResponseSpec call() { // Get prompt configuration from DriftKit DriftKitPromptProvider.PromptConfiguration config = promptProvider.getPromptWithVariables(promptId, variables, language); // Build ChatClient prompt var promptSpec = chatClient.prompt(); // Add system message if present if (config.hasSystemMessage()) { promptSpec.system(config.getSystemMessage()); } // Add user message promptSpec.user(config.getUserMessage()); // Apply temperature if specified if (config.getTemperature() != null) { promptSpec.options(ChatOptions.builder() .temperature(config.getTemperature()) .build() ); } return promptSpec.call(); } /** * Execute the prompt and return content directly */ public String content() { return call().content(); } /** * Execute the prompt and map to entity */ public <T> T entity(Class<T> type) { return call().entity(type); } /** * Execute the prompt and return full ChatResponse */ public ChatResponse chatResponse() { return call().chatResponse(); } /** * Stream the response */ public reactor.core.publisher.Flux<String> stream() { // Get prompt configuration from DriftKit DriftKitPromptProvider.PromptConfiguration config = promptProvider.getPromptWithVariables(promptId, variables, language); // Build ChatClient prompt var promptSpec = chatClient.prompt(); // Add system message if present if (config.hasSystemMessage()) { promptSpec.system(config.getSystemMessage()); } // Add user message promptSpec.user(config.getUserMessage()); // Apply temperature if specified if (config.getTemperature() != null) { promptSpec.options(ChatOptions.builder() .temperature(config.getTemperature()) .build() ); } // Stream return promptSpec.stream().content(); } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai/0.8.1/ai/driftkit/context
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai/0.8.1/ai/driftkit/context/springai/DriftKitPromptProvider.java
package ai.driftkit.context.springai; import ai.driftkit.common.domain.Language; import ai.driftkit.common.domain.Prompt; import ai.driftkit.context.core.service.PromptService; import ai.driftkit.context.core.util.PromptUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.util.List; import java.util.Map; import java.util.Optional; /** * Provider for DriftKit prompts to be used with Spring AI ChatClient. * This allows seamless integration of DriftKit's prompt management * with Spring AI's fluent API. * * Usage example: * <pre> * @Component * public class MyService { * private final ChatClient chatClient; * private final DriftKitPromptProvider promptProvider; * * public String classifySentiment(String review) { * // Get prompt configuration from DriftKit * var promptConfig = promptProvider.getPrompt("sentiment.analysis", Language.ENGLISH); * * return chatClient.prompt() * .system(promptConfig.getSystemMessage()) * .user(u -> u.text(promptConfig.getUserMessage()) * .param("review", review)) * .options(opt -> opt.temperature(promptConfig.getTemperature())) * .call() * .entity(Sentiment.class); * } * } * </pre> */ @Slf4j @RequiredArgsConstructor public class DriftKitPromptProvider { private final PromptService promptService; /** * Get prompt configuration for use with Spring AI ChatClient * * @param promptId The DriftKit prompt ID * @return PromptConfiguration ready for Spring AI */ public PromptConfiguration getPrompt(String promptId) { return getPrompt(promptId, Language.GENERAL); } /** * Get prompt configuration with language support * * @param promptId The DriftKit prompt ID * @param language The desired language * @return PromptConfiguration ready for Spring AI */ public PromptConfiguration getPrompt(String promptId, Language language) { // First try to get prompt for specific language List<Prompt> prompts = promptService.getPromptsByMethods(List.of(promptId)); Optional<Prompt> promptOpt = prompts.stream() .filter(p -> p.getLanguage() == language) .findFirst(); // Fall back to GENERAL language if specific language not found if (promptOpt.isEmpty() && language != Language.GENERAL) { promptOpt = prompts.stream() .filter(p -> p.getLanguage() == Language.GENERAL) .findFirst(); if (promptOpt.isPresent()) { log.debug("Prompt {} not found for language {}, falling back to GENERAL", promptId, language); } } if (promptOpt.isEmpty()) { throw new IllegalArgumentException( String.format("Prompt not found: %s for language: %s", promptId, language)); } Prompt prompt = promptOpt.get(); return PromptConfiguration.builder() .promptId(promptId) .userMessage(prompt.getMessage()) .systemMessage(prompt.getSystemMessage()) .temperature(prompt.getTemperature()) .jsonResponse(prompt.isJsonResponse()) .responseFormat(prompt.getResponseFormat()) .language(prompt.getLanguage()) .build(); } /** * Get prompt with variables already applied * * @param promptId The DriftKit prompt ID * @param variables Variables to apply to the prompt * @return PromptConfiguration with processed messages */ public PromptConfiguration getPromptWithVariables(String promptId, Map<String, Object> variables) { return getPromptWithVariables(promptId, variables, Language.GENERAL); } /** * Get prompt with variables already applied and language support * * @param promptId The DriftKit prompt ID * @param variables Variables to apply to the prompt * @param language The desired language * @return PromptConfiguration with processed messages */ public PromptConfiguration getPromptWithVariables(String promptId, Map<String, Object> variables, Language language) { PromptConfiguration config = getPrompt(promptId, language); // Apply variables to messages String processedUserMessage = PromptUtils.applyVariables(config.getUserMessage(), variables); String processedSystemMessage = config.getSystemMessage() != null ? PromptUtils.applyVariables(config.getSystemMessage(), variables) : null; return config.toBuilder() .userMessage(processedUserMessage) .systemMessage(processedSystemMessage) .build(); } /** * Check if a prompt exists for a given ID and language * * @param promptId The DriftKit prompt ID * @param language The language to check * @return true if prompt exists */ public boolean hasPrompt(String promptId, Language language) { List<Prompt> prompts = promptService.getPromptsByMethods(List.of(promptId)); return prompts.stream().anyMatch(p -> p.getLanguage() == language); } /** * Get all available languages for a prompt * * @param promptId The DriftKit prompt ID * @return List of available languages */ public List<Language> getAvailableLanguages(String promptId) { List<Prompt> prompts = promptService.getPromptsByMethods(List.of(promptId)); return prompts.stream() .map(Prompt::getLanguage) .distinct() .toList(); } /** * Configuration holder for DriftKit prompts */ @lombok.Data @lombok.Builder(toBuilder = true) public static class PromptConfiguration { private final String promptId; private final String userMessage; private final String systemMessage; private final Double temperature; private final boolean jsonResponse; private final ai.driftkit.common.domain.client.ResponseFormat responseFormat; private final Language language; /** * Check if this prompt has a system message */ public boolean hasSystemMessage() { return systemMessage != null && !systemMessage.isBlank(); } /** * Get temperature or default value */ public double getTemperatureOrDefault(double defaultValue) { return temperature != null ? temperature : defaultValue; } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai/0.8.1/ai/driftkit/context
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai/0.8.1/ai/driftkit/context/springai/DriftKitTracingAdvisor.java
package ai.driftkit.context.springai; import ai.driftkit.common.domain.ModelTrace; import ai.driftkit.common.domain.client.*; import ai.driftkit.workflows.core.agent.RequestTracingProvider; import ai.driftkit.workflows.core.agent.RequestTracingRegistry; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.ChatClientRequest; import org.springframework.ai.chat.client.ChatClientResponse; import org.springframework.ai.chat.client.advisor.api.*; import org.springframework.ai.chat.model.ChatResponse; import org.springframework.ai.chat.prompt.ChatOptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * Spring AI Advisor that provides DriftKit tracing for ChatClient calls. * This advisor intercepts Spring AI requests and responses to provide * detailed tracing information compatible with DriftKit's monitoring system. * * Usage example: * <pre> * @Configuration * public class ChatClientConfig { * * @Bean * public ChatClient chatClient(ChatClient.Builder builder, * DriftKitTracingAdvisor tracingAdvisor) { * return builder * .defaultAdvisors(tracingAdvisor) * .build(); * } * } * </pre> */ @Slf4j public class DriftKitTracingAdvisor implements CallAdvisor, StreamAdvisor { private final RequestTracingProvider tracingProvider; private final String applicationName; // Thread-local storage for request timing private static final ThreadLocal<RequestContext> requestContextHolder = new ThreadLocal<>(); public DriftKitTracingAdvisor() { this(RequestTracingRegistry.getInstance(), "spring-ai-app"); } public DriftKitTracingAdvisor(RequestTracingProvider tracingProvider) { this(tracingProvider, "spring-ai-app"); } public DriftKitTracingAdvisor(RequestTracingProvider tracingProvider, String applicationName) { this.tracingProvider = tracingProvider; this.applicationName = applicationName; } @Override public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) { // Create request context for tracing RequestContext reqContext = getRequestContext(request); // Store in thread-local for response handling requestContextHolder.set(reqContext); // Log request start log.debug("Starting Spring AI request: {}", reqContext.requestId); try { // Call the next advisor in chain ChatClientResponse response = chain.nextCall(request); // Calculate execution time long executionTimeMs = Duration.between(reqContext.startTime, Instant.now()).toMillis(); // Build DriftKit trace ModelTrace trace = buildTrace(reqContext, response.chatResponse(), executionTimeMs); // Build tracing context RequestTracingProvider.RequestContext traceContext = RequestTracingProvider.RequestContext.builder() .contextId(reqContext.requestId) .contextType("SPRING_AI_CHAT") .variables(reqContext.advisorParams) .build(); // Convert Spring AI request/response to DriftKit format for tracing if (tracingProvider != null) { // Build ModelTextRequest representation ModelTextRequest modelRequest = buildModelTextRequest(reqContext); // Build ModelTextResponse representation ModelTextResponse modelResponse = buildModelTextResponse(response.chatResponse(), trace); // Trace using existing interface tracingProvider.traceTextRequest(modelRequest, modelResponse, traceContext); log.debug("Traced Spring AI request: {} in {}ms", reqContext.requestId, executionTimeMs); } return response; } catch (Exception e) { log.error("Error tracing Spring AI response", e); throw new RuntimeException("Error in DriftKit tracing advisor", e); } finally { // Clean up thread-local requestContextHolder.remove(); } } private static @NotNull RequestContext getRequestContext(ChatClientRequest request) { RequestContext reqContext = new RequestContext(); reqContext.requestId = UUID.randomUUID().toString(); reqContext.startTime = Instant.now(); reqContext.userMessage = request.prompt().getUserMessage().getText(); reqContext.systemMessage = request.prompt().getSystemMessage().getText(); reqContext.advisorParams = request.context(); reqContext.chatOptions = request.prompt().getOptions(); return reqContext; } @Override public Flux<ChatClientResponse> adviseStream(ChatClientRequest request, StreamAdvisorChain chain) { // Create request context for tracing RequestContext reqContext = getRequestContext(request); log.debug("Starting Spring AI streaming request: {}", reqContext.requestId); // For streaming, we'll trace the initial request and log completion return Mono.just(request) .publishOn(Schedulers.boundedElastic()) .map(req -> { // Log request details if (tracingProvider != null) { try { ModelTextRequest modelRequest = buildModelTextRequest(reqContext); log.debug("Tracing streaming request: {}", reqContext.requestId); } catch (Exception e) { log.error("Error preparing trace for streaming request", e); } } return req; }) .flatMapMany(req -> chain.nextStream(req)) .doOnComplete(() -> { long executionTimeMs = Duration.between(reqContext.startTime, Instant.now()).toMillis(); log.debug("Completed Spring AI streaming request: {} in {}ms", reqContext.requestId, executionTimeMs); }) .doOnError(error -> { log.error("Error in Spring AI streaming request: {}", reqContext.requestId, error); }); } @Override public String getName() { return "DriftKitTracingAdvisor"; } @Override public int getOrder() { // Run early in the advisor chain to capture full execution time return 0; // Lower values execute first } private ModelTrace buildTrace(RequestContext reqContext, ChatResponse response, long executionTimeMs) { ModelTrace trace = ModelTrace.builder() .executionTimeMs(executionTimeMs) .hasError(false) .build(); // Extract model information if (response.getMetadata() != null) { Object model = response.getMetadata().get("model"); if (model != null) { trace.setModel(model.toString()); } } // Extract options information if (reqContext.chatOptions != null) { if (reqContext.chatOptions.getTemperature() != null) { trace.setTemperature(reqContext.chatOptions.getTemperature()); } if (reqContext.chatOptions.getModel() != null) { trace.setModel(reqContext.chatOptions.getModel()); } } // Extract token usage if available if (response.getMetadata() != null && response.getMetadata().containsKey("usage")) { extractTokenUsage(trace, response.getMetadata().get("usage")); } // Extract response format if (response.getResults() != null && !response.getResults().isEmpty()) { var result = response.getResults().get(0); if (result.getMetadata() != null && result.getMetadata().containsKey("finishReason")) { trace.setResponseFormat(result.getMetadata().get("finishReason").toString()); } } return trace; } private void extractTokenUsage(ModelTrace trace, Object usage) { if (usage instanceof Map) { Map<?, ?> usageMap = (Map<?, ?>) usage; Object promptTokens = usageMap.get("promptTokens"); if (promptTokens instanceof Number) { trace.setPromptTokens(((Number) promptTokens).intValue()); } Object completionTokens = usageMap.get("completionTokens"); if (completionTokens instanceof Number) { trace.setCompletionTokens(((Number) completionTokens).intValue()); } } } /** * Create a named instance of the tracing advisor */ public static DriftKitTracingAdvisor named(String applicationName) { return new DriftKitTracingAdvisor(RequestTracingRegistry.getInstance(), applicationName); } /** * Create an instance with a specific tracing provider */ public static DriftKitTracingAdvisor withProvider(RequestTracingProvider provider) { return new DriftKitTracingAdvisor(provider); } /** * Build ModelTextRequest from Spring AI request context */ private ModelTextRequest buildModelTextRequest(RequestContext reqContext) { List<ModelImageResponse.ModelContentMessage> messages = new ArrayList<>(); // Add system message if present if (reqContext.systemMessage != null && !reqContext.systemMessage.isBlank()) { messages.add(ModelImageResponse.ModelContentMessage.create(Role.system, reqContext.systemMessage)); } // Add user message if (reqContext.userMessage != null && !reqContext.userMessage.isBlank()) { messages.add(ModelImageResponse.ModelContentMessage.create(Role.user, reqContext.userMessage)); } // Build request var requestBuilder = ModelTextRequest.builder() .messages(messages); // Apply options if available if (reqContext.chatOptions != null) { if (reqContext.chatOptions.getModel() != null) { requestBuilder.model(reqContext.chatOptions.getModel()); } if (reqContext.chatOptions.getTemperature() != null) { requestBuilder.temperature(reqContext.chatOptions.getTemperature()); } // Note: ModelTextRequest doesn't have maxTokens, topP, topK fields // These would need to be added if required for tracing } return requestBuilder.build(); } /** * Build ModelTextResponse from Spring AI response */ private ModelTextResponse buildModelTextResponse(ChatResponse response, ModelTrace trace) { var responseBuilder = ModelTextResponse.builder() .trace(trace); // Extract model from metadata if (response.getMetadata() != null && response.getMetadata().containsKey("model")) { responseBuilder.model(response.getMetadata().get("model").toString()); } // Build choices from results if (response.getResults() != null && !response.getResults().isEmpty()) { List<ModelTextResponse.ResponseMessage> choices = new ArrayList<>(); for (var result : response.getResults()) { String content = result.getOutput() != null ? result.getOutput().getText() : ""; var message = ModelTextResponse.ResponseMessage.builder() .message(ModelImageResponse.ModelMessage.builder() .role(Role.assistant) .content(content) .build()) .build(); choices.add(message); } responseBuilder.choices(choices); // Note: ModelTextResponse doesn't have a response field - it's computed from choices } // Extract usage if available if (response.getMetadata() != null && response.getMetadata().containsKey("usage")) { Object usage = response.getMetadata().get("usage"); if (usage instanceof Map) { Map<?, ?> usageMap = (Map<?, ?>) usage; var usageBuilder = ModelTextResponse.Usage.builder(); Object promptTokens = usageMap.get("promptTokens"); if (promptTokens instanceof Number) { usageBuilder.promptTokens(((Number) promptTokens).intValue()); } Object completionTokens = usageMap.get("completionTokens"); if (completionTokens instanceof Number) { usageBuilder.completionTokens(((Number) completionTokens).intValue()); } Object totalTokens = usageMap.get("totalTokens"); if (totalTokens instanceof Number) { usageBuilder.totalTokens(((Number) totalTokens).intValue()); } responseBuilder.usage(usageBuilder.build()); } } return responseBuilder.build(); } /** * Internal context holder for request data */ private static class RequestContext { String requestId; Instant startTime; String userMessage; String systemMessage; Map<String, Object> advisorParams; ChatOptions chatOptions; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai/0.8.1/ai/driftkit/context
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai/0.8.1/ai/driftkit/context/springai/SpringAIChatClientFactory.java
package ai.driftkit.context.springai; import ai.driftkit.context.core.service.PromptService; import ai.driftkit.workflows.core.agent.RequestTracingProvider; import ai.driftkit.workflows.core.agent.RequestTracingRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor; import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor; import org.springframework.ai.chat.client.advisor.api.Advisor; import reactor.core.scheduler.Schedulers; import org.springframework.ai.chat.memory.ChatMemory; import org.springframework.ai.chat.memory.MessageWindowChatMemory; import org.springframework.ai.chat.memory.ChatMemoryRepository; import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository; import org.springframework.ai.chat.model.ChatModel; import java.util.ArrayList; import java.util.List; /** * Factory for creating Spring AI ChatClient instances with DriftKit integration. * This factory automatically configures ChatClient with: * - DriftKit tracing advisor for monitoring * - DriftKit prompt provider for prompt management * - Optional chat memory support * * Usage example: * <pre> * @Configuration * public class ChatClientConfig { * * @Bean * public SpringAIChatClientFactory chatClientFactory(ChatModel chatModel, * PromptService promptService) { * return SpringAIChatClientFactory.builder() * .chatModel(chatModel) * .promptService(promptService) * .enableTracing(true) * .enableMemory(true) * .build(); * } * * @Bean * public ChatClient chatClient(SpringAIChatClientFactory factory) { * return factory.createChatClient(); * } * } * </pre> */ @Slf4j public class SpringAIChatClientFactory { private final ChatModel chatModel; private final PromptService promptService; private final RequestTracingProvider tracingProvider; private final boolean enableTracing; private final boolean enableMemory; private final boolean enableLogging; private final ChatMemory chatMemory; private final String applicationName; private SpringAIChatClientFactory(Builder builder) { this.chatModel = builder.chatModel; this.promptService = builder.promptService; this.tracingProvider = builder.tracingProvider != null ? builder.tracingProvider : RequestTracingRegistry.getInstance(); this.enableTracing = builder.enableTracing; this.enableMemory = builder.enableMemory; this.enableLogging = builder.enableLogging; this.chatMemory = builder.chatMemory != null ? builder.chatMemory : MessageWindowChatMemory.builder() .chatMemoryRepository(new InMemoryChatMemoryRepository()) .maxMessages(10) .build(); this.applicationName = builder.applicationName; } /** * Create a new Spring AI ChatClient with DriftKit integration */ public ChatClient createSpringAIChatClient() { return createSpringAIChatClient(ChatClient.builder(chatModel)); } /** * Create a new Spring AI ChatClient with custom builder */ public ChatClient createSpringAIChatClient(ChatClient.Builder clientBuilder) { List<Advisor> advisors = new ArrayList<>(); // Add tracing advisor if enabled if (enableTracing && tracingProvider != null) { DriftKitTracingAdvisor tracingAdvisor = new DriftKitTracingAdvisor( tracingProvider, applicationName); advisors.add(tracingAdvisor); log.info("Added DriftKit tracing advisor to ChatClient"); } // Add memory advisor if enabled if (enableMemory) { // Create MessageChatMemoryAdvisor using builder MessageChatMemoryAdvisor memoryAdvisor = MessageChatMemoryAdvisor.builder(chatMemory) .conversationId("default") .scheduler(Schedulers.boundedElastic()) .build(); advisors.add(memoryAdvisor); log.info("Added memory advisor to ChatClient"); } // Add logging advisor if enabled if (enableLogging) { SimpleLoggerAdvisor loggingAdvisor = new SimpleLoggerAdvisor(); advisors.add(loggingAdvisor); log.info("Added logging advisor to ChatClient"); } // Apply advisors with proper typing if (!advisors.isEmpty()) { // Pass the list of advisors directly clientBuilder.defaultAdvisors(advisors); } return clientBuilder.build(); } /** * Create a DriftKitChatClient with prompt provider integration */ public DriftKitChatClient createChatClient() { ChatClient chatClient = createSpringAIChatClient(); DriftKitPromptProvider promptProvider = new DriftKitPromptProvider(promptService); return new DriftKitChatClient(chatClient, promptProvider); } /** * Get the prompt provider for standalone use */ public DriftKitPromptProvider getPromptProvider() { return new DriftKitPromptProvider(promptService); } public static Builder builder() { return new Builder(); } public static class Builder { private ChatModel chatModel; private PromptService promptService; private RequestTracingProvider tracingProvider; private boolean enableTracing = true; private boolean enableMemory = false; private boolean enableLogging = false; private ChatMemory chatMemory; private String applicationName = "spring-ai-app"; public Builder chatModel(ChatModel chatModel) { this.chatModel = chatModel; return this; } public Builder promptService(PromptService promptService) { this.promptService = promptService; return this; } public Builder tracingProvider(RequestTracingProvider tracingProvider) { this.tracingProvider = tracingProvider; return this; } public Builder enableTracing(boolean enableTracing) { this.enableTracing = enableTracing; return this; } public Builder enableMemory(boolean enableMemory) { this.enableMemory = enableMemory; return this; } public Builder enableLogging(boolean enableLogging) { this.enableLogging = enableLogging; return this; } public Builder chatMemory(ChatMemory chatMemory) { this.chatMemory = chatMemory; return this; } public Builder applicationName(String applicationName) { this.applicationName = applicationName; return this; } public SpringAIChatClientFactory build() { if (chatModel == null) { throw new IllegalStateException("ChatModel is required"); } if (promptService == null) { throw new IllegalStateException("PromptService is required"); } return new SpringAIChatClientFactory(this); } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai-starter/0.8.1/ai/driftkit/context/springai
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai-starter/0.8.1/ai/driftkit/context/springai/autoconfigure/DriftKitSpringAIAutoConfiguration.java
package ai.driftkit.context.springai.autoconfigure; import ai.driftkit.context.core.service.PromptService; import ai.driftkit.context.springai.*; import ai.driftkit.workflows.core.agent.RequestTracingProvider; import ai.driftkit.workflows.core.agent.RequestTracingRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.model.ChatModel; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Auto-configuration for DriftKit Spring AI integration. * Automatically configures: * - DriftKitPromptProvider for using DriftKit prompts with Spring AI * - DriftKitTracingAdvisor for tracing Spring AI calls * - SpringAIChatClientFactory for creating enhanced ChatClient instances * - DriftKitChatClient for convenient prompt-based interactions */ @Slf4j @AutoConfiguration @ConditionalOnClass({ChatModel.class, PromptService.class}) @ConditionalOnBean(PromptService.class) @EnableConfigurationProperties(DriftKitSpringAIProperties.class) public class DriftKitSpringAIAutoConfiguration { /** * Create DriftKitPromptProvider for accessing DriftKit prompts */ @Bean @ConditionalOnMissingBean public DriftKitPromptProvider driftKitPromptProvider(PromptService promptService) { log.info("Creating DriftKitPromptProvider"); return new DriftKitPromptProvider(promptService); } /** * Create DriftKitTracingAdvisor for tracing Spring AI calls */ @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = "driftkit.spring-ai", name = "tracing.enabled", havingValue = "true", matchIfMissing = true ) public DriftKitTracingAdvisor driftKitTracingAdvisor(DriftKitSpringAIProperties properties) { log.info("Creating DriftKitTracingAdvisor"); RequestTracingProvider tracingProvider = RequestTracingRegistry.getInstance(); if (tracingProvider == null) { log.warn("No RequestTracingProvider found in registry, tracing will be disabled"); return new DriftKitTracingAdvisor(null, properties.getApplicationName()); } return new DriftKitTracingAdvisor(tracingProvider, properties.getApplicationName()); } /** * Create SpringAIChatClientFactory for building enhanced ChatClient instances */ @Bean @ConditionalOnMissingBean @ConditionalOnBean(ChatModel.class) public SpringAIChatClientFactory springAIChatClientFactory( ChatModel chatModel, PromptService promptService, DriftKitSpringAIProperties properties) { log.info("Creating SpringAIChatClientFactory"); var builder = SpringAIChatClientFactory.builder() .chatModel(chatModel) .promptService(promptService) .applicationName(properties.getApplicationName()) .enableTracing(properties.getTracing().isEnabled()) .enableMemory(properties.getMemory().isEnabled()) .enableLogging(properties.getLogging().isEnabled()); // Set tracing provider if available RequestTracingProvider tracingProvider = RequestTracingRegistry.getInstance(); if (tracingProvider != null) { builder.tracingProvider(tracingProvider); } return builder.build(); } /** * Create default DriftKitChatClient if ChatModel is available */ @Bean @ConditionalOnMissingBean(DriftKitChatClient.class) @ConditionalOnBean({ChatModel.class, SpringAIChatClientFactory.class}) @ConditionalOnProperty( prefix = "driftkit.spring-ai", name = "chat-client.enabled", havingValue = "true", matchIfMissing = true ) public DriftKitChatClient driftKitChatClient(SpringAIChatClientFactory factory) { log.info("Creating DriftKitChatClient"); return factory.createChatClient(); } /** * Configuration for enhanced ChatClient with advisors */ @Configuration @ConditionalOnBean(ChatModel.class) @ConditionalOnProperty( prefix = "driftkit.spring-ai", name = "enhanced-chat-client.enabled", havingValue = "true", matchIfMissing = false ) public static class EnhancedChatClientConfiguration { @Bean @ConditionalOnMissingBean(name = "driftKitEnhancedChatClient") public ChatClient driftKitEnhancedChatClient( SpringAIChatClientFactory factory, ChatModel chatModel, DriftKitSpringAIProperties properties) { log.info("Creating enhanced ChatClient with DriftKit integration"); // Create ChatClient builder with ChatModel ChatClient.Builder builder = ChatClient.builder(chatModel); // Add default system message if configured if (properties.getDefaultSystemMessage() != null) { builder.defaultSystem(properties.getDefaultSystemMessage()); } // Use factory to apply advisors and configuration return factory.createSpringAIChatClient(builder); } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai-starter/0.8.1/ai/driftkit/context/springai
java-sources/ai/driftkit/driftkit-context-engineering-spring-ai-starter/0.8.1/ai/driftkit/context/springai/autoconfigure/DriftKitSpringAIProperties.java
package ai.driftkit.context.springai.autoconfigure; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Configuration properties for DriftKit Spring AI integration */ @Data @ConfigurationProperties(prefix = "driftkit.spring-ai") public class DriftKitSpringAIProperties { /** * Application name for tracing */ private String applicationName = "spring-ai-app"; /** * Default system message for ChatClient */ private String defaultSystemMessage; /** * Tracing configuration */ private TracingProperties tracing = new TracingProperties(); /** * Memory configuration */ private MemoryProperties memory = new MemoryProperties(); /** * Logging configuration */ private LoggingProperties logging = new LoggingProperties(); /** * Chat client configuration */ private ChatClientProperties chatClient = new ChatClientProperties(); /** * Enhanced chat client configuration */ private EnhancedChatClientProperties enhancedChatClient = new EnhancedChatClientProperties(); @Data public static class TracingProperties { /** * Enable tracing for Spring AI calls */ private boolean enabled = true; } @Data public static class MemoryProperties { /** * Enable chat memory advisor */ private boolean enabled = false; /** * Maximum messages to keep in memory */ private int maxMessages = 20; } @Data public static class LoggingProperties { /** * Enable logging advisor */ private boolean enabled = false; } @Data public static class ChatClientProperties { /** * Enable DriftKitChatClient bean creation */ private boolean enabled = true; } @Data public static class EnhancedChatClientProperties { /** * Enable enhanced ChatClient bean creation */ private boolean enabled = false; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/config/ApplicationContextProvider.java
package ai.driftkit.context.spring.config; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component("promptContextProvider") public class ApplicationContextProvider implements ApplicationContextAware { private static ApplicationContext context; /** * Sets the ApplicationContext. Called by Spring during context initialization. * * @param applicationContext the Spring ApplicationContext */ @Override public void setApplicationContext(ApplicationContext applicationContext) { context = applicationContext; } /** * Retrieves the stored ApplicationContext. * * @return the Spring ApplicationContext */ public static ApplicationContext getApplicationContext() { if (context == null) { throw new IllegalStateException("ApplicationContext has not been initialized yet."); } return context; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/config/EtlConfigProperties.java
package ai.driftkit.context.spring.config; import ai.driftkit.config.EtlConfig; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @Configuration public class EtlConfigProperties { @Bean @ConditionalOnMissingBean @ConfigurationProperties(prefix = "driftkit") public EtlConfig etlConfig() { return new EtlConfig(); } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/config/PromptServiceAutoConfiguration.java
package ai.driftkit.context.spring.config; import ai.driftkit.config.EtlConfig; import ai.driftkit.context.core.registry.PromptServiceRegistry; import ai.driftkit.context.core.service.DictionaryItemService; import ai.driftkit.context.core.service.PromptService; import ai.driftkit.context.spring.service.SpringDictionaryItemService; import ai.driftkit.context.spring.service.PromptServiceSpringAdapter; import ai.driftkit.context.spring.repository.SpringDictionaryItemRepository; import ai.driftkit.contextengineering.autoconfigure.WebMvcConfiguration; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import java.util.HashMap; import java.util.Map; /** * Auto-configuration for DriftKit Context Engineering module. * * This configuration automatically sets up: * - Component scanning for context engineering services * - MongoDB repositories for context persistence * - Default EtlConfig with prompt service configuration * - DictionaryItemService implementation * - PromptService implementation */ @Slf4j @AutoConfiguration(after = ai.driftkit.config.autoconfigure.EtlConfigAutoConfiguration.class) @ComponentScan(basePackages = { "ai.driftkit.context.spring.service", "ai.driftkit.context.spring.repository", "ai.driftkit.context.spring.config", "ai.driftkit.context.spring.controller", "ai.driftkit.context.spring.testsuite" }) @EnableMongoRepositories(basePackages = { "ai.driftkit.context.spring.repository", "ai.driftkit.context.spring.testsuite.repository" }) @Import(WebMvcConfiguration.class) public class PromptServiceAutoConfiguration { private final PromptService promptService; public PromptServiceAutoConfiguration(@Autowired(required = false) PromptService promptService) { this.promptService = promptService; } @PostConstruct public void registerPromptService() { if (promptService != null) { PromptServiceRegistry.register(promptService); log.info("Auto-registered PromptService with global registry: {}", promptService.getClass().getSimpleName()); } } @PreDestroy public void unregisterPromptService() { if (promptService != null) { PromptServiceRegistry.unregister(); log.debug("Unregistered PromptService from global registry"); } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/controller/DictionaryController.java
package ai.driftkit.context.spring.controller; import ai.driftkit.common.domain.Language; import ai.driftkit.common.domain.DictionaryItem; import ai.driftkit.common.domain.RestResponse; import ai.driftkit.context.core.service.DictionaryItemService; import ai.driftkit.context.core.service.DictionaryGroupService; import ai.driftkit.common.domain.DictionaryGroup; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; @Slf4j @Controller @RequestMapping(path = "/data/v1.0/admin/dictionary/") public class DictionaryController { @Autowired private DictionaryItemService dictionaryItemService; @Autowired private DictionaryGroupService dictionaryGroupService; @GetMapping("/") public @ResponseBody RestResponse<List<DictionaryItem>> getDictionaryItems( @RequestParam(required = false) Language language, @RequestParam(required = false) String groupId ) { List<DictionaryItem> items; if (StringUtils.isNotBlank(groupId)) { items = dictionaryItemService.findByGroupId(groupId); } else if (language != null) { items = dictionaryItemService.findByLanguage(language); } else { items = dictionaryItemService.findAll(); } return new RestResponse<>( true, items ); } @GetMapping("/{id}") public @ResponseBody RestResponse<DictionaryItem> getDictionaryItem(@PathVariable String id) { Optional<DictionaryItem> item = dictionaryItemService.findById(id); return new RestResponse<>( item.isPresent(), item.orElse(null) ); } @PostMapping("/text") public @ResponseBody RestResponse<DictionaryItem> updateDictionaryIdAsText( @RequestBody DictionaryTextData request ) { List<String> markers = splitText(request.getMarkers()); List<String> samples = splitText(request.getExamples()); fixRequest(request); Optional<DictionaryGroup> group = dictionaryGroupService.findById(request.getGroupId()); DictionaryItem item = dictionaryItemService.save(new DictionaryItem( request.id, request.index, request.groupId, request.name, group.map(DictionaryGroup::getLanguage).orElse(null), markers, samples, System.currentTimeMillis(), System.currentTimeMillis() )); return new RestResponse<>( true, item ); } @PostMapping("/texts") public @ResponseBody RestResponse<List<DictionaryItem>> updateDictionaryIdAsText( @RequestBody List<DictionaryTextData> request ) { List<DictionaryItem> result = new ArrayList<>(); for (DictionaryTextData data : request) { List<String> markers = splitText(data.getMarkers()); List<String> samples = splitText(data.getExamples()); fixRequest(data); Optional<DictionaryGroup> group = dictionaryGroupService.findById(data.getGroupId()); Language language = group.map(DictionaryGroup::getLanguage).orElse(null); DictionaryItem item = dictionaryItemService.save(new DictionaryItem( data.id, data.index, data.groupId, data.name, language, markers, samples, System.currentTimeMillis(), System.currentTimeMillis() )); result.add(item); } return new RestResponse<>( true, result ); } @PostMapping("/items") public @ResponseBody RestResponse<List<DictionaryItem>> updateDictionaryIdAsItems( @RequestBody List<DictionaryItem> items ) { Map<String, List<DictionaryItem>> group2items = items.stream().collect(Collectors.groupingBy(DictionaryItem::getGroupId)); for (Entry<String, List<DictionaryItem>> group2list : group2items.entrySet()) { if (StringUtils.isNotBlank(group2list.getKey())) { Optional<DictionaryGroup> byId = dictionaryGroupService.findById(group2list.getKey()); Language language = byId.map(DictionaryGroup::getLanguage).orElse(null); for (DictionaryItem item : group2list.getValue()) { item.setLanguage(language); } } } List<DictionaryItem> item = dictionaryItemService.saveAll(items); return new RestResponse<>(true, item); } @PostMapping("/") public @ResponseBody RestResponse<DictionaryItem> updateDictionaryIdAsData( @RequestBody DictionaryData request ) { List<String> markers = request.getMarkers(); List<String> samples = request.getExamples(); if (request.name == null) { request.name = request.id; } String groupId = request.getGroupId(); Language language = null; if (StringUtils.isNotBlank(groupId)) { Optional<DictionaryGroup> byId = dictionaryGroupService.findById(groupId); language = byId.map(DictionaryGroup::getLanguage).orElse(null); } DictionaryItem item = dictionaryItemService.save(new DictionaryItem( request.id, request.index, request.groupId, request.name, language, markers, samples, System.currentTimeMillis(), System.currentTimeMillis() )); return new RestResponse<>( true, item ); } private static List<String> splitText(String markerText) { if (StringUtils.isBlank(markerText)) { return null; } String lineBreak; if (markerText.contains(",")) { lineBreak = ","; } else if (markerText.contains("\n")) { lineBreak = "\n"; } else { return List.of(markerText); } List<String> result = new ArrayList<>(); String[] split = markerText.split(lineBreak); for (String s : split) { result.add(s.trim()); } return result; } @Data @NoArgsConstructor @AllArgsConstructor public static class DictionaryTextData { private String id; private int index; private String name; private String groupId; private String markers; private String examples; } @Data @NoArgsConstructor @AllArgsConstructor public static class DictionaryData { private String id; private int index; private String name; private String groupId; private List<String> markers; private List<String> examples; } private static void fixRequest(DictionaryTextData data) { if (data.name == null) { data.name = data.id; } if (data.id != null) { data.id = data.id.toLowerCase(Locale.ROOT); } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/controller/DictionaryGroupController.java
package ai.driftkit.context.spring.controller; import ai.driftkit.common.domain.Language; import ai.driftkit.common.domain.DictionaryGroup; import ai.driftkit.common.domain.RestResponse; import ai.driftkit.context.core.service.DictionaryGroupService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Locale; import java.util.Optional; @Slf4j @Controller @RequestMapping(path = "/data/v1.0/admin/dictionary/group") public class DictionaryGroupController { @Autowired private DictionaryGroupService dictionaryGroupService; @GetMapping("/") public @ResponseBody RestResponse<List<DictionaryGroup>> getGroups() { return new RestResponse<>(true, dictionaryGroupService.findAll()); } @GetMapping("/{id}") public @ResponseBody RestResponse<DictionaryGroup> getGroup(@PathVariable String id) { Optional<DictionaryGroup> group = dictionaryGroupService.findById(id); return new RestResponse<>(group.isPresent(), group.orElse(null)); } @PostMapping("/") public @ResponseBody RestResponse<DictionaryGroup> saveGroup(@RequestBody DictionaryGroup group) { fixGroup(group); DictionaryGroup savedGroup = dictionaryGroupService.save(group); return new RestResponse<>(true, savedGroup); } @DeleteMapping("/{id}") public @ResponseBody RestResponse<Boolean> deleteGroup(@PathVariable String id) { dictionaryGroupService.deleteById(id); return new RestResponse<>(true, true); } private void fixGroup(DictionaryGroup group) { if (group.getId() != null) { group.setId(group.getId().toLowerCase(Locale.ROOT)); } if (group.getLanguage() == null) { group.setLanguage(Language.GENERAL); } } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/controller/FolderController.java
package ai.driftkit.context.spring.controller; import ai.driftkit.context.spring.service.FolderService; import ai.driftkit.context.spring.testsuite.domain.Folder; import ai.driftkit.context.spring.testsuite.domain.FolderType; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/data/v1.0/admin/test-sets/folders") @RequiredArgsConstructor public class FolderController { private final FolderService folderService; @GetMapping public ResponseEntity<List<Folder>> getAllFolders() { List<Folder> folders = folderService.getFoldersByType(FolderType.TEST_SET); return ResponseEntity.ok(folders); } @GetMapping("/{id}") public ResponseEntity<Folder> getFolderById(@PathVariable String id) { return folderService.getFolderById(id) .map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } @PostMapping public ResponseEntity<Folder> createFolder(@RequestBody Folder folder) { folder.setType(FolderType.TEST_SET); // Ensure it's a TestSet folder return ResponseEntity.ok(folderService.createFolder(folder)); } @PutMapping("/{id}") public ResponseEntity<Folder> updateFolder(@PathVariable String id, @RequestBody Folder folder) { folder.setType(FolderType.TEST_SET); // Ensure it's a TestSet folder return folderService.updateFolder(id, folder) .map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteFolder(@PathVariable String id) { if (folderService.deleteFolder(id)) { return ResponseEntity.noContent().build(); } return ResponseEntity.notFound().build(); } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/controller/ParserController.java
package ai.driftkit.context.spring.controller; import ai.driftkit.vector.spring.domain.ContentType; import ai.driftkit.vector.spring.domain.ParsedContent; import ai.driftkit.vector.spring.parser.UnifiedParser.ByteArrayParserInput; import ai.driftkit.vector.spring.parser.UnifiedParser.YoutubeIdParserInput; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import ai.driftkit.vector.spring.service.ParserService; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; @Slf4j @Controller @RequestMapping(path = "/data/v1.0/admin/parse/") public class ParserController { @Autowired private ParserService parserService; @Operation(summary = "Upload a file") @PostMapping(value = "/file", consumes = { "multipart/form-data" }) public ResponseEntity<ParsedContent> uploadFile( @Parameter(description = "File to be uploaded", required = true) @RequestParam("file") MultipartFile file, @RequestParam(required = false) Boolean save, @RequestParam(required = false) Boolean metadata ) throws IOException { ByteArrayParserInput input = new ByteArrayParserInput( file.getBytes(), Optional.ofNullable(file.getOriginalFilename()).orElse(file.getName()), ContentType.fromString(file.getContentType()) ); ParsedContent result = parserService.parse( input, BooleanUtils.isNotFalse(save) ); if (BooleanUtils.isNotTrue(metadata)) { result.setMetadata(null); } return ResponseEntity.ofNullable(result); } @PostMapping(value = "/youtube") public ResponseEntity<ParsedContent> youtube( @RequestBody YoutubeInput input, @RequestParam(required = false) Boolean save ) throws IOException { List<String> languages = input.getLanguages() .stream() .flatMap(e -> Stream.of(e.split(","))) .map(String::trim) .collect(Collectors.toList()); String primaryLanguage = languages.remove(0); YoutubeIdParserInput youtube = new YoutubeIdParserInput(); youtube.setContentType(ContentType.YOUTUBE_TRANSCRIPT); youtube.setInput(languages); youtube.setVideoId(input.getVideoId()); youtube.setPrimaryLang(primaryLanguage); ParsedContent result = parserService.parse( youtube, BooleanUtils.isNotFalse(save) ); if (BooleanUtils.isNotTrue(input.getMetadata())) { result.setMetadata(null); } return ResponseEntity.ofNullable(result); } @Data @NoArgsConstructor @AllArgsConstructor public static class YoutubeInput { List<String> languages; String videoId; Boolean metadata; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/controller/PromptAppController.java
package ai.driftkit.context.spring.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class PromptAppController { // Redirects all routes from /prompt-engineering/* to the SPA index @GetMapping({ "/prompt-engineering", "/prompt-engineering/", "/prompt-engineering/chat/**", "/prompt-engineering/prompts/**", "/prompt-engineering/indexes/**", "/prompt-engineering/dictionaries/**", "/prompt-engineering/checklists/**" }) public String forwardToSpaIndex() { return "forward:/prompt-engineering/index.html"; } // Fallback route for any paths not explicitly handled @GetMapping("/{path:^(?!api|data|prompt-engineering).*$}") public String redirect() { return "forward:/"; } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/controller/PromptRestController.java
package ai.driftkit.context.spring.controller; import ai.driftkit.common.domain.CreatePromptRequest; import ai.driftkit.common.domain.Prompt; import ai.driftkit.context.core.service.PromptService; import ai.driftkit.common.domain.RestResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; @Slf4j @Controller @RequestMapping(path = "/data/v1.0/admin/prompt/") public class PromptRestController { @Autowired private PromptService promptService; @PostMapping("/create-if-not-exists") public @ResponseBody RestResponse<Prompt> createIfNotExists( @RequestBody CreatePromptRequest promptData ) { Prompt result = promptService.createIfNotExists( promptData.getMethod(), promptData.getMessage(), promptData.getSystemMessage(), promptData.isJsonResponse(), promptData.getLanguage(), BooleanUtils.isTrue(promptData.getForceRepoVersion()), promptData.getWorkflow() ); return new RestResponse<>( true, result ); } @GetMapping("/") public @ResponseBody RestResponse<List<Prompt>> getPrompt() { List<Prompt> prompts = promptService.getPrompts(); return new RestResponse<>( true, prompts ); } @DeleteMapping("/{id}") public @ResponseBody RestResponse<Prompt> deletePrompt(@PathVariable String id) { Prompt prompt = promptService.deletePrompt(id); return new RestResponse<>( true, prompt ); } @PostMapping("/list") public @ResponseBody RestResponse<List<Prompt>> getPrompt( @RequestBody List<Prompt> prompts ) { for (Prompt prompt : prompts) { promptService.savePrompt(prompt); } return new RestResponse<>( true, prompts ); } @PostMapping("/") public @ResponseBody RestResponse<Prompt> savePrompt( @RequestBody Prompt input ) { Prompt prompt = promptService.savePrompt(input); return new RestResponse<>( true, prompt ); } @GetMapping("/{method}") public @ResponseBody RestResponse<Prompt> getPrompt( @PathVariable String method ) { Prompt prompt = promptService.getCurrentPromptOrThrow(method); return new RestResponse<>( true, prompt ); } @GetMapping("/byIds") public @ResponseBody RestResponse<List<Prompt>> getPromptsByIds( @RequestParam String ids ) { String[] promptIds = ids.split(","); List<String> idList = List.of(promptIds); List<Prompt> prompts = promptService.getPromptsByIds(idList); return new RestResponse<>( true, prompts ); } }
0
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring
java-sources/ai/driftkit/driftkit-context-engineering-spring-boot-starter/0.8.1/ai/driftkit/context/spring/domain/DictionaryGroupDocument.java
package ai.driftkit.context.spring.domain; import ai.driftkit.common.domain.DictionaryGroup; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "dictionary_groups") public class DictionaryGroupDocument extends DictionaryGroup { @Id @Override public String getId() { return super.getId(); } }