Java 接入 Gemini SSE

170 天前
 wind1986

有人成功的么?有点奇怪, 其他家的 SSE 都能正常接入, 就是 Gemini 的不行, 通过 okhttp 接入的 ,NodeJs 和 Python 之类均可以.
调试之后发现返回 http 的头不对, application/json; charset=UTF-8, 手动更改为 text/event-stream, 不抛异常, 但是不能进入具体事件代码, 有人知道为什么么?
随便找的一份代码

@Slf4j
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SseTest {

    @Test
    public void test01() {
        // OkHttp 客户端
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(50, TimeUnit.SECONDS)
                .readTimeout(50, TimeUnit.SECONDS)
                .build();

        // 事件源工厂
        EventSource.Factory factory = EventSources.createFactory(okHttpClient);

        // 请求体
        String requestBody = "{ \"contents\":[\n" +
                "            {\"role\": \"user\",\n" +
                "              \"parts\":[{\"text\": \"Write a story about a magic backpack.\"}]\n" +
                "            }\n" +
                "          ]\n" +
                "        }";

        // 请求对象
        Request request = new Request.Builder()
                .url("http://wainao.api-v2.cloudos.com/google/v1beta/models/gemini-pro:streamGenerateContent?key=AIzaSyBGJbctKS06Zn")
                .post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody))
                .build();

        // 自定义监听器
        EventSourceListener eventSourceListener = new ConsoleEventSourceListener();

        // 创建事件
        EventSource eventSource = factory.newEventSource(request, eventSourceListener);

        // 等待线程结束
        CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

@Slf4j
class ConsoleEventSourceListener extends EventSourceListener {

    @Override
    public void onOpen(EventSource eventSource, Response response) {
        log.info("OpenAI 建立 sse 连接...");
    }

    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {
        log.info("OpenAI 返回数据:{}", data);
        if ("[DONE]".equals(data)) {
            log.info("OpenAI 返回数据结束了");
            return;
        }
    }

    @Override
    public void onClosed(EventSource eventSource) {
        log.info("OpenAI 关闭 sse 连接...");
    }

    @SneakyThrows
    @Override
    public void onFailure(EventSource eventSource, Throwable t, Response response) {
        if (Objects.isNull(response)) {
            log.error("OpenAI  sse 连接异常:{}", t);
            eventSource.cancel();
            return;
        }
        ResponseBody body = response.body();
        if (Objects.nonNull(body)) {
            log.error("OpenAI  sse 连接异常 data:{},异常:{}", body.string(), t);
        } else {
            log.error("OpenAI  sse 连接异常 data:{},异常:{}", response, t);
        }
        eventSource.cancel();
    }
}
587 次点击
所在节点    分享创造
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1001249

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX