{"id":5331,"date":"2024-09-09T09:26:13","date_gmt":"2024-09-09T09:26:13","guid":{"rendered":"https:\/\/www.aegissofttech.com\/insights\/?p=5331"},"modified":"2025-10-02T06:51:05","modified_gmt":"2025-10-02T06:51:05","slug":"spring-ai-a-chat-completion-tutorial","status":"publish","type":"post","link":"https:\/\/www.aegissofttech.com\/insights\/spring-ai-a-chat-completion-tutorial\/","title":{"rendered":"Spring AI: A Chat Completion Tutorial &#8211; Building Smart Applications"},"content":{"rendered":"\t\t<div data-elementor-type=\"wp-post\" data-elementor-id=\"5331\" class=\"elementor elementor-5331\">\n\t\t\t\t<div class=\"elementor-element elementor-element-2be0ade7 e-flex e-con-boxed e-con e-parent\" data-id=\"2be0ade7\" data-element_type=\"container\" data-e-type=\"container\">\n\t\t\t\t\t<div class=\"e-con-inner\">\n\t\t\t\t<div class=\"elementor-element elementor-element-7df17a1 elementor-widget elementor-widget-text-editor\" data-id=\"7df17a1\" data-element_type=\"widget\" data-e-type=\"widget\" data-widget_type=\"text-editor.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t\n<p>With technology, artificial intelligence (AI) integration in applications has become innovative and efficient. The <a href=\"https:\/\/spring.io\/projects\/spring-ai\" target=\"_blank\" rel=\"noopener\">Spring AI Project<\/a> is an influential add-on framework based on Spring, making it easy to bring AI capabilities to Spring-based applications. In this article, we take a brief look at Spring AI and guide you to demonstrate a chat completion article.<\/p>\n<h2><a name=\"introduction\"><\/a>1. What is Spring AI?<\/h2>\n<p>The <a href=\"https:\/\/spring.io\/projects\/spring-ai\" target=\"_blank\" rel=\"noopener\">Spring AI Project<\/a> was an extension project to the Spring framework where additional capabilities in the form of tools and libraries that assist in the integration of AI into applications were introduced. It connects AI models with end-user programs ensuring easy use and maximum flexibility and offers rich support for many AI services and frameworks. Whether one is working with machine learning models, natural language processing, or computer vision, the Spring AI will help embed all the other AI capabilities into applications in the most effortless manner possible.<\/p>\n<h2><a name=\"generate-an-openai-api-key\"><\/a>2. How to generate an OpenAI API key?<\/h2>\n<p>We will now understand how to obtain an OpenAI key. We&#8217;ll use an OpenAI model to generate an image.<\/p>\n<ul>\n<li>Create an Account or Sign In: Go to the <a href=\"https:\/\/www.openai.com\" target=\"_blank\" rel=\"noopener\">OpenAI website<\/a> and either sign up for a new account or log in to your existing one.<\/li>\n<li>Access API Keys: After logging in, head to the API Keys section within your account dashboard.<\/li>\n<li>Generate a New API Key: Select the option to create a new API key. Assign a name or description to the key for easy reference.<\/li>\n<li>Generate and Save the Key: Click the Generate Key button. Make sure to copy the newly created API key and store it in a safe place, as you will need it to access OpenAI&#8217;s services.<\/li>\n<\/ul>\n<h2><a name=\"code-example\"><\/a>3. Code example<\/h2>\n<h3>3.1 Dependencies<\/h3>\n<p>Add the following dependencies to your <code>pom.xml<\/code> file.<\/p>\n<pre class=\"brush:plain; wrap-lines:false;\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;project xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\"\n         xsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 https:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\"&gt;\n    &lt;modelVersion&gt;4.0.0&lt;\/modelVersion&gt;\n    &lt;parent&gt;\n        &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n        &lt;artifactId&gt;spring-boot-starter-parent&lt;\/artifactId&gt;\n        &lt;version&gt;3.2.4&lt;\/version&gt;\n        &lt;relativePath\/&gt; &lt;!-- lookup parent from repository --&gt;\n    &lt;\/parent&gt;\n    &lt;groupId&gt;myexample&lt;\/groupId&gt;\n    &lt;artifactId&gt;demo&lt;\/artifactId&gt;\n    &lt;version&gt;0.0.1-SNAPSHOT&lt;\/version&gt;\n    &lt;properties&gt;\n        &lt;java.version&gt;17&lt;\/java.version&gt;\n    &lt;\/properties&gt;\n    &lt;dependencies&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter-web&lt;\/artifactId&gt;\n        &lt;\/dependency&gt;\n        &lt;!--&lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter&lt;\/artifactId&gt;\n        &lt;\/dependency&gt;--&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter-test&lt;\/artifactId&gt;\n            &lt;scope&gt;test&lt;\/scope&gt;\n        &lt;\/dependency&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.ai&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-ai-openai-spring-boot-starter&lt;\/artifactId&gt;\n            &lt;version&gt;0.8.0-SNAPSHOT&lt;\/version&gt;\n        &lt;\/dependency&gt;\n    &lt;\/dependencies&gt;\n\n    &lt;build&gt;\n        &lt;plugins&gt;\n            &lt;plugin&gt;\n                &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n                &lt;artifactId&gt;spring-boot-maven-plugin&lt;\/artifactId&gt;\n            &lt;\/plugin&gt;\n        &lt;\/plugins&gt;\n    &lt;\/build&gt;\n\n    &lt;repositories&gt;\n        &lt;repository&gt;\n            &lt;id&gt;spring-milestones&lt;\/id&gt;\n            &lt;name&gt;Spring Milestones&lt;\/name&gt;\n            &lt;url&gt;https:\/\/repo.spring.io\/milestone&lt;\/url&gt;\n            &lt;snapshots&gt;\n                &lt;enabled&gt;false&lt;\/enabled&gt;\n            &lt;\/snapshots&gt;\n        &lt;\/repository&gt;\n        &lt;repository&gt;\n            &lt;id&gt;spring-snapshots&lt;\/id&gt;\n            &lt;name&gt;Spring Snapshots&lt;\/name&gt;\n            &lt;url&gt;https:\/\/repo.spring.io\/snapshot&lt;\/url&gt;\n            &lt;releases&gt;\n                &lt;enabled&gt;false&lt;\/enabled&gt;\n            &lt;\/releases&gt;\n        &lt;\/repository&gt;\n    &lt;\/repositories&gt;\n\n&lt;\/project&gt;\n<\/pre>\n<h3>3.2 Update the application properties<\/h3>\n<p>Add the following properties to the <code>application.properties<\/code> file. Remember to replace the OpenAI key.<\/p>\n<pre class=\"brush:plain; wrap-lines:false;\"># Spring Boot Application Properties\nspring.application.name=springaichatapplication\nspring.main.banner-mode=off\nserver.port=9090\n\n# OpenAI API Key\nspring.ai.openai.api-key=your-openai-api-key\n<\/pre>\n<h3>3.3 Creating the Controller<\/h3>\n<p>The <code>BasicChatController<\/code> class is a REST controller in a Spring Boot application, responsible for handling HTTP requests related to chat completion. The controller method calls the <code>openAiClient.call(\u2026)<\/code> to get a response from the OpenAI API and return a Map containing the response.<\/p>\n<pre class=\"brush:java; wrap-lines:false;\">package myexample.demo.controller;\n\nimport org.springframework.ai.openai.OpenAiChatClient;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport java.util.Map;\n\n@RestController\n@RequestMapping(\"\/chat\")\npublic class BasicChatController {\n\n    private final OpenAiChatClient chatClient;\n\n    @Autowired\n    public BasicChatController(OpenAiChatClient chatClient) {\n        this.chatClient = chatClient;\n    }\n\n    \/**\n     * Handles GET requests to the \/greet endpoint.\n     *\n     * @param message the message to be sent to the OpenAI chat client. Defaults to \"Tell a random good morning fact\" if not provided.\n     * @return a map containing the response generated by the OpenAI chat client.\n     *\/\n    \/\/ http:\/\/localhost:9090\/chat\/greet?message=Tell%20a%20random%20good%20morning%20fact\n    \/\/ http:\/\/localhost:9090\/chat\/greet?message=Hello\n    @GetMapping(\"\/greet\")\n    public Map chat(@RequestParam(value = \"message\", defaultValue = \"Tell a random good morning fact\") String message) {\n        System.out.println(\"Message: \" + message);\n        return Map.of(\"Generated by OpenAI\", chatClient.call(message));\n    }\n}\n<\/pre>\n<h3>3.4 Create the Main file<\/h3>\n<p>Create a Spring Boot application to initialize the application.<\/p>\n<pre class=\"brush:java; wrap-lines:false;\">package myexample.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringaichatapplicationApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(SpringaichatapplicationApplication.class, args);\n        System.out.println(\"Spring AI Chat Application Started...\");\n    }\n}\n<\/pre>\n<h3>3.5 Run the application and Demo<\/h3>\n<p>Now start the application and open the Postman tool to hit the api endpoint. Import the below curl GET request in the Postman tool. You\u2019re free to change the prompt with a valid instruction.<\/p>\n<pre class=\"brush:plain; wrap-lines:false;\">curl 'http:\/\/localhost:9090\/chat\/greet?message=Hello'\n<\/pre>\n<p>If everything goes well the chat completion response will be returned from OpenAI and sent to the client as a json response.<\/p>\n<pre class=\"brush:plain; wrap-lines:false;\">{\n    \"Generated by OpenAI\": \"Hello! How can I assist you today?\"\n}\n<\/pre>\n<h2><a name=\"conclusion\"><\/a>4. Conclusion<\/h2>\n<p>In conclusion, as AI continues to reshape the technological landscape, tools like <a href=\"https:\/\/www.aegissofttech.com\/insights\/alternatives-to-spring-apache-shiro-2-quarkus\/\">alternatives to spring boot<\/a>\u00a0AI are essential for seamlessly integrating AI into applications. By leveraging Spring AI, Java developers can easily add advanced AI capabilities to their Spring-based projects, enabling innovative solutions like generating images from user prompts, chat completion bots, and more. If you&#8217;re looking to implement AI-driven solutions in your applications, <a href=\"https:\/\/www.aegissofttech.com\/hire-java-developers.html\">hire Java developers<\/a> who specialize in Spring AI to ensure the seamless integration of these advanced capabilities.<\/p>\n<h2><a name=\"download-the-source-code\"><\/a>5. Download the code<\/h2>\n<div class=\"download\">You can download the full code here: <strong><a href=\"https:\/\/www.aegissofttech.com\/insights\/wp-content\/uploads\/2024\/09\/Springai-chat-completion-example.zip\">Download<\/a><\/strong><\/div>\n<div>\u00a0<\/div>\n<div>If you&#8217;re interested in learning more about Kafka migration to Spring Boot, check out our related blog: <a href=\"https:\/\/www.aegissofttech.com\/insights\/kafka-baggage-amp-webflux-migration-to-spring-boot\/\">Kafka migration to Spring Boot<\/a><\/div>\n\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t","protected":false},"excerpt":{"rendered":" ","protected":false},"author":12,"featured_media":5332,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[919,12],"tags":[928],"class_list":["post-5331","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-spring-boot","category-java","tag-spring-ai"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5331","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/comments?post=5331"}],"version-history":[{"count":16,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5331\/revisions"}],"predecessor-version":[{"id":14788,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5331\/revisions\/14788"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/media\/5332"}],"wp:attachment":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/media?parent=5331"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/categories?post=5331"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/tags?post=5331"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}