ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] openAI API 이용한 chatGPT, 자바로 채팅 기능 구현하기 - V2
    자바 2023. 4. 24. 18:18

    이번에는 누가 구현해 놓은 라이브러리를 사용했다

    https://github.com/TheoKanning/openai-java

     

     

    public class testAPI {
    	
    	public static void main(String[] args) throws Exception {		
    		String input = "Y";
    		while (!input.equals("N")) {
    			Scanner sc = new Scanner(System.in);
    			input = sc.nextLine();
    			chatGPTV5(input);
    		}
            	chatGPTV4();
    	}
    	
    	public static String chatGPTV4() throws Exception {
            	String token = "인증키";
            	OpenAiService service = new OpenAiService(token);
    
            	System.out.println("\nCreating completion...");
            	CompletionRequest completionRequest = CompletionRequest.builder()
                    	.model("ada")
                    	.prompt("Somebody once told me the world is gonna roll me")
                    	.echo(true)
                    	.user("testing")
    			.n(3)
                    	.build();
            	service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
    
    
            	CreateImageRequest request = CreateImageRequest.builder()
                    	.prompt("A cow breakdancing with a turtle")
                    	.build();
    
            	System.out.println("\nImage is located at:");
            	System.out.println(service.createImage(request).getData().get(0).getUrl());
       	
       		return "";
       	}
    	
    	public static String chatGPTV5(String input) throws Exception {
        	
            	String token = "인증키";
            	OpenAiService service = new OpenAiService(token);
    
            	System.out.println("Streaming chat completion...");
            	final List<ChatMessage> messages = new ArrayList<>();
            	final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), input);
            	messages.add(systemMessage);
            	ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
                    	.builder()
                    	.model("gpt-3.5-turbo")
                    	.messages(messages)
    			.n(1)
              	    	.maxTokens(50)
    			.logitBias(new HashMap<>())
                    	.build();
            
            	System.out.println(chatCompletionRequest.toString());
            	service.createChatCompletion(chatCompletionRequest).getChoices().forEach(System.out::println);
       	
       		return "";
    	}
    }

     

     

    1) chatGPTV4()

    이거는 image generation인데 재밌어서 해봤다

    마찬가지로 scanner로 원하는 이미지를 설명하면 그림을 그려주지만 귀찮아서 input 값을 주지는 않았다

    프롬프트에 넣어준대로 "A cow breakdancing with a turtle"이라고 실행하면 아래의 그림을 그려준다

     

     

     

    2) chatGPTV5()

    이거는 앞에서 했던 그대로 chat completions

    - 여전히 앞 대화 내용을 기억하지는 못 한다

    728x90
Designed by Tistory.