Skip to main content
Innovation|Innovation

Spring AI తో AI-Powered జావా అప్లికేషన్లు నిర్మించడం: సంపూర్ణ గైడ్

Spring AI తో AI-powered Java applications నిర్మించడానికి సంపూర్ణ గైడ్ — ChatClient, prompt templates, structured output, RAG, function calling, advisors, chat memory, embeddings, multi-modality, మరియు provider configuration.

8 ఏప్రిల్, 20266 min read

Spring AI జావా డెవలపర్ల కోసం ఎందుకు ప్రతిదీ మారుస్తుంది

Spring AI, Spring Boot డెవలపర్లు ఇష్టపడే productivity మరియు portability ను AI ప్రపంచానికి తీసుకువస్తుంది. ఒక clean abstraction పై మీ AI code ఒక్కసారి రాయండి, తర్వాత providers ను మార్చండి — OpenAI, Anthropic Claude, Google Gemini, Ollama, AWS Bedrock — configuration మార్పుతో, code rewrite కాదు.

మే 2025 లో 1.0 GA గా విడుదలైంది, Spring AI అందిస్తుంది: ఏకీకృత chat API, Java records కు structured output mapping, built-in RAG support, function/tool calling, chat memory, advisors, embeddings, image generation, multi-modality, మరియు evaluation — అన్నీ Spring Boot auto-configuration తో.

ప్రారంభించడం

మీ pom.xml కు BOM మరియు provider starter జోడించండి:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>1.1.4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<!-- ఒక provider starter ఎంచుకోండి -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

application.yml లో configure చేయండి:

spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
      chat:
        options:
          model: gpt-4o
          temperature: 0.7

ప్రధాన Abstractions: ChatModel, ChatClient, Prompt

Spring AI యొక్క శక్తి provider-agnostic interfaces లో ఉంది. మీ code abstractions పై program చేస్తుంది; Spring Boot concrete provider ను wire చేస్తుంది.

ChatClient — Fluent API (సిఫారసు చేయబడింది)

@RestController
class ChatController {
    private final ChatClient chatClient;

    ChatController(ChatClient.Builder builder) {
        this.chatClient = builder
            .defaultSystem("You are a helpful coding assistant.")
            .build();
    }

    @GetMapping("/chat")
    String chat(@RequestParam String message) {
        return chatClient.prompt()
            .user(message)
            .call()
            .content();
    }
}

Message Types

SystemMessage instructions set చేస్తుంది. UserMessage user input carry చేస్తుంది (multimodal కోసం text + media). AssistantMessage model replies hold చేస్తుంది. ToolResponseMessage tool/function results return చేస్తుంది.

Streaming Responses

@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> streamChat(@RequestParam String message) {
    return chatClient.prompt()
        .user(message)
        .stream()
        .content();
}

Prompt Templates

Spring AI యొక్క PromptTemplate ఉపయోగించి variable substitution తో prompts ను reusable గా ఉంచండి:

// Inline template
String answer = chatClient.prompt()
    .user(u -> u
        .text("List {count} best practices for {topic}")
        .param("count", "5")
        .param("topic", "REST API design"))
    .call()
    .content();

// System prompt template
String systemText = """
    You are an expert in {domain}.
    Reply in the style of a {style}.
    """;

SystemPromptTemplate systemTemplate = new SystemPromptTemplate(systemText);
Message systemMessage = systemTemplate.createMessage(Map.of(
    "domain", "distributed systems",
    "style", "senior engineer"
));

// Classpath resource నుండి load చేయండి
@Value("classpath:/prompts/analysis.st")
private Resource analysisTemplate;
PromptTemplate template = new PromptTemplate(analysisTemplate);

Prompt Engineering ఉత్తమ పద్ధతులు

నిర్దిష్టంగా ఉండండి: model కు ఖచ్చితంగా ఏ format, tone, మరియు constraints అవసరమో చెప్పండి. System messages ఉపయోగించండి: System prompt లో persona మరియు rules set చేయండి, user prompt లో user content. One-shot/few-shot: కావలసిన output యొక్క ఉదాహరణ చేర్చండి. Chain-of-thought: సంక్లిష్ట reasoning కోసం "step by step ఆలోచించండి" అని model ను అడగండి. Structured output: JSON request చేసి records కు map చేయండి.

Structured Output — AI Responses Java Records గా

AI-generated text ను typed Java objects లోకి నేరుగా map చేయండి. Manual JSON parsing అవసరం లేదు.

// మీ record define చేయండి
record BookRecommendation(String title, String author,
                          String genre, String summary) {}

// Single entity
BookRecommendation book = chatClient.prompt()
    .user("Recommend a classic science fiction novel.")
    .call()
    .entity(BookRecommendation.class);

// Entities List
List<BookRecommendation> books = chatClient.prompt()
    .user("Recommend 5 classic sci-fi novels.")
    .call()
    .entity(new ParameterizedTypeReference<List<BookRecommendation>>() {});

// Map output
Map<String, Object> data = chatClient.prompt()
    .user("List the population of Tokyo, London, and New York")
    .call()
    .entity(new ParameterizedTypeReference<Map<String, Object>>() {});

RAG: Retrieval Augmented Generation

RAG మీ AI ను మీ సొంత డేటా ఉపయోగించి ప్రశ్నలకు సమాధానం ఇవ్వడానికి అనుమతిస్తుంది — vector store నుండి సంబంధిత documents retrieve చేసి prompt లో context గా inject చేయడం ద్వారా.

Step 1: Document Ingestion (ETL)

@Component
class DocumentIngestionService {
    private final VectorStore vectorStore;

    DocumentIngestionService(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }

    public void ingest(String pdfPath) {
        // 1. Documents చదవండి (PDF, JSON, HTML, Markdown, DOCX supported)
        PagePdfDocumentReader reader = new PagePdfDocumentReader(pdfPath,
            PdfDocumentReaderConfig.builder()
                .withPagesPerDocument(1).build());

        // 2. Chunks గా split చేయండి
        TokenTextSplitter splitter = TokenTextSplitter.builder()
            .withChunkSize(800)
            .withMinChunkSizeChars(350).build();

        // 3. Store — embeddings ఆటోమేటిక్‌గా generate అవుతాయి
        vectorStore.write(splitter.apply(reader.read()));
    }
}

Step 2: QuestionAnswerAdvisor తో Query

ChatResponse response = chatClient.prompt()
    .advisors(QuestionAnswerAdvisor.builder(vectorStore)
        .searchRequest(SearchRequest.builder()
            .similarityThreshold(0.75)
            .topK(5).build())
        .build())
    .user("మా refund policy digital products గురించి ఏమి చెబుతుంది?")
    .call()
    .chatResponse();

Query Rewriting తో Advanced RAG

Advisor ragAdvisor = RetrievalAugmentationAdvisor.builder()
    .queryTransformers(RewriteQueryTransformer.builder()
        .chatClientBuilder(chatClientBuilder.build().mutate()).build())
    .documentRetriever(VectorStoreDocumentRetriever.builder()
        .vectorStore(vectorStore)
        .similarityThreshold(0.50)
        .topK(5).build())
    .build();

String answer = chatClient.prompt()
    .advisors(ragAdvisor)
    .user("SSL ఎలా configure చేయాలి?")
    .call()
    .content();

Vector Store Configuration (PGVector)

# application.yml
spring:
  ai:
    vectorstore:
      pgvector:
        initialize-schema: true
        dimensions: 1536
        distance-type: cosine_distance

Supported vector stores: PGVector, Chroma, Pinecone, Redis, Milvus, Weaviate, Qdrant, Elasticsearch, MongoDB Atlas, Neo4j, మరియు ఇంకా.

Function Calling / Tool Use

AI models మీ Java methods ను invoke చేయడానికి real-time data fetch చేయడానికి లేదా actions perform చేయడానికి అనుమతించండి.

@Tool తో Declarative

class WeatherTools {

    @Tool(description = "Get current weather for a given city")
    String getWeather(
            @ToolParam(description = "City name") String city,
            @ToolParam(description = "Temperature unit", required = false) String unit) {
        // ఇక్కడ real weather API call చేయండి
        return "Weather in %s: 22 degrees %s, sunny."
            .formatted(city, unit != null ? unit : "Celsius");
    }
}

// ఉపయోగించండి — model ఎప్పుడు function call చేయాలో నిర్ణయిస్తుంది
String response = chatClient.prompt()
    .user("London లో వాతావరణం ఎలా ఉంది?")
    .tools(new WeatherTools())
    .call()
    .content();

Spring Beans గా Functions

public record CurrencyRequest(String from, String to, double amount) {}
public record CurrencyResponse(double convertedAmount, double rate) {}

@Bean
@Description("Convert an amount from one currency to another")
Function<CurrencyRequest, CurrencyResponse> convertCurrency() {
    return request -> {
        double rate = fetchExchangeRate(request.from(), request.to());
        return new CurrencyResponse(request.amount() * rate, rate);
    };
}

// Bean name ద్వారా reference
String answer = chatClient.prompt()
    .user("100 USD ను EUR కు convert చేయండి")
    .toolNames("convertCurrency")
    .call()
    .content();

Tool Context — అదనపు Data పంపండి

class CustomerTools {
    @Tool(description = "Get customer by ID")
    Customer getCustomer(Long id, ToolContext ctx) {
        String tenantId = (String) ctx.getContext().get("tenantId");
        return customerRepo.findByIdAndTenant(id, tenantId);
    }
}

String answer = chatClient.prompt()
    .user("Customer #42 గురించి చెప్పండి")
    .tools(new CustomerTools())
    .toolContext(Map.of("tenantId", "acme-corp"))
    .call()
    .content();

Advisors — AI Calls కోసం Interceptors

Advisors prompts ను model కు చేరుకునే ముందు modify చేస్తాయి మరియు responses ను తిరిగి వచ్చే దారిలో process చేస్తాయి — AI కోసం Spring MVC interceptors లాగా.

Chat Memory — సంభాషణ చరిత్ర

ChatMemory memory = MessageWindowChatMemory.builder()
    .chatMemoryRepository(new InMemoryChatMemoryRepository())
    .maxMessages(20).build();

ChatClient client = ChatClient.builder(chatModel)
    .defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build())
    .build();

// మొదటి call
client.prompt().user("నా పేరు Alice")
    .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, "session-1"))
    .call().content();

// రెండవ call — పేరు గుర్తుంటుంది
client.prompt().user("నా పేరు ఏమిటి?")
    .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, "session-1"))
    .call().content(); // "మీ పేరు Alice"

Custom Advisor — Latency Tracking

public class LatencyAdvisor implements CallAdvisor {
    public String getName() { return "LatencyAdvisor"; }
    public int getOrder() { return 0; }

    public ChatClientResponse adviseCall(ChatClientRequest request,
                                          CallAdvisorChain chain) {
        long start = System.currentTimeMillis();
        ChatClientResponse response = chain.nextCall(request);
        log.info("AI call took {}ms", System.currentTimeMillis() - start);
        return response;
    }
}

బహుళ Advisors ను కలపడం

ChatClient client = ChatClient.builder(chatModel)
    .defaultAdvisors(
        MessageChatMemoryAdvisor.builder(memory).build(),
        QuestionAnswerAdvisor.builder(vectorStore).build(),
        new SimpleLoggerAdvisor(),
        new LatencyAdvisor()
    ).build();

Embeddings

Similarity search, clustering, మరియు RAG కోసం text ను numerical vectors గా convert చేయండి.

@Service
class EmbeddingService {
    private final EmbeddingModel embeddingModel;

    // ఒక text
    float[] embed(String text) {
        return embeddingModel.embed(text);
    }

    // Batch
    List<float[]> embedBatch(List<String> texts) {
        return embeddingModel.embed(texts);
    }

    // Vector dimensions
    int dimensions() { return embeddingModel.dimensions(); }
}

Multi-Modality — Images + Text

GPT-4o, Claude 3, లేదా Gemini వంటి models కు images ను text తో పాటు పంపండి:

String description = chatClient.prompt()
    .user(u -> u
        .text("ఈ image లో మీరు ఏమి చూస్తున్నారో వివరించండి.")
        .media(MimeTypeUtils.IMAGE_PNG,
               new ClassPathResource("/images/diagram.png")))
    .call()
    .content();

// URL నుండి
String analysis = chatClient.prompt()
    .user(u -> u
        .text("ఈ image లో ఏమి ఉంది?")
        .media(MimeTypeUtils.IMAGE_JPEG,
               URI.create("https://example.com/photo.jpg")))
    .call()
    .content();

Image Generation

@RestController
class ImageController {
    private final ImageModel imageModel;

    @GetMapping("/generate-image")
    String generateImage(@RequestParam String description) {
        ImageResponse response = imageModel.call(
            new ImagePrompt(description,
                OpenAiImageOptions.builder()
                    .quality("hd").N(1)
                    .height(1024).width(1024).build()));
        return response.getResult().getOutput().getUrl();
    }
}

Evaluation — మీ AI ని Test చేయండి

Spring AI relevance check చేయడానికి మరియు hallucinations catch చేయడానికి evaluators అందిస్తుంది:

// Response ప్రశ్న మరియు context కు relevant గా ఉందా?
RelevancyEvaluator evaluator = new RelevancyEvaluator(ChatClient.builder(chatModel));
EvaluationResponse eval = evaluator.evaluate(
    new EvaluationRequest(question, context, aiResponse));
assertThat(eval.isPass()).isTrue();

// Fact-checking — hallucinations detect చేయండి
FactCheckingEvaluator factChecker = new FactCheckingEvaluator(
    ChatClient.builder(chatModel));
EvaluationResponse result = factChecker.evaluate(
    new EvaluationRequest(knownFacts, Collections.emptyList(), claim));
assertFalse(result.isPass()); // claim తెలిసిన facts కు విరుద్ధం

Provider Configuration Cheat Sheet

ProviderStarter Artifactముఖ్య Config
OpenAIspring-ai-starter-model-openaispring.ai.openai.api-key
Anthropic Claudespring-ai-starter-model-anthropicspring.ai.anthropic.api-key
Ollama (Local)spring-ai-starter-model-ollamaspring.ai.ollama.base-url
AWS Bedrockspring-ai-starter-model-bedrockspring.ai.bedrock.aws.region
Azure OpenAIspring-ai-starter-model-azure-openaispring.ai.azure.openai.api-key
Google Geminispring-ai-starter-model-vertex-aispring.ai.vertex.ai.gemini.project-id
PGVectorspring-ai-starter-vector-store-pgvectorspring.ai.vectorstore.pgvector.*

ముఖ్యమైన అంశాలు

Provider-agnostic: ఒకసారి రాయండి, config ద్వారా AI providers మార్చండి. Vendor lock-in లేదు.

Spring-native: Auto-configuration, dependency injection, profiles — Spring developers ఆశించే ప్రతిదీ.

Production-ready patterns: RAG, tool calling, chat memory, advisors, evaluation, మరియు structured output అన్నీ built in.

సరళంగా ప్రారంభించండి: ChatClient.prompt().user("...").call().content() — అదే మీ మొదటి AI call. అవసరమైనప్పుడు RAG, tools, మరియు memory జోడించండి.

Spring AI, AI integration ను ఏదైనా ఇతర Spring dependency లాగా అనిపించేలా చేస్తుంది — starter import చేయండి, configure చేయండి, inject చేయండి, మరియు ఉపయోగించండి.

More from Innovation

Innovation

ఈ ఏడాది తెలివితేటలు చౌకయ్యాయి — విలువ మీరు దానితో నిర్మించేదానికి మారింది

ఒక మిలియన్ AI టోకెన్ల ఖర్చు ఒకే ఏడాదిలో దాదాపు నాలుగు రెట్లు తగ్గింది. ముడిసరుకు ఇంత వేగంగా చౌకైనప్పుడు, ప్రయోజనం మోడల్ ఎవరిది అనేది కాకుండా ఉపయోగకరమైనది ఎవరు నిర్మిస్తారు అనేదిగా మారుతుంది.

14, జూన్ 20263 min read
Innovation

రోబోట్లు ప్రదర్శన ఆపి పని మొదలుపెట్టిన సంవత్సరం

ఒక దశాబ్దం పాటు హ్యూమనాయిడ్ రోబోట్లు కేవలం డెమో వీడియోలే — ఎప్పుడూ ఆకట్టుకునేవి, ఎప్పుడూ ఐదేళ్ళ దూరంలో ఉండేవి. 2026లో కథ నిశ్శబ్దంగా వీడియోల నుండి ఉత్పత్తి సంఖ్యలకు మారింది.

14, జూన్ 20263 min read
Innovation

AI నెలనెలా చౌకవుతోంది. మరి అందరి AI బిల్లులు ఎందుకు పేలిపోతున్నాయి?

AI ధర ఏడాదిలో సుమారు 4 రెట్లు తగ్గింది — కానీ కంపెనీలు వార్షిక AI బడ్జెట్లను నెలల్లో ఖర్చు చేస్తున్నాయి. రెండూ నిజమే — కారణం అర్థం చేసుకోవడం ముఖ్యం.

12, జూన్ 20263 min read