### Generate Text Embeddings with DeepSeek4J (Java) Source: https://context7.com/pig-mesh/deepseek4j/llms.txt Java examples demonstrating how to use the EmbeddingClient from the DeepSeek4J library. It covers generating embeddings for single text inputs and batch processing multiple texts. The examples also show how to access embedding details and token usage from the response. ```java import io.github.pigmesh.ai.deepseek.core.EmbeddingClient; import io.github.pigmesh.ai.deepseek.core.embedding.*; import java.util.List; import java.util.ArrayList; public class EmbeddingExample { @Autowired private EmbeddingClient embeddingClient; public void generateEmbeddings() { // Simple embedding for single text List embedding = embeddingClient.embed( "DeepSeek is a powerful AI model" ); System.out.println("Embedding dimension: " + embedding.size()); System.out.println("First 5 values: " + embedding.subList(0, 5)); } public void batchEmbeddings() { // Batch embedding for multiple texts EmbeddingRequest request = EmbeddingRequest.builder() .model(EmbeddingModel.BGE_M3) .input( "Artificial intelligence is transforming technology", "Machine learning enables computers to learn from data", "Deep learning uses neural networks" ) .dimensions(1024) // Optional: specify output dimensions .build(); EmbeddingResponse response = embeddingClient.embed(request); // Process each embedding List embeddings = response.data(); for (int i = 0; i < embeddings.size(); i++) { Embedding emb = embeddings.get(i); System.out.println("Text " + (i + 1) + " embedding index: " + emb.index()); System.out.println("Vector dimension: " + emb.embedding().size()); } // Token usage Usage usage = response.usage(); System.out.println("Tokens used: " + usage.totalTokens()); } public double cosineSimilarity(List vec1, List vec2) { double dotProduct = 0.0; double norm1 = 0.0; double norm2 = 0.0; for (int i = 0; i < vec1.size(); i++) { dotProduct += vec1.get(i) * vec2.get(i); norm1 += vec1.get(i) * vec1.get(i); norm2 += vec2.get(i) * vec2.get(i); } return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2)); } public void semanticSearch() { // Query and documents String query = "What is machine learning?"; List documents = List.of( "Machine learning is a subset of AI", "Python is a programming language", "Neural networks are used in deep learning" ); // Generate embeddings List queryEmbedding = embeddingClient.embed(query); List similarities = new ArrayList<>(); for (String doc : documents) { List docEmbedding = embeddingClient.embed(doc); double similarity = cosineSimilarity(queryEmbedding, docEmbedding); similarities.add(similarity); } // Find most similar document int maxIndex = 0; double maxSimilarity = similarities.get(0); for (int i = 1; i < similarities.size(); i++) { if (similarities.get(i) > maxSimilarity) { maxSimilarity = similarities.get(i); maxIndex = i; } } System.out.println("Query: " + query); System.out.println("Most similar: " + documents.get(maxIndex)); System.out.println("Similarity: " + maxSimilarity); } } ``` -------------------------------- ### Java SSE Stream Chat Completion with DeepSeekClient Source: https://github.com/pig-mesh/deepseek4j/blob/main/README.md This Java code example shows how to use the DeepSeekClient to perform a chat completion with Server-Sent Events (SSE) streaming. It returns a Flux of ChatCompletionResponse, enabling real-time updates in your application. It requires the DeepSeekClient to be injected. ```java @Autowired private DeepSeekClient deepSeekClient; // sse 流式返回 @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux chat(String prompt) { return deepSeekClient.chatFluxCompletion(prompt); } ``` -------------------------------- ### Initialize Vue App with SSE, Theme, and Message State Management (JavaScript) Source: https://github.com/pig-mesh/deepseek4j/blob/main/sse.html Initializes the Vue.js application using create.mount. It sets up reactive state for Server-Sent Events (SSE) connection status, theme toggling, and message management. It also exposes functions to connect/disconnect from SSE and clear messages. ```javascript const { createApp, ref } = Vue const app = createApp({ setup() { const sseUrl = ref('http://localhost:8080/stream') const messages = ref([]) const isConnected = ref(false) const currentTheme = ref('light') const toggleTheme = () => { currentTheme.value = currentTheme.value === 'light' ? 'dark' : 'light' } const connect = () => { console.log('Connecting to SSE...') const eventSource = new EventSource(sseUrl.value) eventSource.onopen = () => { isConnected.value = true console.log('SSE connection opened') } eventSource.onmessage = (event) => { messages.value.push(JSON.parse(event.data)) console.log('Message received:', event.data) } eventSource.onerror = (error) => { isConnected.value = false console.error('SSE error:', error) eventSource.close() } } const disconnect = () => { console.log('Disconnecting from SSE...') // Assuming eventSource is accessible here, which might require it to be a global or passed around // For simplicity in this example, a placeholder. In a real app, manage the EventSource instance properly. isConnected.value = false console.log('SSE disconnected') } const clearMessages = () => { messages.value = [] } return { sseUrl, messages, isConnected, currentTheme, toggleTheme, connect, disconnect, clearMessages } } }).mount('#app') ``` -------------------------------- ### Configure DeepSeek Embedding API (YAML) Source: https://context7.com/pig-mesh/deepseek4j/llms.txt Configuration for the DeepSeek embedding API, including API key, base URL, model selection, and request logging. This file is essential for initializing the embedding client. ```yaml embedding: api-key: sk-your-embedding-api-key base-url: https://api.deepseek.com/v1 model: bge-m3 log-requests: false ``` -------------------------------- ### Add Maven Dependency for deepseek4j Source: https://github.com/pig-mesh/deepseek4j/blob/main/README.md This snippet shows how to add the deepseek-spring-boot-starter dependency to your Maven project's pom.xml file. This is the first step to integrate deepseek4j into your Spring Boot application. ```xml io.github.pig-mesh.ai deepseek-spring-boot-starter 1.4.7 ``` -------------------------------- ### Java Chat Completion with Reasoning Source: https://context7.com/pig-mesh/deepseek4j/llms.txt This Java code demonstrates how to use the DeepSeek client to perform chat completions with reasoning enabled. It shows how to build a request, execute it, and then extract the reasoning process, the final answer, and detailed token usage from the response. Ensure the DeepSeek client library is correctly configured and accessible. ```java import io.github.pigmesh.ai.deepseek.core.chat.*; import io.github.pigmesh.ai.deepseek.core.shared.Usage; public class ReasoningExample { public void demonstrateReasoning(DeepSeekClient client) { // Build request with reasoning enabled ChatCompletionRequest request = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_REASONER) .addSystemMessage("You are a mathematical problem solver.") .addUserMessage("Solve this problem: If a train travels 120 miles in 2 hours, how long will it take to travel 300 miles at the same speed?") .temperature(1.0) .maxCompletionTokens(8000) .includeReasoning(true) // Enable reasoning output .build(); // Execute and get full response ChatCompletionResponse response = client .chatCompletion(new OpenAiClientContext(), request) .execute(); // Access the first choice ChatCompletionChoice choice = response.choices().get(0); AssistantMessage message = choice.message(); // Get reasoning content (thought process) String reasoning = message.reasoning(); System.out.println("Reasoning process: " + reasoning); // Get final answer String answer = message.content(); System.out.println("Answer: " + answer); // Get token usage with billing details Usage usage = response.usage(); System.out.println("Prompt tokens: " + usage.promptTokens()); System.out.println("Completion tokens: " + usage.completionTokens()); System.out.println("Total tokens: " + usage.totalTokens()); // Access detailed token breakdown if (usage.promptTokensDetails() != null) { System.out.println("Cached tokens: " + usage.promptTokensDetails().cachedTokens()); } if (usage.completionTokensDetails() != null) { System.out.println("Reasoning tokens: " + usage.completionTokensDetails().reasoningTokens()); } } } ``` -------------------------------- ### Java Function Calling with Deepseek4j Client Source: https://context7.com/pig-mesh/deepseek4j/llms.txt Demonstrates defining a 'get_weather' function, creating a tool, building a chat completion request with the tool, executing the request, and processing the AI's tool call. It includes simulating function execution and sending the result back to the model for a final answer. Requires Deepseek4j core and Jackson libraries. ```java import io.github.pigmesh.ai.deepseek.core.chat.*; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class FunctionCallingExample { private final ObjectMapper objectMapper = new ObjectMapper(); public void demonstrateFunctionCalling(DeepSeekClient client) { // Define a weather function Function weatherFunction = Function.builder() .name("get_weather") .description("Get the current weather in a location") .parameters(JsonObjectSchema.builder() .addProperty("location", JsonStringSchema.builder() .description("The city name, e.g., San Francisco") .build()) .addProperty("unit", JsonEnumSchema.builder() .enumValues("celsius", "fahrenheit") .description("Temperature unit") .build()) .required("location") .build()) .build(); // Create tool from function Tool weatherTool = Tool.from(weatherFunction); // Build request with tools ChatCompletionRequest request = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .addUserMessage("What's the weather like in Tokyo?") .tools(weatherTool) .toolChoice(ToolChoiceMode.AUTO) .build(); // Execute request ChatCompletionResponse response = client .chatCompletion(new OpenAiClientContext(), request) .execute(); // Process tool calls AssistantMessage assistantMessage = response.choices().get(0).message(); if (assistantMessage.toolCalls() != null && !assistantMessage.toolCalls().isEmpty()) { for (ToolCall toolCall : assistantMessage.toolCalls()) { String functionName = toolCall.function().name(); String arguments = toolCall.function().arguments(); System.out.println("Function called: " + functionName); System.out.println("Arguments: " + arguments); // Execute the function String result = executeFunction(functionName, arguments); // Send result back to model ChatCompletionRequest followUp = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .addUserMessage("What's the weather like in Tokyo?") .addAssistantMessage(assistantMessage.content()) .addToolMessage(toolCall.id(), result) .build(); ChatCompletionResponse finalResponse = client .chatCompletion(new OpenAiClientContext(), followUp) .execute(); System.out.println("Final answer: " + finalResponse.content()); } } } private String executeFunction(String functionName, String arguments) { try { if ("get_weather".equals(functionName)) { Map params = objectMapper.readValue( arguments, Map.class ); String location = (String) params.get("location"); String unit = (String) params.getOrDefault("unit", "celsius"); // Simulate weather API call return String.format( "{\"location\": \"%s\", \"temperature\": 22, \"unit\": \"%s\", \"condition\": \"sunny\"}", location, unit ); } } catch (Exception e) { return "{\"error\": \"" + e.getMessage() + "\"}"; } return "{}"; } } ``` -------------------------------- ### Java: Programmatically Configure DeepSeek AI Client with Proxy and Timeouts Source: https://context7.com/pig-mesh/deepseek4j/llms.txt Builds a DeepSeekClient instance programmatically with custom configurations, including API key, base URL, model, proxy settings, various timeouts (connect, read, call), logging levels, and system prompts. This allows for fine-grained control over the client's behavior and network settings. ```java import io.github.pigmesh.ai.deepseek.core.DeepSeekClient; import io.github.pigmesh.ai.deepseek.core.DeepSeekConfig; import io.github.pigmesh.ai.deepseek.core.LogLevel; import io.github.pigmesh.ai.deepseek.core.chat.*; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; public class DeepSeekClientExample { public static DeepSeekClient createClient() { // Create proxy if needed Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080) ); // Build client with custom configuration return DeepSeekClient.builder() .openAiApiKey("sk-your-api-key") .baseUrl("https://api.deepseek.com/v1") .model(ChatCompletionModel.DEEPSEEK_REASONER.getValue()) .proxy(proxy) .connectTimeout(Duration.ofSeconds(30)) .readTimeout(Duration.ofSeconds(60)) .callTimeout(Duration.ofSeconds(120)) .logRequests(true) .logResponses(true) .logLevel(LogLevel.DEBUG) .systemMessage("You are a helpful AI assistant.") .searchApiKey("your-search-api-key") .build(); } public static void main(String[] args) { DeepSeekClient client = createClient(); try { // Use the client String response = client.chatCompletion( new OpenAiClientContext(), "Explain quantum computing in simple terms" ).execute(); System.out.println(response); } finally { // Clean up resources client.shutdown(); } } } ``` -------------------------------- ### Java: List Available DeepSeek Models Source: https://context7.com/pig-mesh/deepseek4j/llms.txt This Java code demonstrates how to retrieve and display a list of available models supported by the DeepSeek API. It iterates through the `ModelsResponse` object, printing the `id`, `ownedBy`, and `created` timestamp for each model. Error handling is included for potential exceptions during the API call. ```java import io.github.pigmesh.ai.deepseek.core.OpenAiHttpException; import io.github.pigmesh.ai.deepseek.core.moderation.*; import java.util.concurrent.TimeoutException; public class ErrorHandlingExample { // ... handleErrors and moderateContent methods public void listAvailableModels(DeepSeekClient client) { try { ModelsResponse models = client.models(); System.out.println("Available models:"); models.data().forEach(model -> { System.out.println(" - " + model.id()); System.out.println(" Owned by: " + model.ownedBy()); System.out.println(" Created: " + model.created()); }); } catch (Exception e) { System.err.println("Failed to list models: " + e.getMessage()); } } } ``` -------------------------------- ### Java Multi-turn Conversation with DeepSeek4J Source: https://context7.com/pig-mesh/deepseek4j/llms.txt This Java code demonstrates how to manage context across multiple turns in a conversation using the DeepSeekClient. It involves creating a list of messages (system, user, assistant) and sending them in subsequent requests to maintain conversational history. Dependencies include the DeepSeek4J core chat library. The input is a list of messages and the output is the assistant's response. ```java import io.github.pigmesh.ai.deepseek.core.chat.*; import java.util.ArrayList; import java.util.List; public class ConversationExample { public void multiTurnConversation(DeepSeekClient client) { List conversationHistory = new ArrayList<>(); // Initial system message conversationHistory.add(SystemMessage.from( "You are a helpful coding assistant specializing in Java." )); // First turn conversationHistory.add(UserMessage.from( "How do I read a file in Java?" )); ChatCompletionRequest request1 = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .messages(conversationHistory) .temperature(0.7) .build(); ChatCompletionResponse response1 = client .chatCompletion(new OpenAiClientContext(), request1) .execute(); String answer1 = response1.content(); System.out.println("Assistant: " + answer1); // Add assistant's response to history conversationHistory.add(AssistantMessage.from(answer1)); // Second turn conversationHistory.add(UserMessage.from( "Can you show me an example with error handling?" )); ChatCompletionRequest request2 = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .messages(conversationHistory) .temperature(0.7) .build(); ChatCompletionResponse response2 = client .chatCompletion(new OpenAiClientContext(), request2) .execute(); String answer2 = response2.content(); System.out.println("Assistant: " + answer2); // Continue conversation as needed... } public void conversationWithContext(DeepSeekClient client) { // Using builder pattern for cleaner code ChatCompletionRequest request = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .addSystemMessage("You are a travel guide.") .addUserMessage("I want to visit Japan") .addAssistantMessage("Japan is a wonderful destination! What would you like to know?") .addUserMessage("What's the best time to visit?") .temperature(0.8) .maxCompletionTokens(2000) .build(); String response = client .chatCompletion(new OpenAiClientContext(), request) .execute() .content(); System.out.println(response); } } ``` -------------------------------- ### Spring Boot: Configure DeepSeek AI API Key and Model Source: https://context7.com/pig-mesh/deepseek4j/llms.txt Configure the DeepSeek AI API key, model, logging, and timeouts for Spring Boot applications. This YAML configuration sets up the necessary parameters for the DeepSeekClient to interact with the AI service. ```yaml # application.yml deepseek: api-key: sk-your-api-key-here model: deepseek-reasoner log-requests: true log-responses: true connect-timeout: 30 read-timeout: 60 call-timeout: 120 ``` -------------------------------- ### Spring Boot: Implement Streaming and Synchronous Chat Completion Source: https://context7.com/pig-mesh/deepseek4j/llms.txt Demonstrates how to use the DeepSeekClient within a Spring Boot application for both streaming and synchronous chat completions. The streaming endpoint produces Server-Sent Events (SSE), while the synchronous endpoint returns a direct string response. Requires the deepseek-spring-boot-starter Maven dependency. ```java import io.github.pigmesh.ai.deepseek.core.DeepSeekClient; import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse; import org.springframework.web.bind.annotation.*; import org.springframework.http.MediaType; import reactor.core.publisher.Flux; @RestController @RequestMapping("/api") public class ChatController { @Autowired private DeepSeekClient deepSeekClient; // Streaming SSE endpoint @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux chat(@RequestParam String prompt) { return deepSeekClient.chatFluxCompletion(prompt); } // Synchronous completion @PostMapping("/chat/sync") public String chatSync(@RequestBody String message) { ChatCompletionRequest request = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_REASONER) .addUserMessage(message) .temperature(0.7) .maxCompletionTokens(4000) .build(); ChatCompletionResponse response = deepSeekClient .chatCompletion(new OpenAiClientContext(), request) .execute(); return response.content(); } } ``` -------------------------------- ### Tailwind CSS DaisyUI Theme Configuration Source: https://github.com/pig-mesh/deepseek4j/blob/main/sse.html Configuration for Tailwind CSS to enable DaisyUI theming. It defines 'light' and 'dark' themes with custom color palettes for primary, secondary, accent, neutral, and base elements. Includes CSS for dark mode scrollbar styling. ```javascript tailwind.config = { daisyui: { themes: [{ light: { "primary": "#570DF8", "primary-focus": "#4506CB", "secondary": "#F000B8", "accent": "#37CDBE", "neutral": "#3D4451", "base-100": "#FFFFFF", "base-200": "#F2F2F2", "base-300": "#E5E6E6", "base-content": "#1F2937", "info": "#3ABFF8", "success": "#36D399", "warning": "#FBBD23", "error": "#F87272" }, dark: { "primary": "#BB86FC", "primary-focus": "#9965E3", "secondary": "#03DAC6", "accent": "#BB86FC", "neutral": "#121212", "base-100": "#1E1E1E", "base-200": "#2C2C2C", "base-300": "#242424", "base-content": "#E1E1E1", "info": "#0175C2", "success": "#00C853", "warning": "#FFB74D", "error": "#CF6679" } }], } } /* 暗色模式下的滚动条样式 */ [data-theme='dark'] ::-webkit-scrollbar { width: 8px; height: 8px; } [data-theme='dark'] ::-webkit-scrollbar-track { background: #2C2C2C; border-radius: 4px; } [data-theme='dark'] ::-webkit-scrollbar-thumb { background: #424242; border-radius: 4px; } [data-theme='dark'] ::-webkit-scrollbar-thumb:hover { background: #505050; } ``` -------------------------------- ### Java DeepSeek Web Search Chat Completion Source: https://context7.com/pig-mesh/deepseek4j/llms.txt Integrates DeepSeek's web search for enhanced chat completions. It takes a user query, performs a search, and returns a chat response incorporating search results. The code uses Reactor's Flux for asynchronous stream processing. It handles responses and errors, printing content as it arrives. ```java import io.github.pigmesh.ai.deepseek.core.search.*; import reactor.core.publisher.Flux; public class WebSearchExample { public void searchAndChat(DeepSeekClient client) { // Simple search integration String query = "What are the latest developments in quantum computing?"; Flux stream = client.chatSearchCompletion(query); stream.subscribe( response -> { if (!response.choices().isEmpty()) { String content = response.choices().get(0).delta().content(); if (content != null) { System.out.print(content); } } }, error -> System.err.println("Error: " + error), () -> System.out.println("\n\nSearch-enhanced response complete") ); } public void customSearchRequest(DeepSeekClient client) { // Custom search configuration SearchRequest searchRequest = SearchRequest.builder() .enable(true) .query("AI breakthroughs 2024") .freshness(FreshnessEnums.PAST_MONTH) .summary(true) .count(10) .page(1) .build(); String userQuery = "Summarize recent AI advancements"; Flux stream = client.chatSearchCompletion( userQuery, searchRequest ); StringBuilder result = new StringBuilder(); stream.subscribe( response -> { if (!response.choices().isEmpty()) { String content = response.choices().get(0).delta().content(); if (content != null) { result.append(content); } } }, error -> System.err.println("Search failed: " + error), () -> System.out.println("Result: " + result.toString()) ); } public void nonStreamingSearch(DeepSeekClient client) { // Non-streaming search completion String query = "Explain blockchain technology"; client.chatSearchStreamingCompletion(query) .onPartialResponse(chunk -> { System.out.print(chunk.choices().get(0).delta().content()); }) .onComplete(() -> System.out.println("\nDone")) .execute(); } } ``` -------------------------------- ### Java Streaming Chat Completion with Project Reactor Source: https://context7.com/pig-mesh/deepseek4j/llms.txt Implements real-time streaming of chat completions using Project Reactor's Flux. It processes each received chunk of the response, appends the content, and prints it to the console. This method is suitable for basic streaming scenarios where immediate feedback is desired. ```java import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; import java.util.concurrent.atomic.AtomicReference; public class StreamingExample { public void streamChatCompletion(DeepSeekClient client) { // Simple streaming Flux stream = client.chatFluxCompletion( "Write a short story about a robot learning to paint" ); StringBuilder fullResponse = new StringBuilder(); stream.subscribe( chunk -> { // Process each chunk if (!chunk.choices().isEmpty()) { Delta delta = chunk.choices().get(0).delta(); if (delta != null && delta.content() != null) { fullResponse.append(delta.content()); System.out.print(delta.content()); } } }, error -> System.err.println("Error: " + error.getMessage()), () -> System.out.println("\n\nStreaming completed!") ); } public void advancedStreamingWithRequest(DeepSeekClient client) { // Streaming with custom request ChatCompletionRequest request = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .addSystemMessage("You are a creative writing assistant.") .addUserMessage("Generate a haiku about autumn") .temperature(0.9) .maxCompletionTokens(100) .build(); Flux stream = client.chatFluxCompletion(request); stream .subscribeOn(Schedulers.boundedElastic()) .doOnNext(response -> { // Log metadata System.out.println("Model: " + response.model()); System.out.println("ID: " + response.id()); }) .map(response -> { if (!response.choices().isEmpty()) { return response.choices().get(0).delta().content(); } return ""; }) .filter(content -> content != null && !content.isEmpty()) .collectList() .subscribe(chunks -> { String complete = String.join("", chunks); System.out.println("Complete response: " + complete); }); } public void nonReactiveStreaming(DeepSeekClient client) { // Using callback-based streaming ChatCompletionRequest request = ChatCompletionRequest.builder() .addUserMessage("Count from 1 to 10") .build(); client.chatCompletion(new OpenAiClientContext(), request) .onPartialResponse(response -> { // Called for each chunk System.out.print(response.choices().get(0).delta().content()); }) .onComplete(() -> System.out.println("\nDone!")) .onError(error -> System.err.println("Error: " + error)) .execute(); } } ``` -------------------------------- ### Configure DeepSeek API Key in Spring Boot Source: https://github.com/pig-mesh/deepseek4j/blob/main/README.md This snippet demonstrates how to configure your DeepSeek API key in your Spring Boot application's configuration file (application.yml or application.properties). This is essential for authenticating your requests to the DeepSeek API. ```yaml deepseek: api-key: your-api-key-here ``` -------------------------------- ### Generate Structured JSON Output with DeepSeek4j Source: https://context7.com/pig-mesh/deepseek4j/llms.txt This Java code defines a JSON schema for a recipe and uses the DeepSeekClient to request a recipe in that structured format. It parses the JSON response and prints the recipe details. This approach ensures that the model's output adheres to a specific structure, which is useful for downstream processing. Dependencies include DeepSeek client libraries and Jackson for JSON processing. ```java import io.github.pigmesh.ai.deepseek.core.chat.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class StructuredOutputExample { private final ObjectMapper objectMapper = new ObjectMapper(); public void extractStructuredData(DeepSeekClient client) throws Exception { // Define JSON schema for response JsonObjectSchema schema = JsonObjectSchema.builder() .name("recipe") .description("A cooking recipe with ingredients and steps") .addProperty("name", JsonStringSchema.builder() .description("Recipe name") .build()) .addProperty("servings", JsonIntegerSchema.builder() .description("Number of servings") .build()) .addProperty("ingredients", JsonArraySchema.builder() .items(JsonObjectSchema.builder() .addProperty("item", JsonStringSchema.builder().build()) .addProperty("amount", JsonStringSchema.builder().build()) .build()) .build()) .addProperty("steps", JsonArraySchema.builder() .items(JsonStringSchema.builder().build()) .build()) .required("name", "servings", "ingredients", "steps") .additionalProperties(false) .strict(true) .build(); // Create response format ResponseFormat responseFormat = ResponseFormat.builder() .type(ResponseFormatType.JSON_SCHEMA) .jsonSchema(schema) .build(); // Build request ChatCompletionRequest request = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .addUserMessage("Give me a recipe for chocolate chip cookies") .responseFormat(responseFormat) .temperature(0.7) .build(); // Execute and parse JSON ChatCompletionResponse response = client .chatCompletion(new OpenAiClientContext(), request) .execute(); String jsonContent = response.content(); JsonNode recipe = objectMapper.readTree(jsonContent); System.out.println("Recipe: " + recipe.get("name").asText()); System.out.println("Servings: " + recipe.get("servings").asInt()); System.out.println("\nIngredients:"); recipe.get("ingredients").forEach(ingredient -> { System.out.println(" - " + ingredient.get("amount").asText() + " " + ingredient.get("item").asText()); }); System.out.println("\nSteps:"); recipe.get("steps").forEach(step -> { System.out.println(" " + step.asText()); }); } public void simpleJsonMode(DeepSeekClient client) { // Simple JSON mode without strict schema ChatCompletionRequest request = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .addUserMessage("List 3 programming languages with their main use cases") .responseFormat(ResponseFormatType.JSON_OBJECT) .build(); ChatCompletionResponse response = client .chatCompletion(new OpenAiClientContext(), request) .execute(); System.out.println("JSON Response: " + response.content()); } } ``` -------------------------------- ### Java: Moderate User Content with DeepSeek Source: https://context7.com/pig-mesh/deepseek4j/llms.txt This Java code snippet illustrates how to use the DeepSeek client to moderate user-provided content before processing it. It sends the input to the moderation endpoint and checks if the content is flagged for policy violations. If flagged, it prints specific category warnings; otherwise, it proceeds to generate a chat completion response. ```java import io.github.pigmesh.ai.deepseek.core.OpenAiHttpException; import io.github.pigmesh.ai.deepseek.core.moderation.*; import java.util.concurrent.TimeoutException; public class ErrorHandlingExample { // ... handleErrors method public void moderateContent(DeepSeekClient client) { String userInput = "User provided content to check"; // Check content for policy violations ModerationRequest moderationRequest = ModerationRequest.builder() .input(userInput) .model(ModerationModel.TEXT_MODERATION_LATEST) .build(); try { ModerationResponse modResponse = client .moderation(new OpenAiClientContext(), moderationRequest) .execute(); ModerationResult result = modResponse.results().get(0); if (result.flagged()) { System.out.println("Content flagged!"); Categories categories = result.categories(); CategoryScores scores = result.categoryScores(); if (categories.hate()) { System.out.println("Hate speech detected (score: " + scores.hate() + ")"); } // Check other categories... return; // Don't process flagged content } // Content is safe, proceed with chat ChatCompletionRequest chatRequest = ChatCompletionRequest.builder() .addUserMessage(userInput) .build(); String response = client .chatCompletion(new OpenAiClientContext(), chatRequest) .execute() .content(); System.out.println("Response: " + response); } catch (Exception e) { System.err.println("Moderation failed: " + e.getMessage()); } } // ... listAvailableModels method } ``` -------------------------------- ### Java: Handle DeepSeek API Errors and Timeouts Source: https://context7.com/pig-mesh/deepseek4j/llms.txt This Java code demonstrates how to handle various errors when interacting with the DeepSeek API. It includes catching specific `OpenAiHttpException` for API-related issues (like status codes and error codes), `TimeoutException` for network or server response delays, and a general `Exception` for any other unexpected errors. It also checks the `finishReason` in the response for potential content truncation or filtering. ```java import io.github.pigmesh.ai.deepseek.core.OpenAiHttpException; import io.github.pigmesh.ai.deepseek.core.moderation.*; import java.util.concurrent.TimeoutException; public class ErrorHandlingExample { public void handleErrors(DeepSeekClient client) { try { ChatCompletionRequest request = ChatCompletionRequest.builder() .model(ChatCompletionModel.DEEPSEEK_CHAT) .addUserMessage("Hello, how are you?") .build(); ChatCompletionResponse response = client .chatCompletion(new OpenAiClientContext(), request) .execute(); // Check finish reason String finishReason = response.choices().get(0).finishReason(); if ("length".equals(finishReason)) { System.out.println("Warning: Response truncated due to length limit"); } else if ("content_filter".equals(finishReason)) { System.out.println("Warning: Content filtered"); } System.out.println(response.content()); } catch (OpenAiHttpException e) { // API-specific errors System.err.println("API Error: " + e.getMessage()); System.err.println("Status code: " + e.statusCode()); System.err.println("Error code: " + e.code()); } catch (TimeoutException e) { System.err.println("Request timed out"); } catch (Exception e) { System.err.println("Unexpected error: " + e.getMessage()); } } // ... other methods in the class } ``` -------------------------------- ### Vue.js SSE Debugging Component Source: https://github.com/pig-mesh/deepseek4j/blob/main/sse.html A Vue.js component for debugging Server-Sent Events (SSE) connections. It allows users to connect to an SSE URL, display incoming messages, parse them into structured data (including reasoning chains), and manage the connection state. It also handles theme switching and scrolling to the bottom of message containers. ```javascript const { createApp, ref, computed, watch, nextTick, onMounted } = Vue createApp({ setup() { const sseUrl = ref('http://127.0.0.1:8080/chat?prompt=新能源汽车优势在哪里?') const messages = ref([]) const isConnected = ref(false) const currentTheme = ref('light') const isInThinkTag = ref(false) let eventSource = null const reasoningRef = ref(null) const answerRef = ref(null) // 计算推理过程(思考链) const reasoningChain = computed(() => { return messages.value .filter(m => m.parsed?.reasoning_content) .map(m => m.parsed.reasoning_content) .join('') }) // 计算最终答案 const finalAnswer = computed(() => { const rawContent = messages.value .filter(m => m.parsed?.content) .map(m => m.parsed.content) .join('') return marked.parse(rawContent) }) // 初始化主题 onMounted(() => { const savedTheme = localStorage.getItem('theme') currentTheme.value = savedTheme || 'light' document.documentElement.setAttribute('data-theme', currentTheme.value) }) // 切换主题 const toggleTheme = () => { currentTheme.value = currentTheme.value === 'light' ? 'dark' : 'light' localStorage.setItem('theme', currentTheme.value) document.documentElement.setAttribute('data-theme', currentTheme.value) } // 滚动到底部的函数 const scrollToBottom = (element) => { if (element) { // 获取实际的滚动容器(mockup-window 内的 overflow-y-auto 元素) const scrollContainer = element.querySelector('.overflow-y-auto') if (scrollContainer) { scrollContainer.scrollTop = scrollContainer.scrollHeight } } } // 监听消息变化,自动滚动 watch(() => [messages.value.length, reasoningChain.value, finalAnswer.value], () => { nextTick(() => { if (reasoningRef.value) { scrollToBottom(reasoningRef.value) } if (answerRef.value) { scrollToBottom(answerRef.value) } // 滚动原始数据区域 const messagesContainer = document.querySelector('.messages-container .overflow-y-auto') if (messagesContainer) { messagesContainer.scrollTop = messagesContainer.scrollHeight } }) }, { deep: true }) const parseSSEData = (data) => { try { const parsed = JSON.parse(data) // 检查是否直接返回了 reasoning_content const directReasoning = parsed.choices?.[0]?.delta?.reasoning_content if (directReasoning) { return { id: parsed.id, created: parsed.created, model: parsed.model, reasoning_content: directReasoning, content: parsed.choices?.[0]?.delta?.content || '' } } const content = parsed.choices?.[0]?.delta?.content || '' // 处理 think 标签包裹的情况 if (content.includes('')) { isInThinkTag.value = true const startIndex = content.indexOf('') + ''.length return { id: parsed.id, created: parsed.created, model: parsed.model, reasoning_content: content.substring(startIndex), content: content.substring(0, content.indexOf('')) } } if (content.includes('')) { isInThinkTag.value = false const endIndex = content.indexOf('') return { id: parsed.id, created: parsed.created, model: parsed.model, reasoning_content: content.substring(0, endIndex), content: content.substring(endIndex + ''.length) } } // 根据状态决定内容归属 return { id: parsed.id, created: parsed.created, model: parsed.model, reasoning_content: isInThinkTag.value ? content : '', content: isInThinkTag.value ? '' : content } } catch (e) { console.error('解析JSON失败:', e) return null } } const connect = () => { if (eventSource) { eventSource.close() } // 清空消息 clearMessages() try { eventSource = new EventSource(sseUrl.value) isConnected.value = true eventSource.onmessage = (event) => { const parsed = parseSSEData(event.data) messages.value.push({ time: new Date().toLocaleTimeString(), data: event.data, parsed: parsed }) } eventSource.onerror = (error) => { console.error('SSE Error:', error) disconnect() } } catch (error) { console.error('Connection Error:', error) disconnect() } } const disconnect = () => { if (eventSource) { eventSource.close() eventSource = null } isConnected.value = false } const clearMessages = () => { messages.value = [] } return { sseUrl, messages, isConnected, currentTheme, reasoningChain, finalAnswer, reasoningRef, answerRef, connect, disconnect, clearMessages, toggleTheme } } }).mount('#app') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.