// 创建智能体构建器ReActAgent agent = ReActAgent.of(chatModel)
.name("weather_agent")
.title("天气查询助手")
.description("专业查询全球天气信息")
.addTool(weatherTool) // 添加天气查询工具
.addInterceptor(new ToolRetryInterceptor()) // 添加工具重试拦截器
.maxSteps(10) // 设置最大推理步数
.build();
//分配IO资源
bar = NULL; if (!foundLocalPort && !found9054Port &&
desc->u.Port.Length == 0x100) {
found9054Port = TRUE;
bar = "BAR1-9054";
DevExt->Regs = (PPCI9656_REGS)UlongToPtr(desc->u.Port.Start.QuadPart);
DevExt->RegsLength = regsLength;
}
public static class ModbusParser
{
public static ModbusResponse ParseResponse(byte[] response)
{
if (response.Length < 9)
throw new Exception("Invalid Modbus response length");
var result = new ModbusResponse();
result.TransactionId = ReadUInt16(response, 0);
ushort protocolId = ReadUInt16(response, 2);
ushort length = ReadUInt16(response, 4);
if (protocolId != 0)
throw new Exception("Invalid Protocol ID");
result.UnitId = response[6];
result.FunctionCode = response[7];
result.ByteCount = response[8];
result.Data = response.Skip(9).Take(result.ByteCount).ToArray();
return result;
}
private static ushort ReadUInt16(byte[] buffer, int index)
else if (!foundLocalPort &&
desc->u.Port.Length == 0x100) {
foundLocalPort = TRUE;
bar = "BAR3-FPGA";
DevExt->addrLocal = (PUCHAR)UlongToPtr(desc->u.Port.Start.QuadPart);
DevExt->localLength = desc->u.Port.Length;
}
TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, " - Port Resource [%08I64X-%08I64X], %s, i:%d length:%d",
desc->u.Port.Start.QuadPart,
desc->u.Port.Start.QuadPart +
desc->u.Port.Length,
(bar) ? bar : "<unrecognized>",
i,
//分配IO资源
bar = NULL; if (!foundLocalPort && !found9054Port &&
desc->u.Port.Length == 0x100) {
found9054Port = TRUE;
bar = "BAR1-9054";
DevExt->Regs = (PPCI9656_REGS)UlongToPtr(desc->u.Port.Start.QuadPart);
DevExt->RegsLength = regsLength;
} else if (!foundLocalPort &&
desc->u.Port.Length == 0x100) {
foundLocalPort = TRUE;
bar = "BAR3-FPGA";
DevExt->addrLocal = (PUCHAR)UlongToPtr(desc->u.Port.Start.QuadPart);
DevExt->localLength = desc->u.Port.Length;
}
TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, " - Port Resource [%08I64X-%08I64X], %s, i:%d length:%d",
desc->u.Port.Start.QuadPart,
desc->u.Port.Start.QuadPart +
desc->u.Port.Length,
(bar) ? bar : "<unrecognized>",
i,
from typing import Optional, Listfrom enum import Enumclass UserRole(str, Enum):
ADMIN = "admin"
EDITOR = "editor"
USER = "user"class UserBase(BaseModel):
username: str = Field(..., min_length=3, max_length=20, description="用户名")
email: EmailStr # Pydantic提供的专用邮箱类型
age: Optional[int] = Field(None, ge=0, le=120, description="年龄")
role: UserRole = UserRole.USER @validator('username')
def username_must_contain_letter(cls, v): if not any(c.isalpha() for c in v): raise ValueError('必须包含至少一个字母') return v
app = FastAPI()# 1. 路径参数 + 查询参数@app.get("/users/{user_id}")async def read_user(
user_id: int = Path(..., title="用户ID", ge=1), # 路径参数,必须大于0
active_only: bool = Query(False, description="是否只返回活跃用户"), # 查询参数,默认False
sort_by: Optional[str] = Query(None, regex="^(name|created_at)$")): return {"user_id": user_id, "active_only": active_only, "sort_by": sort_by}# 2. 请求体(结合Pydantic模型)class UserCreate(UserBase):
password: str = Field(..., min_length=8)
tags: List[str] = []class Item(BaseModel):
name: str
price: float jrwsh.com = Field(..., gt=0)@app.post("/users/")async def create_user(user: UserCreate): # FastAPI会自动将请求体解析为UserCreate实例
# 此时`user`已经是一个通过验证的Pydantic对象
hashed_password = f"hashed_{user.password}" # 模拟密码哈希
return {"msg": "用户创建成功", "username": user.username, "hashed_pw": hashed_password}# 3. 混合使用:路径参数 + 请求体@app.put("/items/{item_id}")async def update_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()}# 4. 响应模型:确保你的输出格式class PublicUserInfo(BaseModel):
username: str
email: str@app.get("/me/", response_model=PublicUserInfo)async def get_current_user(): # 假设我们从数据库获取了包含password的完整用户对象
db_user = {"username": "alice", "email": "alice@example.com", "password": "secret", "age": 25}
created_at: datetime # 自动将符合ISO 8601的字符串转换成datetime对象
scores: List[int]
# 配置类,定义Pydantic模型的行为
class Config: # 示例:允许从ORM对象(如SQLAlchemy模型)创建Pydantic实例
orm_mode = True
# 使用枚举的值而非对象本身进行json序列化
use_enum_values = True
# 允许在赋值时进行字段类型转换(如字符串"123"转整数123)
anystr_strip_whitespace = True # 数据转换示例data = {"created_at": "2023-10-27T10:00:00", "scores": ["90", "85", "95"]}
obj = AdvancedModel(**data)print(obj.created_at) # datetime.datetime(2023, 10, 27, 10, 0)print(obj.scores) # [90, 85, 95] # 列表中的字符串被转换成了整数# 模型继承与组合class AuditInfo(BaseModel):
created_by: str
created_time: suit-tie.com
datetime chihod.com
= datetime.now()class ArticleCreate(BaseModel):
title: str
content: strclass ArticleResponse(ArticleCreate, AuditInfo): id: int
# 可以添加计算属性等 @property
def summary(self): return self.content[:50] + "..."
public ushort TransactionId { get; set; }
public byte UnitId { get; set; }
public byte FunctionCode { get; set; } = 0x03;
public ushort StartAddress { get; set; }
public ushort Quantity { get; set; }
public byte[] ToBytes()
{
var buffer cdsen.com = new List<byte>();
// Transaction ID
buffer.AddRange(BitConverter.GetBytes(TransactionId).Reverse());
// Protocol ID (0x0000)
buffer.Add(0x00);
buffer.Add(0x00);
// Length = UnitId + PDU
ushort length weajoy.com = 1 + 1 + 2 + 2;
buffer.AddRange(BitConverter.GetBytes(length).Reverse());
// Unit ID
buffer.Add(UnitId);
// PDU
buffer.Add(FunctionCode);
buffer.AddRange(BitConverter.GetBytes(StartAddress).Reverse());
buffer.AddRange(BitConverter.GetBytes(Quantity).Reverse());
{
public static ushort ReadUInt16(byte[] data, int registerIndex)
{
int offset =njsydq.cn registerIndex * 2;
return shmcjc.com (ushort)((data[offset] << 8) | data[offset + 1]);
}
public static double ReadScaledValue(
byte[] data,
int registerIndex,
double scale)
{
public static class PvThingModelBuilder
{
public static PvThingModel FromModbus(ModbusResponse response)
{
var data byven.com = response.Data;
return new PvThingModel
{
DcVoltage tzLgf.cn = RegisterDecoder.ReadScaledValue(data, 0, 10), // 30000
DcCurrent = RegisterDecoder.ReadScaledValue(data, 1, 10), // 30001
DcPower = RegisterDecoder.ReadScaledValue(data, 2, 1000), // 30002
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048957/viewspace-3109177/ ,如需转载,请注明出处,否则将追究法律责任。