(第三周,校历11周)阅读openai文档,了解Chat Completions api,以及相关使用方法及示例.

目录

一.认识两种api,和它们区别

 Responses vs. Chat Completions

 二.openai 一些简单调用      

1.文本调用(chat completions)

2.openai 模型

3.如何定义llm的角色.

解释

4.历史对话(上下文)

另一种方法:

5.结构化输出

6.函数调用

一句话解释:


我的任务是设置 LLM 创意等级(5 档)设置全局 LLM 人格(自带 6 个,其中最基本的那个要克服 DeepSeek 不说人话(比如过分堆砌意象、说什么都能提到“量子”“前额叶”“框架”“机制”“生态”“预警”“认知科学”等词、有时突兀地插入伪代码)的问题) 增加和删除 LLM 记忆(至多 5 条记忆,每条至多 20 字)为此我需要看openai文档看如何调用api,和怎么使用javascripe

一.认识两种api,和它们区别

 Responses vs. Chat Completions

       responses api 是最新的api,它有着不同的交互方式.使用响应 API 可以更轻松地处理事件。它具有可预测的事件驱动架构,而聊天完成 API 会在生成令牌时持续附加到内容字段,这需要您手动跟踪每种状态之间的差异。使用响应 API 可以更轻松地实现多步骤对话逻辑和推理。响应 API 返回输出,而聊天完成 API 返回 choices 数组。

 二.openai 一些简单调用      

1.文本调用(chat completions)

OpenAI API 为最先进的 AI 模型提供了一个简单的接口,用于文本生成、自然语言处理、计算机视觉等。此示例从提示生成文本输出 ,就像可能使用 ChatGPT 一样。

这是利用api ,让chat写一个关于独角兽的故事.

import OpenAI from "openai";
const client = new OpenAI();

const completion = await client.chat.completions.create({
    model: "gpt-4.1",
    messages: [
        {
            role: "user",
            content: "Write a one-sentence bedtime story about a unicorn.",
        },
    ],
});

console.log(completion.choices[0].message.content);
[
    {
        "index": 0,
        "message": {
            "role": "assistant",
            "content": "Under the soft glow of the moon, Luna the unicorn danced through fields of twinkling stardust, leaving trails of dreams for every child asleep.",
            "refusal": null
        },
        "logprobs": null,
        "finish_reason": "stop"
    }
]

回复的choice

2.openai 模型

openai实验中有不同的模型 有推理模型,mini gpt模型

3.如何定义llm的角色.
import OpenAI from "openai";
const client = new OpenAI();

const completion = await client.chat.completions.create({
    model: "gpt-4.1",
    messages: [
        {
            role: "developer",
            content: "Talk like a pirate."
        },
        
    ],
});

console.log(completion.choices[0].message);

如上文,role 定义了一个开发者的角色,让模型用开发者的角色来回复想海盗一样说话的问题.

解释

消息角色 → 对话中的身份标签
就像微信群聊里有不同身份:

system(系统):群主,负责定规矩
例:{"role": "system", "content": "你是个毒舌但靠谱的健身教练,用emoji和网络用语回答问题"}
→ 相当于群主说:“本群只聊减肥,禁止发广告!”

user(用户):提问者,提需求的人
例:{"role": "user", "content": "怎么瘦肚子?"}
→ 相当于你在群里问:“哪家轻食外卖好吃?”

assistant(助手):AI的历史回复,用于保持对话连贯
例:{"role": "assistant", "content": "先戒掉奶茶!明天开始做平板支撑"}
→ 相当于AI自己接话:“上次推荐的沙拉店咋样?”

我们通过role,可以完成对ai性格的设定。

4.历史对话(上下文)

我们可以使用

import OpenAI from "openai";

const openai = new OpenAI();

const response = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
        {
            role: "user",
            content: "knock knock.",
        },
        {
            role: "assistant",
            content: "Who's there?",
        },
        {
            role: "user",
            content: "Orange.",
        },
    ],
});

console.log(response.choices[0].message.content);

把过去的对话抛给ai,它会直接识别继续推送。这样上下文问题可以解决,但是这样子,几轮之后会增多。

另一种方法:

Assistants API:自动创建对话线程
👉 类似微信自动保存聊天记录,新消息自动关联历史

5.结构化输出

结构化输出 = 让AI的回答按指定格式“填空”,比如生成表格、JSON、代码等机器可读的格式,而不是随意写一段文字。

传统输出:AI自由发挥 → 相当于让朋友口头描述天气:
“今天有点闷热,下午可能会下雨,记得带伞哦~”

结构化输出:

{
  "日期": "2024-05-20",
  "天气": "多云转阵雨",
  "温度": "28℃~33℃",
  "建议": ["带伞", "穿防晒衣"]
}

这样能减少ai瞎编的情况,方便识别和输出。

文档中的例子:

import OpenAI from "openai";
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";

const openai = new OpenAI();

const Step = z.object({
  explanation: z.string(),
  output: z.string(),
});

const MathReasoning = z.object({
  steps: z.array(Step),
  final_answer: z.string(),
});

const completion = await openai.beta.chat.completions.parse({
  model: "gpt-4o-2024-08-06",
  messages: [
    { role: "system", content: "You are a helpful math tutor. Guide the user through the solution step by step." },
    { role: "user", content: "how can I solve 8x + 7 = -23" },
  ],
  response_format: zodResponseFormat(MathReasoning, "math_reasoning"),
});

const math_reasoning = completion.choices[0].message.parsed;

回复:

{
  "steps": [
    {
      "explanation": "Start with the equation 8x + 7 = -23.",
      "output": "8x + 7 = -23"
    },
    {
      "explanation": "Subtract 7 from both sides to isolate the term with the variable.",
      "output": "8x = -23 - 7"
    },
    {
      "explanation": "Simplify the right side of the equation.",
      "output": "8x = -30"
    },
    {
      "explanation": "Divide both sides by 8 to solve for x.",
      "output": "x = -30 / 8"
    },
    {
      "explanation": "Simplify the fraction.",
      "output": "x = -15 / 4"
    }
  ],
  "final_answer": "x = -15 / 4"
}
6.函数调用
一句话解释:

把AI变成会思考的遥控器——它听懂你的话,按下正确的按钮(函数),再用人话告诉你结果。

文档例子:

import { OpenAI } from "openai";

const openai = new OpenAI();

const tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current temperature for a given location.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and country e.g. Bogotá, Colombia"
                }
            },
            "required": [
                "location"
            ],
            "additionalProperties": false
        },
        "strict": true
    }
}];

const completion = await openai.chat.completions.create({
    model: "gpt-4.1",
    messages: [{ role: "user", content: "What is the weather like in Paris today?" }],
    tools,
    store: true,
});

console.log(completion.choices[0].message.tool_calls);

文档中写了一个 get weather方法,然后user角色,问巴黎当天天气,这时候会调用方法,返回天气。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值