赞
踩
由于OpenAI官方并未提供适用于Java的jar包, 所以只能另辟蹊径。如果你知道其他Java调用OpenAI接口的方法, 欢迎分享。
访问 https://free.gpt.ge/github 领取gpt3的api key,需要使用github账号登录
import os import openai import sys import json openai.api_key = "输入你获取的apikey" openai.base_url = "https://free.gpt.ge/v1/" #中转 openai.default_headers = {"x-foo": "true"} while True: try: input_data = sys.stdin.readline().strip() if not input_data: continue message_content = json.loads(input_data)["message"] if message_content.lower() == "quit": break completion = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[ { "role": "user", "content": message_content, }, ], ) print(completion.choices[0].message.content + "response_end") sys.stdout.flush() except Exception as e: print(f"异常: {e}") sys.stdout.flush()
package com.t.demo; import java.io.*; import java.util.Scanner; public class ChatGptController { public static void main(String[] args) { try { // 设置ProcessBuilder,使用绝对路径 ProcessBuilder pb = new ProcessBuilder("python", "C:\\Users\\locky\\Documents\\code\\demo\\src\\main\\java\\com\\t\\demo\\test.py"); pb.environment().put("PYTHONIOENCODING", "UTF-8"); Process process = pb.start(); // 获取进程的输入输出流 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); Scanner sc = new Scanner(System.in); while (true) { System.out.print("你:"); String messageContent = sc.nextLine(); if (messageContent.equals("quit")) break; writer.write("{\"message\":\"" + messageContent + "\"}\n"); writer.flush(); StringBuilder output = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { output.append(line).append("\n"); if (line.contains("response_end")) { // 确保读取到完整的响应 break; } } System.out.println("ChatGPT:" + output.toString().replace("response_end", "").trim()); } writer.close(); reader.close(); process.destroy(); //关闭python进程 } catch (Exception e) { System.out.println("异常!!"); e.printStackTrace(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。