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

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

相关推荐
CaracalTiger4 小时前
告别云端依赖!ComfyUI本地化视频生成实战教程+cpolar实战
python·gpt·开源·aigc·ai编程·1024程序员节·ai-native
CoderJia程序员甲5 小时前
GitHub 热榜项目 - 日榜(2025-10-25)
ai·开源·github·ai编程·github热榜
飞哥数智坊6 小时前
Cursor + CloudBase,两周闲暇时间做出我的“AI 碎片助理”
人工智能·ai编程
云起SAAS11 小时前
空号号码状态检测抖音快手微信小程序看广告流量主开源
ai编程·1024程序员节·看广告变现轻·空号号码状态检测
大模型教程1 天前
如何构建你的Agents|谷歌Agents白皮书
google·llm·agent
大模型教程1 天前
构建可靠AI Agent:从提示词、工作流到知识库的实战指南
程序员·llm·agent
AI大模型1 天前
OpenAI 官方出品:从 0 到 1 构建 AI Agent 实战指南
程序员·llm·agent
AI大模型1 天前
《Hello-Agents》项目正式发布,一起从零学习智能体!
程序员·llm·agent
The 旺1 天前
【AI编程实战】零基础用ChatGPT+Cursor开发完整Web应用:30分钟从idea到上线
前端·chatgpt·ai编程
飞哥数智坊1 天前
想用好 AI 编程?你可能得先学点管理
人工智能·ai编程