第4讲:你的第一个 Skill:Hello World 实战

第4讲:你的第一个 Skill:Hello World 实战

动手创建你的第一个 AI Skill,完成从理论到实践的跨越。


一、准备工作

1.1 注册 Coze 账号

  1. 访问 https://www.coze.cn
  2. 使用手机号或抖音账号注册
  3. 完成实名认证(如需发布到商店)

1.2 了解 Coze 界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
┌─────────────────────────────────────────────────────────┐
│ Coze 工作台 │
├──────────────┬──────────────────────────────────────────┤
│ │ │
│ 导航栏 │ 编辑区域 │
│ ├── 团队空间 │ ┌─────────────────────┐ │
│ ├── 个人空间 │ │ 人设与回复逻辑 │ │
│ ├── 插件 │ │ ├── 角色设定 │ │
│ ├── 工作流 │ │ ├── 技能配置 │ │
│ └── 知识库 │ │ └── 开场白 │ │
│ │ └─────────────────────┘ │
│ │ ┌─────────────────────┐ │
│ │ │ 预览与调试区域 │ │
│ │ │ └── 右侧聊天窗口 │ │
│ │ └─────────────────────┘ │
└──────────────┴──────────────────────────────────────────┘

二、创建第一个 Skill:天气查询助手

2.1 创建 Bot

  1. 点击「创建 Bot」
  2. 填写基本信息:
    • 名称:天气小助手
    • 描述:帮你查询全国各地的天气情况
    • 图标:上传或选择系统图标
  3. 点击「确认」

2.2 配置人设与回复逻辑

在「人设与回复逻辑」区域输入:

1
2
3
4
5
6
7
8
9
10
11
12
# 角色
你是一个专业的天气查询助手,能够准确回答用户关于天气的各种问题。

## 技能
- 查询指定城市的实时天气
- 查询未来 3 天的天气预报
- 提供穿衣、出行建议

## 限制
- 只能查询中国城市的天气
- 如果用户没有指定城市,询问用户所在城市
- 使用中文回复,语气友好亲切

2.3 添加天气查询插件

  1. 点击「插件」右侧的「+」
  2. 搜索「天气」
  3. 选择「墨迹天气」或「心知天气」插件
  4. 点击「添加」

2.4 测试你的 Skill

在右侧预览区域输入:

1
北京今天天气怎么样?

预期输出:

1
2
北京今天天气晴朗,气温 15-25°C,空气质量良,适合户外活动。
建议穿着:薄外套 + 长袖

三、进阶:让 Skill 更智能

3.1 添加工作流

创建一个新的工作流「weather_workflow」:

1
2
3
4
5
6
7
8
9
10
11
开始节点

参数提取节点(提取城市名)

天气查询插件节点(调用天气 API)

数据处理节点(格式化天气信息)

建议生成节点(生成穿衣/出行建议)

结束节点(返回结果)

3.2 工作流详细配置

参数提取节点:

1
2
3
4
5
6
7
8
9
10
11
# 使用大模型提取参数
prompt = """
从用户输入中提取城市名称:
用户输入:{{input}}

返回 JSON 格式:
{
"city": "城市名",
"date": "日期(今天/明天/后天)"
}
"""

天气查询节点:

1
2
3
4
5
6
# 调用墨迹天气插件
plugin: weather_moji
action: get_weather
params:
city: {{city}}
days: 3

建议生成节点:

1
2
3
4
5
6
7
8
9
10
11
12
prompt = """
根据以下天气信息,生成穿衣和出行建议:
城市:{{city}}
天气:{{weather}}
温度:{{temp_low}}°C - {{temp_high}}°C
空气质量:{{aqi}}

请给出:
1. 一句话天气总结
2. 穿衣建议
3. 出行建议
"""

3.3 绑定工作流到 Bot

  1. 回到 Bot 编辑页面
  2. 在「工作流」区域添加「weather_workflow」
  3. 在「人设与回复逻辑」中添加:
1
当用户询问天气时,调用 weather_workflow 工作流获取天气信息。

四、代码实现:从零搭建天气 Skill

如果你想用代码实现,以下是完整示例:

4.1 项目结构

1
2
3
4
5
6
weather-skill/
├── main.py # 主程序
├── intent.py # 意图识别
├── weather_api.py # 天气 API 封装
├── advisor.py # 建议生成
└── requirements.txt # 依赖

4.2 核心代码

main.py

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import json
from intent import IntentClassifier
from weather_api import WeatherAPI
from advisor import Advisor

class WeatherSkill:
"""天气查询 Skill"""

def __init__(self):
self.intent_classifier = IntentClassifier()
self.weather_api = WeatherAPI()
self.advisor = Advisor()

def run(self, user_input: str) -> str:
"""主入口"""
# 1. 识别意图
intent = self.intent_classifier.classify(user_input)

if intent['intent'] != 'query_weather':
return "我可以帮你查询天气,请告诉我你想查哪个城市?"

# 2. 提取城市
city = intent.get('entities', {}).get('city')
if not city:
return "请告诉我你想查询哪个城市的天气?"

# 3. 查询天气
try:
weather_data = self.weather_api.get_weather(city)
except Exception as e:
return f"抱歉,查询 {city} 天气失败:{str(e)}"

# 4. 生成建议
advice = self.advisor.generate(weather_data)

# 5. 组装回复
return self.format_response(weather_data, advice)

def format_response(self, weather, advice) -> str:
"""格式化输出"""
return f"""
🌤️ {weather['city']} 天气预报

📅 日期:{weather['date']}
🌡️ 温度:{weather['temp_low']}°C ~ {weather['temp_high']}°C
☁️ 天气:{weather['condition']}
💨 风力:{weather['wind']}
🌫️ 空气质量:{weather['aqi']}

💡 建议:
{advice}
""".strip()

# 运行
if __name__ == "__main__":
skill = WeatherSkill()

# 测试
test_inputs = [
"北京今天天气怎么样?",
"上海明天会下雨吗?",
"广州天气"
]

for user_input in test_inputs:
print(f"\n用户:{user_input}")
print(f"助手:{skill.run(user_input)}")

intent.py

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
42
43
44
45
46
47
48
49
50
51
import re
from typing import Dict, Any

class IntentClassifier:
"""意图识别器"""

# 天气相关关键词
WEATHER_KEYWORDS = ['天气', '气温', '温度', '下雨', '晴天', '预报']

# 城市列表(简化版)
CITIES = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安']

def classify(self, text: str) -> Dict[str, Any]:
"""识别意图"""
text = text.lower()

# 检查是否是天气查询
is_weather = any(kw in text for kw in self.WEATHER_KEYWORDS)

if not is_weather:
return {'intent': 'unknown', 'confidence': 0}

# 提取城市
city = self._extract_city(text)

# 提取日期
date = self._extract_date(text)

return {
'intent': 'query_weather',
'confidence': 0.95,
'entities': {
'city': city,
'date': date
}
}

def _extract_city(self, text: str) -> str:
"""提取城市名"""
for city in self.CITIES:
if city in text:
return city
return None

def _extract_date(self, text: str) -> str:
"""提取日期"""
if '明天' in text:
return 'tomorrow'
elif '后天' in text:
return 'day_after_tomorrow'
return 'today'

weather_api.py

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import requests
from typing import Dict, Any

class WeatherAPI:
"""天气 API 封装"""

def __init__(self, api_key: str = None):
self.api_key = api_key or "your_api_key"
self.base_url = "https://api.seniverse.com/v3"

def get_weather(self, city: str) -> Dict[str, Any]:
"""获取天气信息"""
# 这里使用示例数据,实际应调用真实 API
# 你可以申请心知天气 API:https://www.seniverse.com/

mock_data = {
'北京': {
'city': '北京',
'date': '2026-04-06',
'temp_low': 15,
'temp_high': 25,
'condition': '晴',
'wind': '北风 3级',
'aqi': '良'
},
'上海': {
'city': '上海',
'date': '2026-04-06',
'temp_low': 18,
'temp_high': 22,
'condition': '多云',
'wind': '东南风 2级',
'aqi': '优'
}
}

return mock_data.get(city, {
'city': city,
'date': '2026-04-06',
'temp_low': 20,
'temp_high': 28,
'condition': '晴',
'wind': '微风',
'aqi': '良'
})

def get_real_weather(self, city: str) -> Dict[str, Any]:
"""调用真实 API(需要申请 key)"""
url = f"{self.base_url}/weather/now.json"
params = {
'key': self.api_key,
'location': city,
'language': 'zh-Hans',
'unit': 'c'
}

response = requests.get(url, params=params)
data = response.json()

return {
'city': data['results'][0]['location']['name'],
'condition': data['results'][0]['now']['text'],
'temp': data['results'][0]['now']['temperature']
}

advisor.py

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
class Advisor:
"""建议生成器"""

def generate(self, weather: dict) -> str:
"""根据天气生成建议"""
temp_high = weather['temp_high']
condition = weather['condition']
aqi = weather['aqi']

suggestions = []

# 穿衣建议
if temp_high < 10:
suggestions.append("👔 穿衣:建议穿羽绒服,注意保暖")
elif temp_high < 20:
suggestions.append("👔 穿衣:建议穿外套,早晚温差大")
elif temp_high < 28:
suggestions.append("👔 穿衣:建议穿长袖或薄外套")
else:
suggestions.append("👔 穿衣:建议穿短袖,注意防晒")

# 出行建议
if '雨' in condition:
suggestions.append("☂️ 出行:记得带伞,路面湿滑注意安全")
elif temp_high > 30:
suggestions.append("🚗 出行:避免中午高温时段外出")
else:
suggestions.append("🚗 出行:天气不错,适合户外活动")

# 空气质量
if aqi in ['优', '良']:
suggestions.append("🌬️ 空气:空气质量不错,可以开窗通风")
else:
suggestions.append("😷 空气:空气质量一般,敏感人群减少外出")

return '\n'.join(suggestions)

requirements.txt

1
requests>=2.28.0

五、测试与调试

5.1 本地测试

1
2
3
4
5
# 安装依赖
pip install -r requirements.txt

# 运行测试
python main.py

5.2 常见错误处理

错误原因解决方案
无法识别城市城市名不在列表中扩展城市列表或使用模糊匹配
API 调用失败网络问题或 API key 无效检查网络,申请有效 API key
回复格式混乱格式化代码有问题检查 format_response 方法
意图识别错误关键词匹配不够准确增加关键词或使用大模型识别

六、发布到 Coze 商店

6.1 完善 Bot 信息

  1. 点击「发布」
  2. 填写发布信息:
    • Bot 介绍:详细描述 Skill 的功能
    • 使用场景:说明适合什么场景使用
    • 示例问题:提供 3-5 个示例对话

6.2 选择发布渠道

  • 豆包:字节跳动旗下 AI 助手
  • 飞书:企业协作平台
  • 微信:微信公众号/小程序
  • API:供开发者调用

6.3 审核与上架

  • 提交后等待平台审核(通常 1-3 个工作日)
  • 审核通过后即可在商店搜索到你的 Skill

七、下节预告

第5讲:Skill 的交互设计:让对话更自然

我们将学习:

  • 如何设计自然的对话流程
  • Prompt 工程技巧
  • 多轮对话管理
  • 错误处理和边界情况

加入学习群

学习过程中遇到问题?欢迎加入交流群:

👉 加入AI编程学习交流群

点击加入


本讲是《Skills 从入门到实践》系列课程的第4讲,下一讲我们将学习 Skill 的交互设计。

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!