3. 大模型API其他调用方式
# 3.1 JavaScript
在 JavaScript 环境中,可以使用 fetch API 或 axios 等库来调用大模型API。
const fetch = require('node-fetch'); // 如果是 Node.js 环境
const API_KEY = 'your-api-key'; // 你的 OpenAI API 密钥
const url = 'https://api.openai.com/v1/chat/completions';
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
};
const data = {
model: "gpt-4o-mini",
messages: [
{
"role": "user",
"content": "Translate the following English text to French: 'Hello, how are you?'"
}
],
max_tokens: 60,
temperature: 0.7
};
fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => console.log(data.choices[0].message.content))
.catch(error => console.error('Error:', error));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 3.1.1 现代 JavaScript (ES6+) 写法
// 使用 async/await
async function callOpenAI(prompt) {
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
temperature: 0.7,
max_tokens: 150
}),
});
const data = await response.json();
return data.choices[0].message.content;
} catch (error) {
console.error('API调用失败:', error);
throw error;
}
}
// 使用示例
callOpenAI("解释什么是人工智能")
.then(result => console.log(result))
.catch(error => console.error(error));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 3.2 curl 接口
其本质是一个 HTTP 接口,所以你也可以用任何语言与方式发送 HTTP 请求来实现调用。
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "Translate the following English text to French: '\''Hello, how are you?'\''"
}
],
"max_tokens": 60,
"temperature": 0.7
}'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 3.2.1 使用环境变量的 curl 示例
# 设置环境变量
export OPENAI_API_KEY="your-api-key"
export OPENAI_BASE_URL="https://api.openai.com/v1"
# 调用API
curl $OPENAI_BASE_URL/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "你是一个专业的翻译助手"},
{"role": "user", "content": "请将以下英文翻译成中文:Hello, how are you?"}
],
"temperature": 0.3
}'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 3.3 Java SpringAI
SpringAI 是 Spring 官方推出的 AI 集成框架,提供统一 API 规范的大模型调用能力,支持 OpenAI、Azure OpenAI、HuggingFace 等主流平台。
# 3.3.1 环境配置
步骤 1:添加依赖
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.8.0</version> <!-- 建议使用最新版本 -->
</dependency>
1
2
3
4
5
6
2
3
4
5
6
步骤 2:配置参数
# application.properties
spring.ai.openai.api-key=your-api-key
spring.ai.openai.base-url=https://api.openai.com/v1
1
2
3
2
3
# 3.3.2 基础调用示例
import org.springframework.ai.client.AiClient;
import org.springframework.ai.prompt.Prompt;
import org.springframework.ai.prompt.messages.Message;
import org.springframework.ai.prompt.messages.SystemMessage;
import org.springframework.ai.prompt.messages.UserMessage;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class AiController {
@Autowired
private AiClient aiClient;
@GetMapping("/chat")
public String chat() {
// 构建对话上下文
List<Message> messages = List.of(
new SystemMessage("你是一个Java开发助手"),
new UserMessage("如何用Spring Boot创建REST API?")
);
// 创建请求
Prompt prompt = new Prompt(
messages,
OpenAiChatOptions.builder()
.withModel("gpt-4o-mini")
.withTemperature(0.7)
.withMaxTokens(200)
.withTopP(0.9)
.build()
);
// 发送请求并获取响应
return aiClient.generate(prompt).getGeneration().getText();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 3.3.3 流式响应
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
@GetMapping("/stream")
public SseEmitter streamChat() {
SseEmitter emitter = new SseEmitter();
aiClient.stream(new Prompt(
List.of(new UserMessage("用Java实现快速排序")),
OpenAiChatOptions.builder().withModel("gpt-4o-mini").build()
)).subscribe(
chunk -> {
try {
emitter.send(chunk.getGeneration().getText());
} catch (IOException e) {
throw new RuntimeException(e);
}
},
emitter::completeWithError,
emitter::complete
);
return emitter;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 3.3.4 配置项说明
| 参数路径 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| spring.ai.openai.api-key | String | - | API 访问密钥(必填) |
| spring.ai.openai.base-url | String | OpenAI 官方URL | 官方URL/代理地址 |
| spring.ai.openai.chat.options.temperature | Double | 0.7 | 随机性控制参数 |
| spring.ai.openai.chat.options.max-tokens | Integer | 2000 | 响应最大长度限制 |
# 3.3.5 注意事项
- 版本兼容性:SpringAI 0.8.x 需要 Spring Boot 3.2+
- JDK 最低要求 17
- 性能优化:
- 使用
@Cacheable缓存高频请求 - 启用
spring.ai.openai.enable-metrics=true进行性能监控
- 使用
# 3.4 其他框架方式对比
| 方式 | 开发成本 | 灵活性 | 适合场景 | 典型用户 |
|---|---|---|---|---|
| 原生API | 高 | 极高 | 核心业务/定制需求 | 技术团队 |
| LangChain | 中 | 高 | 复杂AI工作流 | AI工程师 |
| LlamaIndex | 中 | 中 | 文档问答系统 | 数据团队 |
| Dify/FastGPT | 低 | 低 | 标准化业务场景 | 企业开发、产品经理 |
编辑 (opens new window)
上次更新: 2025/09/16, 11:19:26