|
| 1 | +import { Body, Controller, Post, Route, Security, Tags } from "tsoa"; |
| 2 | + |
| 3 | +export interface SendTestRequestRequest { |
| 4 | + apiKey: string; |
| 5 | +} |
| 6 | + |
| 7 | +export interface SendTestRequestResponse { |
| 8 | + success: boolean; |
| 9 | + response?: string; |
| 10 | + requestId?: string; |
| 11 | + error?: string; |
| 12 | +} |
| 13 | + |
| 14 | +@Security("api_key") |
| 15 | +@Tags("Test") |
| 16 | +@Route("v1/test") |
| 17 | +export class TestController extends Controller { |
| 18 | + @Post("/gateway-request") |
| 19 | + public async sendTestRequest( |
| 20 | + @Body() body: SendTestRequestRequest |
| 21 | + ): Promise<SendTestRequestResponse> { |
| 22 | + try { |
| 23 | + // Determine gateway URL based on environment |
| 24 | + const gatewayUrl = |
| 25 | + process.env.NODE_ENV === "development" |
| 26 | + ? "http://localhost:8793" |
| 27 | + : "https://ai-gateway.helicone.ai"; |
| 28 | + |
| 29 | + // Make test request to AI Gateway |
| 30 | + const response = await fetch(`${gatewayUrl}/chat/completions`, { |
| 31 | + method: "POST", |
| 32 | + headers: { |
| 33 | + Authorization: `Bearer ${body.apiKey}`, |
| 34 | + "Content-Type": "application/json", |
| 35 | + }, |
| 36 | + body: JSON.stringify({ |
| 37 | + model: "gpt-4o-mini", |
| 38 | + messages: [{ role: "user", content: "Say hello!" }], |
| 39 | + }), |
| 40 | + }); |
| 41 | + |
| 42 | + // Extract request ID from headers |
| 43 | + const requestId = response.headers.get("helicone-id") || undefined; |
| 44 | + |
| 45 | + if (!response.ok) { |
| 46 | + const errorText = await response.text(); |
| 47 | + let errorMessage = "Request failed"; |
| 48 | + try { |
| 49 | + const errorJson = JSON.parse(errorText); |
| 50 | + errorMessage = errorJson.error?.message || errorText; |
| 51 | + } catch { |
| 52 | + errorMessage = errorText; |
| 53 | + } |
| 54 | + |
| 55 | + return { |
| 56 | + success: false, |
| 57 | + error: errorMessage, |
| 58 | + requestId, |
| 59 | + }; |
| 60 | + } |
| 61 | + |
| 62 | + // Parse response |
| 63 | + const data = await response.json(); |
| 64 | + const messageContent = |
| 65 | + data.choices?.[0]?.message?.content || "No response content"; |
| 66 | + |
| 67 | + return { |
| 68 | + success: true, |
| 69 | + response: messageContent, |
| 70 | + requestId, |
| 71 | + }; |
| 72 | + } catch (error) { |
| 73 | + console.error("Test request error:", error); |
| 74 | + return { |
| 75 | + success: false, |
| 76 | + error: |
| 77 | + error instanceof Error ? error.message : "Unknown error occurred", |
| 78 | + }; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments