Open AI:springboot 调用open ai 接口

Spring Boot可以通过HTTP客户端调用Open AI的API接口,具体步骤如下:

目录

1.在Open AI官方网站上注册账号并获取API密钥

2.创建一个Spring Boot项目,并添加相关的依赖,例如

3.创建一个Java类作为Open AI的HTTP客户端,例如

4.在Spring Boot的配置文件中添加Open AI的API密钥

5.在Spring Boot的控制器中调用Open AI的API接口,例如


1.在Open AI官方网站上注册账号并获取API密钥

2.创建一个Spring Boot项目,并添加相关的依赖,例如


    org.springframework.boot
    spring-boot-starter-web



   org.springframework.boot
   spring-boot-starter-validation



   org.springframework.boot
   spring-boot-starter-test
   test



   org.springframework.boot
   spring-boot-starter-data-jpa



   org.springframework.boot
   spring-boot-starter-security



   org.springframework.boot
   spring-boot-starter-thymeleaf



   org.springframework.data
   spring-data-rest-webmvc

3.创建一个Java类作为Open AI的HTTP客户端,例如

package com.example.demo.service;

import java.net.URI;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OpenAiApiService {
    
    @Value("${openai.api.key}")
    private String apiKey;
    
    private RestTemplate restTemplate;
    
    public OpenAiApiService() {
        restTemplate = new RestTemplate();
    }
    
    public String generateText(String prompt) {
        String apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);
        
        String requestBody = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": 60}";
        
        RequestEntity requestEntity = RequestEntity
            .post(URI.create(apiUrl))
            .headers(headers)
            .body(requestBody);
        
        ResponseEntity responseEntity = restTemplate.exchange(requestEntity, String.class);
        return responseEntity.getBody();
    }
}

4.在Spring Boot的配置文件中添加Open AI的API密钥

openai:
  api:
    key: YOUR_API_KEY_HERE

5.在Spring Boot的控制器中调用Open AI的API接口,例如

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.example

你可能感兴趣的:(Open,AI,计算机,/,人工智能,java,人工智能,spring,boot,后端)