主流模型调用
一、openAI
使用文档:Developer quickstart - OpenAI API
接口文档: https://platform.openai.com/docs/api-reference
1、获取 OpenAI API Key(即Token)
(1)访问:https://platform.openai.com/account/api-keys
(2)登录你的 OpenAI 账号(或注册一个新的)。
(3)点击 “Create new secret key”。

复制生成的 Key(这个 Key 只显示一次,请妥善保存)

付费完成

2、访问api
url:
https://api.openai.com/v1/chat/completions
header:
Authorization: Bearer {YOUR_API_KEY}
Content-Type: application/json
curl示例:
curl https://api.openai.com/v1/chat/completions
-H "Authorization: Bearer sk-xxx"
-H "Content-Type: application/json"
-d '{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "今天上海的天气怎么样?"}]
}'
二、Ollama
还有的大模型注册送一定免费 tokens,还有的大模型不需要token。下面推荐几个LangChain4j支持的且免费的大模型:
| 模型类型 | LangChain4j 模块 | 特点 | 是否免费 |
|---|---|---|---|
| Ollama | langchain4j-ollama | 本地推理、内置多模型(Llama3、Phi3、Mistral等) | ✅ |
| Local4j | langchain4j-local | 简单内存模型(仅测试) | ✅ |
| HuggingFace Transformers | langchain4j-huggingface | 调用本地或远程的 HF 模型 | ✅(离线模型) |
| LM Studio | 通过 HTTP 调用本地服务 | 支持任何加载的 GGUF 模型 | ✅ |
1、官网下载并安装 Ollama
-
官网:https://ollama.ai
-
支持 macOS、Windows(有 WSL)、Linux
2、启动 Ollama 服务
-
拉取模型(以 Llama3 为例):
ollama pull llama3
-
启动本地 HTTP 服务:
ollama serve
默认端口是 11434,提供 REST API。
3、本地REST API 结构
Ollama 的本地 HTTP API 大致如下:
| 方法 | 路径 | 说明 |
|---|---|---|
| POST | /api/chat | 发送聊天消息,返回模型回复 |
| GET | /api/models | 查看本地可用模型 |
4、调用
curl -X POST http://localhost:11434/api/chat \-H "Content-Type: application/json" \-d '{"model": "llama3","messages": [{"role":"user","content":"讲个笑话"}]}'
Java 调用示例(普通 HttpClient)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;public class OllamaDemo {public static void main(String[] args) throws Exception {String requestBody = """{"model": "llama3","messages": [{"role":"user","content":"用中文解释LangChain4j"}]}""";HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:11434/api/chat")).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(requestBody)).build();HttpClient client = HttpClient.newHttpClient();HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println(response.body());}
}
LangChain4j 提供 OllamaChatModel 直接封装本地 HTTP 调用:
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.ollama.OllamaChatModel;public class LangChainOllamaDemo {public static void main(String[] args) {ChatLanguageModel model = OllamaChatModel.builder().baseUrl("http://localhost:11434") // 本地 Ollama 服务.modelName("llama3").build();String result = model.generate("用中文介绍LangChain4j的核心接口");System.out.println(result);}
}
