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

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

相关推荐
C澒13 分钟前
IntelliPro 企业级产研协作平台:前端智能生产模块设计与落地
前端·ai编程
Cosolar41 分钟前
Nanobot 深度解析:超轻量级通用 AI Agent 运行时的架构设计与实战指南
gpt·llm·ai编程
孟健1 小时前
我把Hermes里23个Agent全切到GLM-5.1:执行力比GPT强,但有个硬伤
ai编程
爱吃的小肥羊1 小时前
2026 最新 Codex 如何使用指南:ChatGPT 订阅、CLI 安装、App 登录全流程
aigc·ai编程
OpenTiny社区1 小时前
重磅预告|OpenTiny 亮相 QCon 北京,共话生成式 UI 最新技术思考
前端·开源·ai编程
小村儿2 小时前
Harness Engineering:为什么你用 AI 越用越累?
前端·后端·ai编程
Bryceee3 小时前
一个本地 AI Agent 是怎么跑起来的
agent·ai编程
该用户已不存在4 小时前
Claude Mythos 发布,强到刚出道就被雪藏?
aigc·ai编程·claude
飞龙14775657467504 小时前
从零创建 skill:Skill Creator 项目全解析
agent
房贷压不垮的码农4 小时前
5 分钟极速入门:用 Python 和 ChromaDB 体验向量数据库的魅力
ai编程