FastGPT源码解析 Agent 智能体插件实现,以获取天气预报为样例

FastGPT 天气预报插件开发文档

概述

本文档介绍如何为 FastGPT 开发一个天气预报插件,该插件可以查询指定城市的实时天气信息,包括温度、湿度、风速等详细数据。

插件结构

天气预报插件包含两个核心文件:

复制代码
packages/plugins/src/weather/
├── index.ts          # 插件核心逻辑
└── template.json     # 插件配置模板

核心文件说明

1. index.ts - 插件逻辑实现

typescript 复制代码
type Props = {
  city: string;
  lang?: string;
};

type Response = Promise<{
  weather: string;
  temperature: string;
  humidity: string;
  windSpeed: string;
  description: string;
}>;

const main = async ({ city, lang = 'zh' }: Props): Response => {
  try {
    const weatherData = await mockWeatherAPI(city, lang);
    
    return {
      weather: weatherData.weather,
      temperature: weatherData.temperature,
      humidity: weatherData.humidity,
      windSpeed: weatherData.windSpeed,
      description: weatherData.description
    };
  } catch (error) {
    return {
      weather: '未知',
      temperature: '--°C',
      humidity: '--%',
      windSpeed: '--km/h',
      description: `获取${city}天气信息失败,请稍后重试`
    };
  }
};

关键特性:

  • 接收城市名称和语言参数
  • 返回结构化的天气数据
  • 包含错误处理机制
  • 支持异步操作

2. template.json - 插件配置

配置文件定义了插件的基本信息和工作流:

json 复制代码
{
  "name": "天气预报查询",
  "intro": "查询指定城市的实时天气信息,包括温度、湿度、风速等详细数据。",
  "isTool": true,
  "templateType": "tools"
}

工作流节点:

  1. 插件开始节点 - 定义输入参数(城市名称、语言)
  2. HTTP请求节点 - 处理天气数据获取
  3. 插件输出节点 - 返回天气信息

输入参数

参数名 类型 必填 描述 示例
city string 城市名称 "北京", "上海", "深圳"
lang string 语言设置 "zh"(中文), "en"(英文)

输出数据

字段名 类型 描述 示例
weather string 天气状况 "晴天", "多云", "小雨"
temperature string 当前温度 "25°C"
humidity string 湿度 "65%"
windSpeed string 风速 "15km/h"
description string 详细描述 "北京当前晴天,气温25°C..."

使用方法

1. 在对话中调用

复制代码
用户:北京今天天气怎么样?
AI:我来为您查询北京的天气信息...

2. 在工作流中使用

  1. 添加"天气预报查询"插件到工作流
  2. 配置城市名称输入
  3. 连接到后续处理节点

实际部署配置

替换真实天气API

将模拟API替换为真实的天气服务:

typescript 复制代码
// 替换 mockWeatherAPI 函数
async function getWeatherFromAPI(city: string, lang: string) {
  const apiKey = process.env.WEATHER_API_KEY;
  const response = await fetch(
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&lang=${lang}`
  );
  const data = await response.json();
  
  return {
    weather: data.weather[0].main,
    temperature: `${Math.round(data.main.temp - 273.15)}°C`,
    humidity: `${data.main.humidity}%`,
    windSpeed: `${data.wind.speed}km/h`,
    description: `${city}当前${data.weather[0].description}...`
  };
}

环境变量配置

.env 文件中添加:

env 复制代码
WEATHER_API_KEY=your_weather_api_key_here

扩展功能

1. 支持更多天气数据

typescript 复制代码
type Response = Promise<{
  // 基础数据
  weather: string;
  temperature: string;
  humidity: string;
  windSpeed: string;
  
  // 扩展数据
  pressure: string;        // 气压
  visibility: string;      // 能见度
  uvIndex: string;         // 紫外线指数
  forecast: Array<{        // 未来几天预报
    date: string;
    weather: string;
    tempHigh: string;
    tempLow: string;
  }>;
}>;

2. 支持地理位置

typescript 复制代码
type Props = {
  city?: string;
  lat?: number;    // 纬度
  lon?: number;    // 经度
  lang?: string;
};

3. 缓存机制

typescript 复制代码
const weatherCache = new Map();

const main = async ({ city, lang = 'zh' }: Props): Response => {
  const cacheKey = `${city}-${lang}`;
  const cached = weatherCache.get(cacheKey);
  
  if (cached && Date.now() - cached.timestamp < 300000) { // 5分钟缓存
    return cached.data;
  }
  
  const weatherData = await getWeatherFromAPI(city, lang);
  weatherCache.set(cacheKey, {
    data: weatherData,
    timestamp: Date.now()
  });
  
  return weatherData;
};

测试方法

1. 单元测试

typescript 复制代码
import weatherPlugin from './index';

describe('Weather Plugin', () => {
  test('should return weather data for valid city', async () => {
    const result = await weatherPlugin({ city: '北京' });
    
    expect(result.weather).toBeDefined();
    expect(result.temperature).toMatch(/\d+°C/);
    expect(result.description).toContain('北京');
  });
  
  test('should handle invalid city gracefully', async () => {
    const result = await weatherPlugin({ city: 'InvalidCity' });
    
    expect(result.weather).toBe('未知');
    expect(result.description).toContain('失败');
  });
});

2. 集成测试

在 FastGPT 应用中创建测试对话,验证插件功能。

注意事项

  1. API限制 - 注意天气API的调用频率限制
  2. 错误处理 - 确保网络异常时有合适的降级处理
  3. 数据格式 - 统一温度、湿度等数据的显示格式
  4. 多语言 - 根据lang参数返回对应语言的天气描述
  5. 缓存策略 - 避免频繁调用外部API

通过本插件示例,只作为实现思路和参考,实际测试以自己环境为准

相关推荐
后端小肥肠2 小时前
OpenClaw实战|从识图到公众号内容自动化,我跑通了完整链路
人工智能·aigc·agent
用户47949283569153 小时前
你不知道的 Claude Code:一行 Fetch 背后的双模型架构
agent·claude
Makesths3 小时前
【JSReverser-MCP】一句话逆向猿人学21题
ai·ai编程
用户47949283569153 小时前
MCP VS SKILLS:你以为你懂了,其实没有
agent·mcp
saifeng5 小时前
安装 Claude Code
ai编程
多年小白5 小时前
OpenClaw 本周技术更新速递
人工智能·ai·ai编程·openclaw
swipe5 小时前
为什么 RAG 一定离不开向量检索:从文档向量化到语义搜索的工程实现
前端·llm·agent
mCell6 小时前
Harness 工程:不是新词,而是 Agent 工程终于被讲明白了
agent·ai编程·claude
OpenTiny社区6 小时前
AI-Extension:让 AI 真的「看得到、动得了」你的浏览器
前端·ai编程·mcp
FserSuN7 小时前
langchain deepagents 框架使用带脚本的Skill
langchain·ai编程