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

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

相关推荐
yaocheng的ai分身7 小时前
Claude Code+GLM 4.6的一些必要配置
ai编程·claude·chatglm (智谱)
mCell8 小时前
MCP有了,Agents.md 又是什么?
ai编程·claude·mcp
OopsOutOfMemory16 小时前
LangChain源码分析(十三)- 运行时与监控
ai·langchain·aigc·ai编程·ai应用
大模型真好玩16 小时前
大模型Agent开发框架哪家强?12项Agent开发框架入门与选型
人工智能·agent·mcp
用户40993225021216 小时前
转账不翻车、并发不干扰,PostgreSQL的ACID特性到底有啥魔法?
后端·ai编程·trae
数据智能老司机18 小时前
建构 AI Agent 应用——Agentic 系统的学习机制
架构·llm·agent
十步杀一人_千里不留行19 小时前
和 AI 一起修 Bug 心得体会
人工智能·bug·ai编程
yaocheng的ai分身19 小时前
Token-efficient tool use
ai编程·claude
数据智能老司机21 小时前
建构 AI Agent 应用——编排
架构·llm·agent
后端研发Marion21 小时前
AI编程CLI编辑器技术对比分析:心流CLI vs OpenAI Codex vs Claude Code
编辑器·ai编程·codex·心流cli·cluade code