Fix mcp token billing bug
This commit is contained in:
1 parent
11264d302d
commit
be7033e9a2
7 files changed
+46
-14
No files matched your search
@@ -8,7 +8,7 @@ import threading
|
||||
import time
|
||||
import logging
|
||||
from typing import Callable
|
||||
|
||||
import os
|
||||
from services.common.config import Config
|
||||
from services.common.database import get_db
|
||||
from services.admin_service.services.billing_message_handler import BillingMessageHandler
|
||||
@@ -20,7 +20,7 @@ class BillingMessageConsumer:
|
||||
"""Billing message consumer"""
|
||||
|
||||
def __init__(self):
|
||||
self.queue_name = "billing.api.calls"
|
||||
self.queue_name = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls"
|
||||
self.connection = None
|
||||
self.channel = None
|
||||
self.consuming = False
|
||||
|
||||
@@ -66,7 +66,7 @@ def stop_billing_consumer():
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifecycle management"""
|
||||
global consumer_thread
|
||||
start_alipay_order_monitor()
|
||||
# start_alipay_order_monitor()
|
||||
|
||||
# Startup: Start consumer in separate thread
|
||||
logger.info("Admin Service starting...")
|
||||
@@ -82,7 +82,7 @@ async def lifespan(app: FastAPI):
|
||||
# Shutdown: Stop consumer
|
||||
logger.info("Admin Service shutting down...")
|
||||
stop_billing_consumer()
|
||||
start_alipay_order_monitor()
|
||||
# start_alipay_order_monitor()
|
||||
|
||||
|
||||
app = FastAPI(title="Admin Service", openapi_url="/openapi.json", lifespan=lifespan)
|
||||
|
||||
@@ -90,11 +90,12 @@ class BillingMessageHandler:
|
||||
service_id=message_data["service_id"],
|
||||
api_id=message_data["api_id"],
|
||||
tool_name=message_data["tool_name"],
|
||||
input_params=message_data["input_params"],
|
||||
input_params=message_data["input_params"],
|
||||
call_success=message_data["call_success"],
|
||||
unit_price=Decimal(message_data["unit_price"]),
|
||||
input_token=Decimal(message_data["input_token"]),
|
||||
output_token=Decimal(message_data["output_token"]),
|
||||
charge_type=message_data["charge_type"],
|
||||
call_start_time=call_start_time,
|
||||
call_end_time=call_end_time,
|
||||
apikey_id=message_data.get("apikey_id"), # Support older version messages that don't have this field
|
||||
@@ -186,7 +187,7 @@ class BillingMessageHandler:
|
||||
status=1, # Completed
|
||||
transaction_id=call_log_id,
|
||||
channel_user_id=None,
|
||||
callback_data=json.dumps(billing_message),
|
||||
callback_data=json.dumps(self._billing_message_to_dict(billing_message)),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
@@ -229,3 +230,30 @@ class BillingMessageHandler:
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to update wallet cache - User ID: {user_id}: {str(e)}")
|
||||
# Cache update failure doesn't affect main flow
|
||||
|
||||
def _billing_message_to_dict(self, billing_message: BillingMessage) -> dict:
|
||||
"""
|
||||
Convert BillingMessage to JSON serializable dictionary
|
||||
|
||||
Args:
|
||||
billing_message: BillingMessage object
|
||||
|
||||
Returns:
|
||||
dict: JSON serializable dictionary
|
||||
"""
|
||||
return {
|
||||
"user_id": billing_message.user_id,
|
||||
"service_id": billing_message.service_id,
|
||||
"api_id": billing_message.api_id,
|
||||
"tool_name": billing_message.tool_name,
|
||||
"input_params": billing_message.input_params,
|
||||
"call_success": billing_message.call_success,
|
||||
"unit_price": str(billing_message.unit_price),
|
||||
"input_token": str(billing_message.input_token),
|
||||
"output_token": str(billing_message.output_token),
|
||||
"charge_type": billing_message.charge_type,
|
||||
"call_start_time": billing_message.call_start_time.isoformat(),
|
||||
"call_end_time": billing_message.call_end_time.isoformat() if billing_message.call_end_time else None,
|
||||
"call_log_id": billing_message.call_log_id,
|
||||
"apikey_id": billing_message.apikey_id,
|
||||
}
|
||||
@@ -3,6 +3,7 @@ Billing service - Handle user API call billing logic
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
@@ -30,7 +31,7 @@ class BillingService:
|
||||
BILLING_LOCK_TIMEOUT = 5 # Distributed lock timeout (seconds)
|
||||
WALLET_CACHE_EXPIRE = 300 # Wallet cache expiration time (seconds)
|
||||
SERVICE_CACHE_EXPIRE = 3600 # Service price cache expiration time (seconds)
|
||||
BILLING_QUEUE_NAME = "billing.api.calls"
|
||||
BILLING_QUEUE_NAME = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls"
|
||||
|
||||
def __init__(self):
|
||||
self.redis = redis_client
|
||||
@@ -150,6 +151,9 @@ class BillingService:
|
||||
"input_params": message.input_params,
|
||||
"call_success": message.call_success,
|
||||
"unit_price": str(message.unit_price),
|
||||
"input_token": str(message.input_token),
|
||||
"output_token": str(message.output_token),
|
||||
"charge_type": message.charge_type,
|
||||
"call_start_time": message.call_start_time.isoformat(),
|
||||
"call_end_time": message.call_end_time.isoformat() if message.call_end_time else None,
|
||||
"apikey_id": message.apikey_id,
|
||||
|
||||
@@ -214,9 +214,9 @@ class McpServerFactory:
|
||||
api_id=call_log_id,
|
||||
tool_name=name,
|
||||
input_params=json.dumps(arguments),
|
||||
unit_price=input_token_amount + output_token_amount,
|
||||
input_token=Decimal(str(input_token)),
|
||||
output_token=Decimal(str(output_token)),
|
||||
unit_price=(input_token_amount + output_token_amount).quantize(Decimal('0.000001')),
|
||||
input_token=Decimal(str(input_token)).quantize(Decimal('0')),
|
||||
output_token=Decimal(str(output_token)).quantize(Decimal('0')),
|
||||
charge_type=pre_deduct_result.charge_type,
|
||||
call_start_time=call_start_time,
|
||||
call_end_time=call_end_time,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""
|
||||
"""
|
||||
|
||||
import os
|
||||
BILLING_LOCK_TIMEOUT = 5
|
||||
WALLET_CACHE_EXPIRE = 300
|
||||
SERVICE_CACHE_EXPIRE = 3600
|
||||
|
||||
BILLING_QUEUE_NAME = "billing.api.calls"
|
||||
BILLING_QUEUE_NAME = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls"
|
||||
BILLING_EXCHANGE_NAME = "billing.exchange"
|
||||
BILLING_ROUTING_KEY = "api.call.billing"
|
||||
|
||||
|
||||
@@ -38,10 +38,10 @@ class UserWalletHistory(Base):
|
||||
comment="Payment method: platform, stripe, alipay, wechat",
|
||||
)
|
||||
amount: Mapped[float] = mapped_column(
|
||||
Numeric(10, 2), nullable=False, comment="Transaction amount (positive for deposit, negative for consumption, 2 decimal places)"
|
||||
Numeric(16, 6), nullable=False, comment="Transaction amount (positive for deposit, negative for consumption, 6 decimal places)"
|
||||
)
|
||||
balance_after: Mapped[float] = mapped_column(
|
||||
Numeric(10, 2), nullable=False, comment="Balance after transaction (2 decimal places)"
|
||||
Numeric(16, 6), nullable=False, comment="Balance after transaction (6 decimal places)"
|
||||
)
|
||||
type: Mapped[TransactionType] = mapped_column(
|
||||
Enum(TransactionType, values_callable=lambda obj: [e.value for e in obj]),
|
||||
|
||||
Reference in new issue
Block a user