|
| 1 | +import "dotenv/config"; |
| 2 | +import { |
| 3 | + NilaiOpenAIClient, |
| 4 | + DelegationTokenServer, |
| 5 | + AuthType, |
| 6 | + type DelegationTokenRequest, |
| 7 | + type DelegationTokenResponse, |
| 8 | + NilAuthInstance, |
| 9 | +} from "@nillion/nilai-ts"; |
| 10 | + |
| 11 | +// To obtain an API key, navigate to https://nilpay.vercel.app/ |
| 12 | +// and create a new subscription. |
| 13 | +// The API key will be displayed in the subscription details. |
| 14 | + |
| 15 | +const API_KEY = process.env.NILLION_API_KEY; |
| 16 | + |
| 17 | +async function main() { |
| 18 | + if (!API_KEY) { |
| 19 | + throw new Error("NILLION_API_KEY environment variable is required"); |
| 20 | + } |
| 21 | + |
| 22 | + // >>> Server initializes a delegation token server |
| 23 | + // The server is responsible for creating delegation tokens |
| 24 | + // and managing their expiration and usage. |
| 25 | + const server = new DelegationTokenServer( |
| 26 | + API_KEY, |
| 27 | + { |
| 28 | + nilauthInstance: NilAuthInstance.SANDBOX, |
| 29 | + expirationTime: 10, // 10 seconds validity of delegation tokens |
| 30 | + tokenMaxUses: 1, // 1 use of a delegation token |
| 31 | + }, |
| 32 | + // For production instances, use the following: |
| 33 | + // NilAuthInstance.PRODUCTION, |
| 34 | + ); |
| 35 | + |
| 36 | + // >>> Client initializes a client |
| 37 | + // The client is responsible for making requests to the Nilai API. |
| 38 | + // We do not provide an API key but we set the auth type to DELEGATION_TOKEN |
| 39 | + const client = new NilaiOpenAIClient({ |
| 40 | + baseURL: "https://nilai-a779.nillion.network/nuc/v1/", |
| 41 | + authType: AuthType.DELEGATION_TOKEN, |
| 42 | + // For production instances, use the following: |
| 43 | + // nilauthInstance: NilAuthInstance.PRODUCTION, |
| 44 | + }); |
| 45 | + |
| 46 | + // >>> Client produces a delegation request |
| 47 | + const delegationRequest: DelegationTokenRequest = client.getDelegationRequest(); |
| 48 | + |
| 49 | + // <<< Server creates a delegation token |
| 50 | + const delegationToken: DelegationTokenResponse = await server.createDelegationToken( |
| 51 | + delegationRequest |
| 52 | + ); |
| 53 | + |
| 54 | + // >>> Client sets internally the delegation token |
| 55 | + client.updateDelegation(delegationToken); |
| 56 | + |
| 57 | + // >>> Client uses the delegation token to make a request |
| 58 | + const response = await client.chat.completions.create({ |
| 59 | + model: "meta-llama/Llama-3.2-3B-Instruct", |
| 60 | + messages: [ |
| 61 | + { role: "user", content: "Hello! Can you help me with something?" } |
| 62 | + ], |
| 63 | + }); |
| 64 | + |
| 65 | + console.log(`Response: ${response.choices[0].message.content}`); |
| 66 | +} |
| 67 | + |
| 68 | +// Run the example |
| 69 | +main().catch(console.error); |
0 commit comments