AGI围城
首页
基础知识
工程实践
所见所思
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

AGI围城

是的,这个世界还是很有趣的。
首页
基础知识
工程实践
所见所思
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 提示词工程

  • 大模型API调用

    • 1. 大模型api简单示例
    • 2. Openai库常用参数详解
    • 3. 大模型API其他调用方式
      • 3.1 JavaScript
        • 3.1.1 现代 JavaScript (ES6+) 写法
      • 3.2 curl 接口
        • 3.2.1 使用环境变量的 curl 示例
      • 3.3 Java SpringAI
        • 3.3.1 环境配置
        • 3.3.2 基础调用示例
        • 3.3.3 流式响应
        • 3.3.4 配置项说明
        • 3.3.5 注意事项
      • 3.4 其他框架方式对比
  • OpenAI工具

  • 嵌入向量

  • 检索增强生成(RAG)

  • 基础知识
  • 大模型API调用
xiao_sl
2025-09-05
目录

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

# 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

# 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

# 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

# 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:配置参数

# application.properties
spring.ai.openai.api-key=your-api-key
spring.ai.openai.base-url=https://api.openai.com/v1
1
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

# 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

# 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)
#llm调用
上次更新: 2025/09/16, 11:19:26
2. Openai库常用参数详解
1. 文件检索

← 2. Openai库常用参数详解 1. 文件检索→

最近更新
01
2. 朴素RAG
09-17
02
1. RAG基本概念
09-13
03
4. 向量相关参考资料
09-12
更多文章>
Theme by Vdoing | Copyright © 2019-2025 AGI围城 | 桂ICP备2024034950号 | 桂公网安备45142202000030
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式