手机 dns 国外网站,做正规小说网站有哪些,php连接wordpress数据库,网站设计基础浅谈人工智能之基于HTTP方式调用本地QWen OPenAI接口#xff08;Java版#xff09;
概述
Qwen是阿里云推出的一款超大规模语言模型#xff0c;其强大的自然语言处理能力使其成为开发智能应用的热门选择。本文将指导你如何使用Java通过HTTP方式调用Qwen的OpenAI接口#x…浅谈人工智能之基于HTTP方式调用本地QWen OPenAI接口Java版
概述
Qwen是阿里云推出的一款超大规模语言模型其强大的自然语言处理能力使其成为开发智能应用的热门选择。本文将指导你如何使用Java通过HTTP方式调用Qwen的OpenAI接口实现文本生成、问答等高级功能。 我们在使用spring ai的发现java要求的版本是java 17但是我们很多时候可能当前电脑安装的java 版本是8所以我们可以通过http协议的方式进行大模型接口调用
准备工作
在开始之前确保你已经搭建了本地Qwen大模型并且已经明确调用的接口和消息方式如我们调用的方式如下 请求http://xx.xx.xxx.xxx:xxxx/v1/chat/completions headersContent-Type:application/json body如下
{model: QWen,messages: [{role: system, content: You are Qwen, created by Alibaba Cloud. You are a helpful assistant.},{role: user, content: 你是谁}],temperature: 0.7,top_p: 0.8,repetition_penalty: 1.05,max_tokens: 512
}我们可以通过上述接口使用postman进行接口调用可以获取如下结果
{id: chat-a6d73e5d0e3c4d959c1b6cee07177407,object: chat.completion,created: 1726730176,model: QWen,choices: [{index: 0,message: {role: assistant,content: 我是Qwen是阿里云开发的一款超大规模语言模型。我能够生成各种类型的文本如文章、故事、诗歌、故事等并能根据不同的场景和需求进行变换和扩展。同时我还具备代码写作能力可以理解和生成多种编程语言的代码。如果您有任何问题或需要帮助请随时告诉我,tool_calls: []},logprobs: null,finish_reason: stop,stop_reason: null}],usage: {prompt_tokens: 32,total_tokens: 102,completion_tokens: 70},prompt_logprobs: null
}应用实例
第一步在你的pom.xml文件中添加以下依赖
dependencygroupIdcn.hutool/groupIdartifactIdhutool-all/artifactIdversion5.6.3/version
/dependency第二步我们新建一个Qwen.class的类
package com.dahua.architectureforps.C9100.aboutHTTP;import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;public class Qwen {public static String OpenAI(String prompt){String result ;//你实际的模型API和模型名称String baseUrl http://xx.xx.xxx.xxx:xxxx/v1/chat/completions;String model QWen;String requestBody {\n \model\: \ model \,\n \messages\: [\n {\role\: \system\, \content\: \You are Qwen, created by Alibaba Cloud. You are a helpful assistant.\},\n {\role\: \user\, \content\: \ prompt \}\n ],\n \temperature\: 0.7,\n \top_p\: 0.8,\n \repetition_penalty\: 1.05,\n \max_tokens\: 512\n };HttpResponse execute HttpRequest.post(baseUrl).header(Accept, application/json).body(requestBody).execute();String body execute.body();System.out.println(body);JSONObject jsonObject JSONObject.parseObject(body);String choices jsonObject.getString(choices);JSONArray choicesArray JSONObject.parseArray(choices);String o choicesArray.getString(0);JSONObject json JSONObject.parseObject(o);String message json.getString(message);JSONObject jsonMessage JSONObject.parseObject(message);result jsonMessage.getString(content);return result;}public static void main(String[] args) {String prompt 你是谁;String s OpenAI(prompt);System.out.println(s);}
}第三步我们运行程序可以得到如下结果 我是Qwen是阿里云开发的一款超大规模语言模型。我能够生成各种类型的文本如文章、故事、诗歌、故事等并能回答问题、提供信息和与用户进行对话。如果您有任何问题或需要帮助请随时告诉我 结论
通过上述方法你可以轻松地使用Java调用Qwen的OpenAI接口实现各种自然语言处理任务。记住每次调用API时都要进行身份验证并且根据API的具体要求构建请求体。此外务必遵循API的使用限制和最佳实践以确保稳定性和性能。后续我们还会分享如何在java17的开发环境下使用spring ai来调用相应的大模型。