lint + formating with black (#158)

* lint + formating with black

* add black as pre commit
This commit is contained in:
Co Tran 2024-10-09 11:25:07 -07:00 committed by GitHub
parent 498e7f9724
commit 5c4a6bc8ff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 581 additions and 295 deletions

View file

@ -6,56 +6,54 @@ import logging
from pydantic import BaseModel
logger = logging.getLogger('uvicorn.error')
logger = logging.getLogger("uvicorn.error")
logger.setLevel(logging.INFO)
app = FastAPI()
@app.get("/healthz")
async def healthz():
return {
"status": "ok"
}
return {"status": "ok"}
class WeatherRequest(BaseModel):
city: str
days: int = 7
units: str = "Farenheit"
city: str
days: int = 7
units: str = "Farenheit"
@app.post("/weather")
async def weather(req: WeatherRequest, res: Response):
weather_forecast = {
"city": req.city,
"temperature": [],
"units": req.units,
}
for i in range(7):
min_temp = random.randrange(50,90)
max_temp = random.randrange(min_temp+5, min_temp+20)
if req.units.lower() == "celsius" or req.units.lower() == "c":
min_temp = (min_temp - 32) * 5.0/9.0
max_temp = (max_temp - 32) * 5.0/9.0
weather_forecast["temperature"].append({
"date": str(date.today() + timedelta(days=i)),
"temperature": {
"min": min_temp,
"max": max_temp
},
"units": req.units,
"query_time": str(datetime.now(timezone.utc))
})
min_temp = random.randrange(50, 90)
max_temp = random.randrange(min_temp + 5, min_temp + 20)
if req.units.lower() == "celsius" or req.units.lower() == "c":
min_temp = (min_temp - 32) * 5.0 / 9.0
max_temp = (max_temp - 32) * 5.0 / 9.0
weather_forecast["temperature"].append(
{
"date": str(date.today() + timedelta(days=i)),
"temperature": {"min": min_temp, "max": max_temp},
"units": req.units,
"query_time": str(datetime.now(timezone.utc)),
}
)
return weather_forecast
class InsuranceClaimDetailsRequest(BaseModel):
policy_number: str
policy_number: str
@app.post("/insurance_claim_details")
async def insurance_claim_details(req: InsuranceClaimDetailsRequest, res: Response):
claim_details = {
"policy_number": req.policy_number,
"claim_status": "Approved",
@ -68,26 +66,25 @@ async def insurance_claim_details(req: InsuranceClaimDetailsRequest, res: Respon
class DefaultTargetRequest(BaseModel):
arch_messages: list
arch_messages: list
@app.post("/default_target")
async def default_target(req: DefaultTargetRequest, res: Response):
logger.info(f"Received arch_messages: {req.arch_messages}")
resp = {
"choices": [
{
"choices": [
{
"message": {
"role": "assistant",
"content": "hello world from api server"
"role": "assistant",
"content": "hello world from api server",
},
"finish_reason": "completed",
"index": 0
}
],
"model": "api_server",
"usage": {
"completion_tokens": 0
"index": 0,
}
}
],
"model": "api_server",
"usage": {"completion_tokens": 0},
}
logger.info(f"sending response: {json.dumps(resp)}")
return resp

View file

@ -3,28 +3,40 @@ from pydantic import BaseModel, Field
app = FastAPI()
class Conversation(BaseModel):
arch_messages: list
class PolicyCoverageRequest(BaseModel):
policy_type: str = Field(..., description="The type of a policy held by the customer For, e.g. car, boat, house, motorcycle)")
policy_type: str = Field(
...,
description="The type of a policy held by the customer For, e.g. car, boat, house, motorcycle)",
)
class PolicyInitiateRequest(PolicyCoverageRequest):
deductible: float = Field(..., description="The deductible amount set of the policy")
deductible: float = Field(
..., description="The deductible amount set of the policy"
)
class ClaimUpdate(BaseModel):
claim_id: str
notes: str # Status or details of the claim
class DeductibleUpdate(BaseModel):
policy_id: str
deductible: float
class CoverageResponse(BaseModel):
policy_type: str
coverage: str # Description of coverage
premium: float # The premium cost
# Get information about policy coverage
@app.post("/policy/coverage", response_model=CoverageResponse)
async def get_policy_coverage(req: PolicyCoverageRequest):
@ -32,10 +44,22 @@ async def get_policy_coverage(req: PolicyCoverageRequest):
Retrieve the coverage details for a given policy type (car, boat, house, motorcycle).
"""
policy_coverage = {
"car": {"coverage": "Full car coverage with collision, liability", "premium": 500.0},
"boat": {"coverage": "Full boat coverage including theft and storm damage", "premium": 700.0},
"house": {"coverage": "Full house coverage including fire, theft, flood", "premium": 1000.0},
"motorcycle": {"coverage": "Full motorcycle coverage with liability", "premium": 400.0},
"car": {
"coverage": "Full car coverage with collision, liability",
"premium": 500.0,
},
"boat": {
"coverage": "Full boat coverage including theft and storm damage",
"premium": 700.0,
},
"house": {
"coverage": "Full house coverage including fire, theft, flood",
"premium": 1000.0,
},
"motorcycle": {
"coverage": "Full motorcycle coverage with liability",
"premium": 400.0,
},
}
if req.policy_type not in policy_coverage:
@ -44,9 +68,10 @@ async def get_policy_coverage(req: PolicyCoverageRequest):
return CoverageResponse(
policy_type=req.policy_type,
coverage=policy_coverage[req.policy_type]["coverage"],
premium=policy_coverage[req.policy_type]["premium"]
premium=policy_coverage[req.policy_type]["premium"],
)
# Initiate policy coverage
@app.post("/policy/initiate")
async def initiate_policy(policy_request: PolicyInitiateRequest):
@ -56,7 +81,11 @@ async def initiate_policy(policy_request: PolicyInitiateRequest):
if policy_request.policy_type not in ["car", "boat", "house", "motorcycle"]:
raise HTTPException(status_code=400, detail="Invalid policy type")
return {"message": f"Policy initiated for {policy_request.policy_type}", "deductible": policy_request.deductible}
return {
"message": f"Policy initiated for {policy_request.policy_type}",
"deductible": policy_request.deductible,
}
# Update claim details
@app.post("/policy/claim")
@ -65,8 +94,11 @@ async def update_claim(req: ClaimUpdate):
Update the status or details of a claim.
"""
# For simplicity, this is a mock update response
return {"message": f"Claim {claim_update.claim_id} for policy {claim_update.claim_id} has been updated",
"update": claim_update.notes}
return {
"message": f"Claim {claim_update.claim_id} for policy {claim_update.claim_id} has been updated",
"update": claim_update.notes,
}
# Update deductible amount
@app.post("/policy/deductible")
@ -75,8 +107,11 @@ async def update_deductible(deductible_update: DeductibleUpdate):
Update the deductible amount for a specific policy.
"""
# For simplicity, this is a mock update response
return {"message": f"Deductible for policy {deductible_update.policy_id} has been updated",
"new_deductible": deductible_update.deductible}
return {
"message": f"Deductible for policy {deductible_update.policy_id} has been updated",
"new_deductible": deductible_update.deductible,
}
# Post method for policy Q/A
@app.post("/policy/qa")
@ -86,21 +121,20 @@ async def policy_qa(conversation: Conversation):
It forwards the conversation to the OpenAI client via a local proxy and returns the response.
"""
return {
"choices": [
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am a helpful insurance agent, and can only help with insurance things"
"role": "assistant",
"content": "I am a helpful insurance agent, and can only help with insurance things",
},
"finish_reason": "completed",
"index": 0
}
],
"model": "insurance_agent",
"usage": {
"completion_tokens": 0
"index": 0,
}
}
],
"model": "insurance_agent",
"usage": {"completion_tokens": 0},
}
# Run the app using:
# uvicorn main:app --reload

View file

@ -4,10 +4,14 @@ from typing import List, Optional
app = FastAPI()
# Define the request model
class DeviceSummaryRequest(BaseModel):
device_ids: List[int]
time_range: Optional[int] = Field(default=7, description="Time range in days, defaults to 7")
time_range: Optional[int] = Field(
default=7, description="Time range in days, defaults to 7"
)
# Define the response model
class DeviceStatistics(BaseModel):
@ -15,18 +19,23 @@ class DeviceStatistics(BaseModel):
time_range: str
data: str
class DeviceSummaryResponse(BaseModel):
statistics: List[DeviceStatistics]
# Request model for device reboot
class DeviceRebootRequest(BaseModel):
device_ids: List[int]
# Response model for the device reboot
class CoverageResponse(BaseModel):
status: str
summary: dict
@app.post("/agent/device_reboot", response_model=CoverageResponse)
def reboot_network_device(request_data: DeviceRebootRequest):
"""
@ -38,20 +47,21 @@ def reboot_network_device(request_data: DeviceRebootRequest):
# Validate 'device_ids' (This is already validated by Pydantic, but additional logic can be added if needed)
if not device_ids:
raise HTTPException(status_code=400, detail="'device_ids' parameter is required")
raise HTTPException(
status_code=400, detail="'device_ids' parameter is required"
)
# Simulate reboot operation and return the response
statistics = []
for device_id in device_ids:
# Placeholder for actual data retrieval or device reboot logic
stats = {
"data": f"Device {device_id} has been successfully rebooted."
}
stats = {"data": f"Device {device_id} has been successfully rebooted."}
statistics.append(stats)
# Return the response with a summary
return CoverageResponse(status="success", summary={"device_ids": device_ids})
# Post method for device summary
@app.post("/agent/device_summary", response_model=DeviceSummaryResponse)
def get_device_summary(request: DeviceSummaryRequest):
@ -77,6 +87,7 @@ def get_device_summary(request: DeviceSummaryRequest):
return DeviceSummaryResponse(statistics=statistics)
@app.post("/agent/network_summary")
async def policy_qa():
"""
@ -84,21 +95,20 @@ async def policy_qa():
It forwards the conversation to the OpenAI client via a local proxy and returns the response.
"""
return {
"choices": [
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am a helpful networking agent, and I can help you get status for network devices or reboot them"
"role": "assistant",
"content": "I am a helpful networking agent, and I can help you get status for network devices or reboot them",
},
"finish_reason": "completed",
"index": 0
}
],
"model": "network_agent",
"usage": {
"completion_tokens": 0
"index": 0,
}
}
],
"model": "network_agent",
"usage": {"completion_tokens": 0},
}
if __name__ == "__main__":
app.run(debug=True)

View file

@ -11,6 +11,7 @@ logging.basicConfig(
)
logger = logging.getLogger(__name__)
def load_sql():
# Example Usage
conn = sqlite3.connect(":memory:")
@ -26,6 +27,7 @@ def load_sql():
return conn
# Function to convert natural language time expressions to "X {time} ago" format
def convert_to_ago_format(expression):
# Define patterns for different time units