AI实战之dify中自定义插件和agent开发

之前测试了dify中的插件,我们现在试一下自定义的

首先确保电脑已经有了Python,我电脑之前就有了

cmd打开Python项目,输入

conda activate text1

激活conda环境,(我这个Python之前经常用了,还没有安装的可以搜一下教程)

pip install fastapi uvicorn requests -i https://pypi.tuna.tsinghua.edu.cn/simple

从清华源下载我们用到的包会很快

pip show fastapi uvicorn requests

可见成功.打开pycharm开始代码编写

from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel
import requests

app = FastAPI()

# 身份验证令牌(个人使用,简单安全)
VALID_TOKEN = "weathertest"

# 城市编码数据(直接硬编码,无需外部文件)
CITY_CODES = {
    "北京": "101010100",
    "上海": "101020100",
    "广州": "101280101",
    "深圳": "101280601",
    "杭州": "101210101",
    "成都": "101270101",
    "武汉": "101200101",
    "西安": "101110101",
    "南京": "101190101",
    "重庆": "101040100",
    "天津": "101030100",
    "苏州": "101190401",
    "郑州": "101180101",
    "长沙": "101250101",
    "青岛": "101120201",
    "大连": "101070201",
    "宁波": "101210401",
    "厦门": "101230201",
    "福州": "101230101",
    "济南": "101120101",
    "合肥": "101220101",
    "南昌": "101240101",
    "昆明": "101290101",
    "南宁": "101300101",
    "贵阳": "101260101",
    "哈尔滨": "101050101",
    "长春": "101060101",
    "沈阳": "101070101",
    "石家庄": "101090101",
    "太原": "101100101",
    "呼和浩特": "101080101",
    "乌鲁木齐": "101130101",
    "拉萨": "101140101",
    "兰州": "101110501",
    "西宁": "101150101",
    "银川": "101170101",
    "海口": "101310101",
    "三亚": "101310201"
}

class WeatherRequest(BaseModel):
    location: str

@app.post("/weather")
def get_current_weather(request: Request, body: WeatherRequest):
    """
    天气查询接口
    - 需要Authorization头认证
    - 返回自然语言格式的天气信息
    """
    # 1. 验证身份
    auth_header = request.headers.get("Authorization")
    if auth_header != f"Bearer {VALID_TOKEN}":
        raise HTTPException(status_code=403, detail="Invalid Authorization header")
    
    location = body.location
    
    # 2. 查找城市编码
    city_code = CITY_CODES.get(location)
    if not city_code:
        return {
            "status": "error",
            "message": f"请提供{location}对应的编码方可查询,目前支持的城市:{','.join(CITY_CODES.keys())}"
        }
    
    # 3. 调用天气API
    url = f"http://t.weather.itboy.net/api/weather/city/{city_code}"
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        data = response.json()
    except Exception as e:
        return {"status": "error", "message": f"天气服务请求失败: {str(e)}"}
    
    # 4. 解析天气数据
    try:
        forecast = data["data"]["forecast"][0]
        weather_type = forecast["type"]
        high = forecast["high"].replace("高温 ", "")
        low = forecast["low"].replace("低温 ", "")
        temperature = f"{high}/{low}"
        
        # 5. 返回自然语言格式
        return f"{location}今天是{weather_type},温度{temperature}"
    except (KeyError, IndexError) as e:
        return {"status": "error", "message": f"天气数据解析失败: {str(e)}"}

# 启动入口
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8081)

这个令牌很重要啊

启动这个代码

python defweathercomponent.py

INFO:     Uvicorn running on http://0.0.0.0:8081 (Press CTRL+C to quit)就证明有了

下一步是公网穿透,由于我本地装了node.js

安装 localtunnel

打开 新的终端(不要关之前运行 main.py 的窗口)

npm install -g localtunnel

启动穿透(获取公网地址)

继续在这个终端输入:

lt --port 8081

成功标志:会出现一行:

your url is: https://xxxx-xxxx-xxxx.loca.lt

复制下来

接下来用apifox测试一下(apifox也是之前安装用过了)新建一个快速请求

然后点击headers添加两个头,把刚才复制来的url加上/weather然后post一下

代码里写了密钥是 weathertest,这个一定要对的上,不然密钥不对

总结一下

这里看到已经又返回了,回到dify界面

千万注意,我这里复制后,盖掉了一个冒号,导致我一直报503,看日志才改好,千万别粗心啊

回到工作室创建agent

目前没有添加刚才的api

这里勾选刚才的自定义工具

成功了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值