|
| 1 | +using Chats.BE.Controllers.Api.AnthropicCompatible.Dtos; |
| 2 | +using Chats.BE.DB; |
| 3 | +using Chats.BE.DB.Enums; |
| 4 | +using Chats.BE.Services; |
| 5 | +using Chats.BE.Services.Models; |
| 6 | +using Chats.BE.Services.Models.ChatServices; |
| 7 | +using Chats.BE.Services.OpenAIApiKeySession; |
| 8 | +using Microsoft.AspNetCore.Authorization; |
| 9 | +using Microsoft.AspNetCore.Mvc; |
| 10 | +using System.Text.Json.Nodes; |
| 11 | + |
| 12 | +namespace Chats.BE.Controllers.Api.AnthropicCompatible; |
| 13 | + |
| 14 | +[Authorize(AuthenticationSchemes = "OpenAIApiKey")] |
| 15 | +public class AnthropicCountTokenController( |
| 16 | + CurrentApiKey currentApiKey, |
| 17 | + ChatFactory cf, |
| 18 | + UserModelManager userModelManager, |
| 19 | + ILogger<AnthropicCountTokenController> logger) : ControllerBase |
| 20 | +{ |
| 21 | + private static readonly DBApiType[] AllowedApiTypes = [DBApiType.OpenAIChatCompletion, DBApiType.OpenAIResponse, DBApiType.AnthropicMessages]; |
| 22 | + |
| 23 | + [HttpPost("v1/messages/count_tokens")] |
| 24 | + public async Task<ActionResult> CountTokens([FromBody] JsonObject json, CancellationToken cancellationToken) |
| 25 | + { |
| 26 | + AnthropicCountTokenRequestWrapper request = new(json); |
| 27 | + |
| 28 | + if (!request.SeemsValid()) |
| 29 | + { |
| 30 | + return ErrorMessage(AnthropicErrorTypes.InvalidRequestError, "Invalid request: model and messages are required."); |
| 31 | + } |
| 32 | + |
| 33 | + if (string.IsNullOrWhiteSpace(request.Model)) |
| 34 | + { |
| 35 | + return ErrorMessage(AnthropicErrorTypes.InvalidRequestError, "model is required."); |
| 36 | + } |
| 37 | + |
| 38 | + UserModel? userModel = await userModelManager.GetUserModel(currentApiKey.ApiKey, request.Model, cancellationToken); |
| 39 | + if (userModel == null) |
| 40 | + { |
| 41 | + return ErrorMessage(AnthropicErrorTypes.NotFoundError, $"The model `{request.Model}` does not exist or you do not have access to it."); |
| 42 | + } |
| 43 | + |
| 44 | + if (!AllowedApiTypes.Contains(userModel.Model.ApiType)) |
| 45 | + { |
| 46 | + return ErrorMessage(AnthropicErrorTypes.InvalidRequestError, $"The model `{request.Model}` does not support messages API."); |
| 47 | + } |
| 48 | + |
| 49 | + try |
| 50 | + { |
| 51 | + Model cm = userModel.Model; |
| 52 | + using ChatService s = cf.CreateChatService(cm); |
| 53 | + ChatRequest chatRequest = request.ToChatRequest(currentApiKey.User.Id.ToString(), cm); |
| 54 | + int inputTokens = await s.CountTokenAsync(chatRequest, cancellationToken); |
| 55 | + |
| 56 | + return Ok(new AnthropicCountTokenResponse { InputTokens = inputTokens }); |
| 57 | + } |
| 58 | + catch (Exception e) |
| 59 | + { |
| 60 | + logger.LogError(e, "Error counting tokens"); |
| 61 | + return ErrorMessage(AnthropicErrorTypes.ApiError, "Internal server error"); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + private BadRequestObjectResult ErrorMessage(string errorType, string message) |
| 66 | + { |
| 67 | + return BadRequest(new AnthropicErrorResponse |
| 68 | + { |
| 69 | + Error = new AnthropicErrorDetail |
| 70 | + { |
| 71 | + Type = errorType, |
| 72 | + Message = message |
| 73 | + } |
| 74 | + }); |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +public class AnthropicCountTokenRequestWrapper(JsonObject json) |
| 79 | +{ |
| 80 | + public string? Model => (string?)json["model"]; |
| 81 | + |
| 82 | + public bool SeemsValid() |
| 83 | + { |
| 84 | + return Model != null && json["messages"] != null; |
| 85 | + } |
| 86 | + |
| 87 | + public ChatRequest ToChatRequest(string userId, Model model) |
| 88 | + { |
| 89 | + // For count tokens, we reuse the AnthropicRequestWrapper logic |
| 90 | + // but we need to ensure max_tokens has a default value |
| 91 | + json["max_tokens"] ??= model.MaxResponseTokens; |
| 92 | + json["stream"] ??= false; |
| 93 | + |
| 94 | + AnthropicRequestWrapper wrapper = new(json); |
| 95 | + return wrapper.ToChatRequest(userId, model); |
| 96 | + } |
| 97 | +} |
0 commit comments