0Pricing
NLP Academy · 课时

从 Python 调用 LLM

发送提示并解析响应

从 Python 调用 LLM 是 CoddyKit 上的免费 NLP Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NLP Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NLP Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Talk to a Model in Code

You do not run giant models on your laptop. Instead you send text to a hosted model over an API and get a reply back. 🌐

Install a Client

Most providers ship a Python client library so you can call the model with a few clean lines instead of raw HTTP.

pip install openai

Keep Your Key Secret

Calls are authenticated with an API key. Store it in an environment variable, never hard-coded in your source files.

import os
key = os.environ["OPENAI_API_KEY"]

Create the Client

You start by building a client object. It reads your key and handles the network details for every request you make.

from openai import OpenAI
client = OpenAI()

Messages, Not Just Text

Chat models take a list of messages, each tagged with a role like system, user, or assistant.

The System Role

A system message sets the model's behavior up front, like telling it to answer briefly or act as a helpful tutor.

Send Your Prompt

You put your question in a user message and send the whole list to the model in a single call.

resp = client.chat.completions.create(
  model="gpt-4o-mini",
  messages=[{"role": "user", "content": "Hi!"}])

Parse the Response

The reply is a structured object. The text you want sits inside the first choice, ready to read or store.

text = resp.choices[0].message.content
print(text)

Control With Temperature

The temperature setting controls randomness. Low values give steady answers; high values give more creative, varied ones.

Cap the Output

Setting max tokens limits how long the reply can be, which keeps responses tidy and your costs predictable.

Handle Failures

Networks fail and limits get hit, so wrap calls in try/except and retry gracefully when an error comes back.

Quick Check

Where do you find the model's text in a chat completion response?

Recap

Install a client, load your key from the environment, send role-tagged messages, then read the text from the first choice. ✅

常见问题解答

「从 Python 调用 LLM」课时是免费的吗?

是的 — 「从 Python 调用 LLM」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NLP Academy 课程的其余内容,请升级到 CoddyKit PRO。 NLP Academy 课程共包含 4 节课。

「从 Python 调用 LLM」这节课中我会学到什么?

发送提示并解析响应 你通过在浏览器中直接运行的动手代码来练习 NLP Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 NLP Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 NLP Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「从 Python 调用 LLM」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 NLP Academy 课中编写并运行代码吗?

能。每节 NLP Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 模型为何会变大
  2. 从 Python 调用 LLM
  3. 零样本与少样本提示
  4. 结构化输出与防护机制
← 返回 NLP Academy