Tutorial: How Spring AI works
2 mins read

Tutorial: How Spring AI works

// src/main/resources/application.resources
spring.ai.azure.openai.chat.options.deployment-name=gpt-35-turbo-16k

Das erstellt eine Property mit dem Value gpt-turbo-16k. There spring.ai.azure.openai.chat.options.deployment-name is wichtig, but is per Autoconfiguration with a Spring-Bean-Configurator effective, where a basic ChatClient is installed. Next dependency in pom.xml stelt diesen The customer has:


  org.springframework.ai
  spring-ai-azure-openai-spring-boot-starter

Wenn Spring das Projekt nach einem ChatClient durchsucht, nutzt es die Property, um einen ChatClient unter Verwendung der Mennskonventionen im openai-Starter project for the creation. In the following helloworld-Beispiel wird dieser ChatClient vom Controller on:

package com.xkcd.ai.helloworld;

import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class SimpleAiController {

	private final ChatClient chatClient;

	@Autowired
	public SimpleAiController(ChatClient chatClient) {
		this.chatClient = chatClient;
	}

	@GetMapping("/ai/simple")
	public MapString,  generation(
			@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
		return Map.of("generation", chatClient.call(message));
	}

}

This is a typical Spring REST Controller, bei dem das chatClient-Member as @Autowired an eine Methode gebunden ist. Dieser ChatClient wird then verwendet, um die Requests unter /ai/simple to edit. Die Endpoint-Methode gives a map with a “Generation”-Key zurück, its Value der Return Value of chatClient.call(message) corresponds to

For all this to work, you need an API key for Azure. Dieser is defined as environment variable:

export SPRING_AI_AZURE_OPENAI_API_KEY=

Subsequently, you also have to “mit” the Engine, where the KI endpoint is located:

export SPRING_AI_AZURE_OPENAI_ENDPOINT=

Sind alle Elemente vorhanden, können Sie das Projekt mit $ maven spring-boot:run execute Uber localhost:8080/ai/simple shouldn Sie nun einen AI-generierten Witz abrufen können.

Other games in the Azure Repository are demonstrated, whose basic Rahmen are available for functions that can be used. You can, for example, easily add a prompt template for Beispiel App:

// src/main/resources/prompts/joke-prompt.st
Tell me a {adjective} joke about {topic}

There is a control unit that uses:

@Value("classpath:/prompts/joke-prompt.st")
	private Resource jokeResource;

Am Ende you could add the following:

PromptTemplate promptTemplate = new PromptTemplate(jokeResource);

(fm)

Want to be more interesting? Our free newsletter liefern Ihnen alles, var IT-Profis wissen sollten – directly in your inbox!