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

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

相关推荐
uncle_ll6 小时前
RAG系统中的文本分块技术:从基础策略到智能分块的深度解析
llm·agent·dify·rag
编程小白_正在努力中6 小时前
第四章深度解析:智能体经典范式实战指南——从ReAct到Reflection的全流程拆解
人工智能·agent·智能体
码码哈哈爱分享9 小时前
500额度claude4.5无线续杯教程
ai编程
世界那么哒哒11 小时前
LangChain v1.0+ 如何构建自定义中间件来拦截和控制 Agent 执行过程
langchain·agent
勿芮介15 小时前
[大模型应用].Net下接入VLM多模态模型分析
.net·ai编程
常先森15 小时前
【解密源码】 RAGFlow 切分最佳实践- paper 篇
架构·llm·agent
温柔哥`16 小时前
PANDA:通过代理型 AI 工程师迈向通用视频异常检测
大模型·agent·rag·vad·视频异常检测·工具调用·mllms
橙武低代码1 天前
业务流低代码平台:从理念到实战
android·低代码·ai编程
webmote1 天前
使用Claude Code进行编程——国内用户使用指南
ai编程·claude·代理·码农·claude code
却尘1 天前
🚀 MCP基础完全上手指南:让Claude像开挂一样调用外部工具
aigc·ai编程·mcp