AI大模型小白手册 | API调用的魔法指南

引言

在上一篇文章中,我们深入探讨了大模型的原理和演进历程。你可能已经被这些"超级大脑"的能力所震撼,但心中可能还有一个疑问:作为一个开发者或技术爱好者,我该如何真正"使用"这些能力?

答案是:通过API调用。

想象一下,你不需要了解内燃机的所有原理,也能开车去任何地方;同样,你不需要训练自己的大模型,也能享受AI的强大能力。API就是这辆"AI汽车"的方向盘和油门。

本文将手把手教你掌握AI大模型API调用的核心技能,从基本概念到实际应用,让你能够在快速将AI能力集成到项目中。

系列目录(持续更新):

AI大模型小白手册|基础原理篇 - 掘金

一、API调用基础:理解"与AI对话"的技术栈

什么是AI模型API?

API(Application Programming Interface)是应用程序编程接口的简称。在大模型领域,API是你与云端AI模型交互的桥梁。

简单来说: 你发送一个问题(Prompt)→ API将其传递给云端模型 → 模型思考并生成回答 → API将答案返回给你。

二、准备工作:选择合适的平台和工具

2.1 主流AI API平台对比

平台 代表模型 主要优势 适合场景
OpenAI GPT-4, GPT-3.5 技术最成熟,生态最完善 国际项目,英文场景
阿里云DashScope 通义千问系列 中文优化好,性价比高 中文应用,企业级项目
DeepSeek API DeepSeek系列 推理能力强,价格亲民 代码生成,逻辑推理
百度文心千帆 文心一言 中文理解深,集成百度生态 内容创作,搜索增强
智谱AI GLM系列 开源友好,技术透明 定制开发,研究项目

2.2 阿里云DashScope:中文开发者的首选平台

在众多AI平台中,阿里云DashScope 很适合中文开发者,因为有以下核心优势:

  1. 原生中文优化:通义千问系列模型对中文语境、文化、表达有深度理解

  2. 稳定可靠:背靠阿里云基础设施,服务稳定性和可用性极高

  3. 性价比高:价格亲民,提供丰富的免费额度供开发者体验

  4. 生态完整:与阿里云其他服务(OSS、函数计算等)无缝集成

  5. 模型丰富:提供从轻量级到顶级的全系列模型

DashScope提供了丰富的模型选择,满足不同场景需求:

模型系列 代表模型 参数量级 主要特点 适用场景
通义千问 Qwen-Max 千亿级 最强能力,综合表现最佳 复杂推理、专业问答、代码生成
Qwen-Plus 百亿级 性价比高,能力均衡 日常对话、内容创作、分析任务
Qwen-Turbo 十亿级 响应快,成本低 简单问答、实时交互、高频调用
视觉模型 Qwen-VL 多模态 图文理解与生成 图像描述、图文问答、文档理解
代码模型 CodeQwen 专用优化 代码生成与解释 编程辅助、代码审查、技术解答
数学模型 Math-模型 数学优化 逻辑推理与计算 数学解题、数据分析、科研辅助

三、5分钟搞定"AI驾驶证":从注册到跑通第一个程序

3.1 三步拿钥匙(API Key)

Step 1:打开 阿里云百炼平台,用支付宝扫码登录(学生党福音,不用企业认证)。

Step 2:左侧导航栏找到「API-KEY」→ 右上角「创建新的API-KEY」→ 复制那串sk-开头的代码。

Step 3(重点):别直接把密钥写代码里!养成安全习惯:

临时配置(当前终端会话):

ini 复制代码
# Mac/Linux终端
export DASHSCOPE_API_KEY="sk-xxxxxxxx"

# Windows CMD
set DASHSCOPE_API_KEY=sk-xxxxxxxx

永久配置方式:

bash 复制代码
如果用的是zshrc,修改 .zshrc 文件
echo 'export DASHSCOPE_API_KEY="your_api_key_here"' >> ~/.zshrc
source ~/.zshrc

如果用的bash_profile,修改 .bash_profile 文件
echo 'export DASHSCOPE_API_KEY="your_api_key_here"' >> ~/.bash_profile
source ~/.bash_profile

验证配置

bash 复制代码
echo $DASHSCOPE_API_KEY

3.2 你的第一个AI对话(10行代码跑起来)

创建first_ai.py,复制下面代码:

ini 复制代码
import dashscope, os

# 从环境变量读取密钥
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")

# 构建对话历史(列表就是聊天记录)
messages = [
    {"role": "user", "content": "用小学生能听懂的话,解释什么是人工智能"}
]

# 调用模型(qwen-turbo是性价比之王)
response = dashscope.Generation.call(
    model="qwen-turbo",
    messages=messages,
    result_format='message'  # 必须加这个,否则返回格式老版本
)

# 提取并打印回答
print("AI说:", response.output.choices[0].message.content)

3.3 DashScope基础语法

1️⃣ 设置密钥

ini 复制代码
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")

2️⃣ 构建对话(永远是列表套字典)

ini 复制代码
messages = [
    {"role": "system", "content": "你是AI助手"},  # 可选:给AI定人设
    {"role": "user", "content": "你好"}           # 必填:你的问题
]

"角色"role的区别

system是"导演",user是"观众",assistant是"演员",function/tool是"道具"。

角色 通俗解释 什么时候用 示例代码
user 你提的问题 每次必须出现 {"role": "user", "content": "今天天气怎样"}
assistant AI上次的回答 多轮对话时追加 {"role": "assistant", "content": "需要查哪个城市?"}
system 给AI定"人设" 需要AI扮演特定角色时 {"role": "system", "content": "你是专业医生"}
function 函数返回的结果 AI调用你的函数后,把结果喂给它 {"role": "function", "name": "get_weather", "content": "北京28度"}
tool 新版工具结果 新版Function Call用,作用同function {"role": "tool", "name": "get_weather", "content": "北京28度"}

3️⃣ 调用模型(5个核心参数)

ini 复制代码
response = dashscope.Generation.call(
    model="qwen-turbo",        # 用哪个模型(见第三章)
    messages=messages,          # 对话历史
    result_format='message',    # 必须!否则返回老格式
    temperature=0.7,            # 可选:AI的"创造力"旋钮
    max_tokens=1500             # 可选:让AI说多少字
)

参数解释:

参数 类型 默认值 人话解释 调参技巧
model string 必填 选哪个"专家"回答 简单任务用turbo,复杂任务用max
messages list 必填 聊天记录 像微信聊天,一条一条追加
result_format string 必填 返回格式 永远写'message',不然取不到答案
temperature float 0.7 AI的"脑洞"大小 0=不脑洞(写合同),1=脑洞全开(写小说)
max_tokens int 1024 最多说几个字 长文章设2000,短问答设500
stream bool False 是否打字机式输出 聊天机器人设True,体验更好

4️⃣ 提取回答

获取结果的三种方式(根据需求选)

lua 复制代码
 # 方式1:同步等待(简单,推荐新手)  response = dashscope.Generation.call(...) answer = response.output.choices[0].message.content print (answer) # 一次性打印全部   # 方式2:流式输出(像ChatGPT那样逐字蹦,体验好)  response = dashscope.Generation.call(..., stream=True) for chunk in response:  print (chunk.output.choices[0].message.content, end= '' ) # end=''防止换行   # 方式3:检查返回状态(生产环境用)  if response.status_code == 200: # HTTP成功  answer = response.output.choices[0].message.content else :  print (f "报错啦:{response.message}" ) # 打印错误信息

四、进阶玩法

4.1 立人设:AI会更听话

System Prompt:AI的"角色扮演"开关

普通对话AI容易"一本正经",但加上system prompt,它能秒变任何角色:

ini 复制代码
import dashscope, os

# 从环境变量读取密钥
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")
print("API Key:", dashscope.api_key)

messages = [
    {"role": "system", "content": "你是一位暴躁的东北烧烤店老板,说话必须带'嘎哈呢'、'整点啥'等东北话"},
    {"role": "user", "content": "推荐个招牌菜"}
]

response = dashscope.Generation.call(
    model="qwen-turbo",
    messages=messages,
    result_format='message'  # 必须加这个,否则返回格式老版本
)

# 提取并打印回答
print("AI说:", response.output.choices[0].message.content)

输出

复制代码
AI说: 哎呦喂!你这小子可算来对地方了!咱家的招牌菜那可真是绝了,整点啥啊?我跟你说啊,这烤串儿是咱们东北老铁们最爱的玩意儿,特别是那个羊蝎子,嘎哈呢?那叫一个香!肉质嫩得跟豆腐似的,配上咱家特制的调料,啧啧,好吃得不行!

不过你要是想吃点别的,咱家还有烧烤鸡翅、烤鱿鱼、烤茄子什么的,都是现烤现卖,保证新鲜!你倒是说说,你想整点啥?我给你推荐几样最拿手的!

4.2 Function Call:天气查询

场景:用户问"北京今天几度?",AI不能瞎猜,它需要调用真实函数去查。

原理:你提前告诉AI"我有查天气工具",AI会自动判断何时该调用它,并自己填参数。

1️⃣ 导入必要的库和设置API密钥

导入库,设置 API 密钥

python 复制代码
import json          # 用于处理JSON格式数据
import os            # 操作系统相关功能
import dashscope     # 阿里云DashScope SDK,用于调用Qwen模型
from dashscope.api_entities.dashscope_response import Role
dashscope.api_key = "sk-xxx"  # 设置API密钥

2️⃣ 定义天气查询函数 get_current_weather

这是一个模拟的天气查询函数,实际应用中应该调用真实的天气API。根据不同的城市返回不同的温度

ini 复制代码
def get_current_weather(location, unit="摄氏度"):
    temperature = -1
    if '大连' in location or 'Dalian' in location:
        temperature = 10
    if location=='上海':
        temperature = 36
    if location=='深圳':
        temperature = 37
    weather_info = {
        "location": location,
        "temperature": temperature,
        "unit": unit,
        "forecast": ["晴天", "微风"],
    }
    return json.dumps(weather_info)

3️⃣ 定义API调用函数

封装了对Qwen模型的API调用。接收对话消息列表、调用Qwen模型、返回模型的响应、如果出错,打印错误信息并返回None

python 复制代码
def get_response(messages):
    try:
        response = dashscope.Generation.call(
            model='qwen-turbo',      # 使用的模型名称
            messages=messages,       # 对话历史
            functions=functions,     # 可用的函数列表
            result_format='message'  # 返回格式
        )
        return response
    except Exception as e:
        print(f"API调用出错: {str(e)}")
        return None

4️⃣ 定义函数描述(Function Schema)

告诉AI模型有哪些函数可以调用,以及这些函数需要什么参数。

  • name:函数名,必须和实际定义的函数名一致
  • description:告诉AI什么时候应该调用这个函数
  • parameters:定义函数需要的参数类型和格式
  • required:哪些参数是必须的
ini 复制代码
functions = [
    {
      'name': 'get_current_weather',           # 函数名称
      'description': 'Get the current weather in a given location.',  # 函数描述
      'parameters': {
            'type': 'object',
            'properties': {
                'location': {
                    'type': 'string',
                    'description': 'The city and state, e.g. San Francisco, CA'
                },
                'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}
            },
        'required': ['location']  # 必填参数
      }
    }
]

5️⃣ 主对话函数(核心逻辑)

5.1 初始化对话

准备用户的提问,格式化为模型需要的消息格式。

ini 复制代码
def run_conversation():
    query = "上海的天气怎样"  # 用户的问题
    messages=[{"role": "user", "content": query}]  # 创建消息列表

5.2 第一次调用模型(判断是否需要调用函数)

  1. 将用户问题发送给Qwen模型
  2. 模型分析问题:"上海的天气怎样"
  3. 模型看到有get_current_weather函数可用
  4. 模型决定:需要调用这个函数来获取天气信息
  5. 模型返回:function_call,表示要调用函数,而不是直接回答
python 复制代码
    # 得到第一次响应
    response = get_response(messages)
    if not response or not response.output:
        print("获取响应失败")
        return None
        
    print('response=', response)
    
    message = response.output.choices[0].message  # 提取模型返回的消息
    messages.append(message)  # 将模型响应添加到消息历史
    print('message=', message)

返回示例

json 复制代码
{
  "role": "assistant",
  "content": "",
  "function_call": {
    "arguments": "{"location": "上海"}",
    "name": "get_current_weather"
  }
}

5.3 执行函数调用

判断用户是否要call function

  1. 检查 :模型是否要求调用函数?是的,有function_call

  2. 提取信息

  • 函数名:get_current_weather
  • 参数:{"location": "上海"}
  1. 执行函数 :调用get_current_weather(location="上海")
  • 返回:{"location": "上海", "temperature": 36, "unit": null, "forecast": ["晴天", "微风"]}
  1. 记录结果:将函数执行结果添加到消息历史中
python 复制代码
    if hasattr(message, 'function_call') and message.function_call:
        function_call = message.function_call
        tool_name = function_call['name']  # 获取函数名:'get_current_weather'
        
        # Step 3, 执行function call
        arguments = json.loads(function_call['arguments'])  # 解析参数:{'location': '上海'}
        print('arguments=', arguments)
        
        # 调用实际的函数
        tool_response = get_current_weather(
            location=arguments.get('location'),  # '上海'
            unit=arguments.get('unit'),          # None(未提供)
        )
        
        # 将函数执行结果添加到消息历史
        tool_info = {"role": "function", "name": tool_name, "content": tool_response}
        print('tool_info=', tool_info)
        messages.append(tool_info)
        print('messages=', messages)

此时messages列表包含

bash 复制代码
[
    {"role": "user", "content": "上海的天气怎样"},                    # 用户问题
    {"role": "assistant", "content": "", "function_call": {...}},    # 模型要求调用函数
    {"role": "function", "name": "get_current_weather", "content": "..."}  # 函数执行结果
]

5.4 第二次调用模型(生成最终回答)

lua 复制代码
  response = get_response(messages)
  if not response or not response.output:
     print("获取第二次响应失败")
     return None
            
     print('response=', response)
     message = response.output.choices[0].message
     return message
   return message

6️⃣ 执行主程序

当直接运行这个脚本时,执行对话流程并打印结果。

sql 复制代码
if __name__ == "__main__":
    result = run_conversation()
    if result:
        print("最终结果:", result)
    else:
        print("对话执行失败")

完整代码如下:

python 复制代码
import json, dashscope, os
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")

# 编写你的函数
def get_current_weather(location, unit="摄氏度"):
    # 获取指定地点的天气
    temperature = -1
    if '大连' in location or 'Dalian' in location:
        temperature = 10
    if location=='上海':
        temperature = 36
    if location=='深圳':
        temperature = 37
    weather_info = {
        "location": location,
        "temperature": temperature,
        "unit": unit,
        "forecast": ["晴天", "微风"],
    }
    # 返回json格式
    return json.dumps(weather_info)

# 封装模型响应函数
def get_response(messages):
    try:
        response = dashscope.Generation.call(
            model='qwen-turbo',
            messages=messages,
            functions=functions,
            result_format='message'
        )
        return response
    except Exception as e:
        print(f"API调用出错: {str(e)}")
        return None

# 使用function call进行QA
def run_conversation():
    query = "上海的天气怎样"
    messages=[{"role": "user", "content": query}]
    
    # 得到第一次响应
    response = get_response(messages)
    if not response or not response.output:
        print("获取响应失败")
        return None
        
    print('response=', response)
    
    message = response.output.choices[0].message
    messages.append(message)
    print('message=', message)
    
    # Step 2, 判断用户是否要call function
    if hasattr(message, 'function_call') and message.function_call:
        function_call = message.function_call
        tool_name = function_call['name']
        # Step 3, 执行function call
        arguments = json.loads(function_call['arguments'])
        print('arguments=', arguments)
        tool_response = get_current_weather(
            location=arguments.get('location'),
            unit=arguments.get('unit'),
        )
        tool_info = {"role": "function", "name": tool_name, "content": tool_response}
        print('tool_info=', tool_info)
        messages.append(tool_info)
        print('messages=', messages)
        
        #Step 4, 得到第二次响应
        response = get_response(messages)
        if not response or not response.output:
            print("获取第二次响应失败")
            return None
            
        print('response=', response)
        message = response.output.choices[0].message
        return message
    return message

functions = [
    {
      'name': 'get_current_weather',
      'description': 'Get the current weather in a given location.',
      'parameters': {
            'type': 'object',
            'properties': {
                'location': {
                    'type': 'string',
                    'description': 'The city and state, e.g. San Francisco, CA'
                },
                'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}
            },
        'required': ['location']
      }
    }
]

# 主函数
if __name__ == "__main__":
    result = run_conversation()
    if result:
        print("最终结果:", result)
    else:
        print("对话执行失败")

五、附录

相关推荐
跨境小渊2 小时前
从“冷启动”到“热转化”——DeepBI赋能listing优化:实战案例揭示投放新突破
人工智能
泰迪智能科技2 小时前
分享|陕西高校大数据人工智能实验室建设内容+建设成效
大数据·人工智能
TOWE technology2 小时前
智联电力基石:从运维视角看数据中心PDU的演进与未来
大数据·人工智能·数据中心·pdu·智能pdu·定制电源管理·idc数据中心
Coder_Boy_2 小时前
SpringAI与LangChain4j的智能应用-(实践篇4)
java·人工智能·spring boot·langchain
zhaodiandiandian2 小时前
从深度学习到大模型,AI技术演进的机遇与挑战
人工智能·深度学习
KJYHS2 小时前
亚马逊新手运营:AI 找竞品实操指南
大数据·人工智能
confiself2 小时前
GUI Agent数据集收集
人工智能
ekprada2 小时前
Day50 - 预训练模型与CBAM集成
人工智能·深度学习·机器学习