通过 AI 快速生成调用代码
通过 AI 快速生成调用代码
无需手写代码,直接让 AI 帮你生成完整的调用示例。
方法:复制文档给 AI
步骤
- 打开需要接入的 API 文档页面
- 复制文档内容(包括参数说明、示例等)
- 把文档内容贴给 ChatGPT / Claude / DeepSeek 等 AI
- 让 AI 生成对应语言的调用代码
示例 Prompt
将以下 Prompt 发送给任意 AI 助手:
我需要调用零度API,Base URL 是 https://api000.com/v1,
我的 API Key 是 sk-xxx(占位符,实际使用时替换)。
请帮我写一个 Python 脚本:
- 使用 OpenAI SDK 调用 gpt-4o 模型
- 实现多轮对话功能
- 支持 Ctrl+C 退出
- 打印每轮的 Token 消耗
各语言快速示例
Python — 多轮对话
from openai import OpenAI
client = OpenAI(
base_url="https://api000.com/v1",
api_key="sk-xxxxxxxxxxxxxxxx"
)
history = [{"role": "system", "content": "你是一个有帮助的助手。"}]
print("多轮对话示例(Ctrl+C 退出)")
while True:
user_input = input("\n你: ").strip()
if not user_input:
continue
history.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="gpt-4o",
messages=history
)
assistant_msg = response.choices[0].message.content
history.append({"role": "assistant", "content": assistant_msg})
print(f"\n助手: {assistant_msg}")
usage = response.usage
print(f"[Token: 输入 {usage.prompt_tokens} / 输出 {usage.completion_tokens}]")
Python — 流式输出
from openai import OpenAI
client = OpenAI(
base_url="https://api000.com/v1",
api_key="sk-xxxxxxxxxxxxxxxx"
)
print("助手: ", end="", flush=True)
stream = client.chat.completions.create(
model="gpt-4o",
stream=True,
messages=[{"role": "user", "content": "用 Python 写一个快速排序算法"}]
)
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)
print()
Node.js — 流式对话
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api000.com/v1",
apiKey: process.env.OPENAI_API_KEY,
});
async function chat(message) {
const stream = await client.chat.completions.create({
model: "gpt-4o",
stream: true,
messages: [{ role: "user", content: message }],
});
process.stdout.write("助手: ");
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) process.stdout.write(content);
}
console.log();
}
await chat("介绍一下零度API");
支持的 SDK
| SDK | 安装 | 官方文档 |
|---|---|---|
| Python openai | pip install openai |
docs.python.org |
| Node.js openai | npm install openai |
npmjs.com/openai |
| Go go-openai | go get github.com/sashabaranov/go-openai |
GitHub |
| Java | Maven: com.theokanning.openai-gpt3-java |
GitHub |
| LangChain Python | pip install langchain-openai |
LangChain Docs |
| LangChain.js | npm install @langchain/openai |
LangChain Docs |