Skip to content

Commit f096716

Browse files
authored
Merge pull request #5 from NillionNetwork/feat/credit_system_integration
feat: added credit system integration
2 parents baf42cc + 7b1205e commit f096716

File tree

12 files changed

+47
-151
lines changed

12 files changed

+47
-151
lines changed

README.md

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import "dotenv/config";
2121

2222
// Initialize client with API key from environment variables
2323
const client = new NilaiOpenAIClient({
24-
baseURL: "https://nilai-a779.nillion.network/v1/",
24+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
2525
apiKey: process.env.NILLION_API_KEY,
2626
});
2727

@@ -46,7 +46,7 @@ import "dotenv/config";
4646

4747
// Set up your API key in a .env file or environment variable
4848
const client = new NilaiOpenAIClient({
49-
baseURL: "https://nilai-a779.nillion.network/v1/",
49+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
5050
apiKey: process.env.NILLION_API_KEY, // Your private key
5151
});
5252

@@ -77,20 +77,18 @@ import {
7777
NilaiOpenAIClient,
7878
DelegationTokenServer,
7979
AuthType,
80-
NilAuthInstance,
8180
} from "@nillion/nilai-ts";
8281
import "dotenv/config";
8382

8483
// Server-side: Create a delegation token server
8584
const server = new DelegationTokenServer(process.env.NILLION_API_KEY, {
86-
nilauthInstance: NilAuthInstance.SANDBOX,
8785
expirationTime: 3600, // 1 hour validity
8886
tokenMaxUses: 10, // Allow 10 uses
8987
});
9088

9189
// Client-side: Initialize client for delegation token mode
9290
const client = new NilaiOpenAIClient({
93-
baseURL: "https://nilai-a779.nillion.network/v1/",
91+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
9492
authType: AuthType.DELEGATION_TOKEN,
9593
});
9694

@@ -137,7 +135,7 @@ import "dotenv/config";
137135
import { NilaiOpenAIClient } from "@nillion/nilai-ts";
138136

139137
const client = new NilaiOpenAIClient({
140-
baseURL: "https://nilai-a779.nillion.network/v1/",
138+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
141139
apiKey: process.env.NILLION_API_KEY,
142140
});
143141
```
@@ -148,7 +146,7 @@ const client = new NilaiOpenAIClient({
148146
- **🤖 OpenAI Compatibility**: Drop-in replacement for the OpenAI client.
149147
- **⚡ Automatic Token Management**: Handles root token caching and expiration automatically.
150148
- **🛡️ Secure Delegation**: Server-side token management with configurable expiration and usage limits.
151-
- **🌐 Network Flexibility**: Support for sandbox and production `nilauth` environments.
149+
- **🌐 Self-Signed NUCs**: Uses self-signed NUC tokens without requiring a remote nilauth service.
152150
- **🔒 Type Safety**: Strongly typed with Zod schema validation for robust development.
153151
- **🔧 Universal Compatibility**: Built-in polyfills for Node.js environments ensure seamless operation across different platforms without manual configuration.
154152

examples/0-api-key.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import "dotenv/config";
2-
import { NilAuthInstance, NilaiOpenAIClient } from "@nillion/nilai-ts";
2+
import { NilaiOpenAIClient } from "@nillion/nilai-ts";
33

44
// To obtain an API key, navigate to https://nilpay.vercel.app/
55
// and create a new subscription.
@@ -10,18 +10,14 @@ const API_KEY = process.env.NILLION_API_KEY;
1010

1111
async function main() {
1212
// Initialize the client in API key mode
13-
// For sandbox, use the following:
1413
const client = new NilaiOpenAIClient({
15-
baseURL: "https://nilai-a779.nillion.network/v1/",
14+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
1615
apiKey: API_KEY,
17-
nilauthInstance: NilAuthInstance.SANDBOX,
18-
// For production, use the following:
19-
// nilauthInstance: NilAuthInstance.PRODUCTION,
2016
});
2117

2218
// Make a request to the Nilai API
2319
const response = await client.chat.completions.create({
24-
model: "google/gemma-3-27b-it",
20+
model: "openai/gpt-oss-20b",
2521
messages: [
2622
{ role: "user", content: "Hello! Can you help me with something?" },
2723
],

examples/1-delegation-token.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import {
44
type DelegationTokenRequest,
55
type DelegationTokenResponse,
66
DelegationTokenServer,
7-
NilAuthInstance,
87
NilaiOpenAIClient,
98
} from "@nillion/nilai-ts";
109

@@ -23,7 +22,6 @@ async function main() {
2322
// The server is responsible for creating delegation tokens
2423
// and managing their expiration and usage.
2524
const server = new DelegationTokenServer(API_KEY, {
26-
nilauthInstance: NilAuthInstance.SANDBOX,
2725
expirationTime: 10, // 10 seconds validity of delegation tokens
2826
tokenMaxUses: 1, // 1 use of a delegation token
2927
});
@@ -32,10 +30,8 @@ async function main() {
3230
// The client is responsible for making requests to the Nilai API.
3331
// We do not provide an API key but we set the auth type to DELEGATION_TOKEN
3432
const client = new NilaiOpenAIClient({
35-
baseURL: "https://nilai-a779.nillion.network/v1/",
33+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
3634
authType: AuthType.DELEGATION_TOKEN,
37-
// For production instances, use the following:
38-
//nilauthInstance: NilAuthInstance.PRODUCTION,
3935
});
4036

4137
// >>> Client produces a delegation request
@@ -51,7 +47,7 @@ async function main() {
5147

5248
// >>> Client uses the delegation token to make a request
5349
const response = await client.chat.completions.create({
54-
model: "google/gemma-3-27b-it",
50+
model: "openai/gpt-oss-20b",
5551
messages: [
5652
{ role: "user", content: "Hello! Can you help me with something?" },
5753
],

examples/2-nildb-prompt-store-retrieve.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import {
44
type DelegationTokenRequest,
55
type DelegationTokenResponse,
66
DelegationTokenServer,
7-
NilAuthInstance,
87
NilaiOpenAIClient,
98
} from "@nillion/nilai-ts";
109
import { Did as DidClass } from "@nillion/nuc";
@@ -17,11 +16,9 @@ const API_KEY = process.env.NILLION_API_KEY;
1716

1817
async function store_to_nildb(prompt: string): Promise<[string, string]> {
1918
// Initialize the client in API key mode
20-
// For sandbox, use the following:
2119
const client = new NilaiOpenAIClient({
22-
baseURL: "https://nilai-f910.nillion.network/nuc/v1/",
20+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
2321
apiKey: API_KEY,
24-
nilauthInstance: NilAuthInstance.PRODUCTION,
2522
});
2623

2724
const createdIds: string[] = await client.createPrompt(prompt);
@@ -46,7 +43,6 @@ async function main() {
4643
// The server is responsible for creating delegation tokens
4744
// and managing their expiration and usage.
4845
const server = new DelegationTokenServer(API_KEY, {
49-
nilauthInstance: NilAuthInstance.PRODUCTION,
5046
expirationTime: 60 * 60, // 3600 seconds = 1 hour validity of delegation tokens
5147
tokenMaxUses: 10, // 10 uses of a delegation token
5248
prompt_document: {
@@ -59,10 +55,8 @@ async function main() {
5955
// The client is responsible for making requests to the Nilai API.
6056
// We do not provide an API key but we set the auth type to DELEGATION_TOKEN
6157
const client = new NilaiOpenAIClient({
62-
baseURL: "https://nilai-f910.nillion.network/nuc/v1/",
58+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
6359
authType: AuthType.DELEGATION_TOKEN,
64-
// For production instances, use the following:
65-
nilauthInstance: NilAuthInstance.PRODUCTION,
6660
});
6761
console.log("Requesting delegation token from NilAI Server");
6862

examples/3-web-search.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import "dotenv/config";
2-
import { NilAuthInstance, NilaiOpenAIClient } from "@nillion/nilai-ts";
2+
import { NilaiOpenAIClient } from "@nillion/nilai-ts";
33

44
// To obtain an API key, navigate to https://nilpay.vercel.app/
55
// and create a new subscription.
@@ -10,19 +10,15 @@ const API_KEY = process.env.NILLION_API_KEY;
1010

1111
async function main() {
1212
// Initialize the client in API key mode
13-
// For sandbox, use the following:
1413
const client = new NilaiOpenAIClient({
15-
baseURL: "https://nilai-a779.nillion.network/v1/",
14+
baseURL: "https://api.nilai.nillion.network/nuc/v1/",
1615
apiKey: API_KEY,
17-
nilauthInstance: NilAuthInstance.SANDBOX,
18-
// For production, use the following:
19-
// nilauthInstance: NilAuthInstance.PRODUCTION,
2016
});
2117

2218
// Make a request to the Nilai API
2319
const response = await client.chat.completions.create(
2420
{
25-
model: "google/gemma-3-27b-it",
21+
model: "openai/gpt-oss-20b",
2622
messages: [
2723
{
2824
role: "user",

src/client.ts

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
import { randomUUID } from "node:crypto";
22
import {
3+
Command,
34
Did as DidClass,
45
InvocationBody,
56
Keypair,
6-
NilauthClient,
77
NucTokenBuilder,
88
type NucTokenEnvelope,
99
NucTokenEnvelopeSchema,
10-
PayerBuilder,
1110
} from "@nillion/nuc";
1211
import {
1312
type AclDto,
@@ -22,7 +21,6 @@ import {
2221
DefaultNilDBConfig,
2322
type DelegationTokenRequest,
2423
type DelegationTokenResponse,
25-
NilAuthInstance,
2624
type NilAuthPublicKey,
2725
type NilaiClientOptions,
2826
type NilDBDelegation,
@@ -34,11 +32,9 @@ export interface NilaiOpenAIClientOptions
3432
extends NilaiClientOptions,
3533
ClientOptions {
3634
authType?: AuthType;
37-
nilauthInstance?: NilAuthInstance;
3835
}
3936
export class NilaiOpenAIClient extends OpenAI {
4037
private authType: AuthType = AuthType.API_KEY;
41-
private nilAuthInstance: NilAuthInstance = NilAuthInstance.SANDBOX;
4238
private nilAuthPrivateKey: Keypair | null = null;
4339
private _rootTokenEnvelope: NucTokenEnvelope | null = null;
4440
private delegationToken: NucTokenEnvelope | null = null;
@@ -47,17 +43,11 @@ export class NilaiOpenAIClient extends OpenAI {
4743
constructor(
4844
options: NilaiOpenAIClientOptions = {
4945
authType: AuthType.API_KEY,
50-
nilauthInstance: NilAuthInstance.SANDBOX,
5146
apiKey: "",
5247
baseURL: "",
5348
},
5449
) {
55-
const {
56-
authType = AuthType.API_KEY,
57-
nilauthInstance = NilAuthInstance.SANDBOX,
58-
apiKey,
59-
...openAIOptions
60-
} = options;
50+
const { authType = AuthType.API_KEY, apiKey, ...openAIOptions } = options;
6151

6252
// Set up authentication
6353
const processedOptions = { apiKey: apiKey, ...openAIOptions };
@@ -80,7 +70,6 @@ export class NilaiOpenAIClient extends OpenAI {
8070
super(processedOptions);
8171

8272
this.authType = authType;
83-
this.nilAuthInstance = nilauthInstance;
8473

8574
this._initializeAuth(apiKey);
8675
}
@@ -138,18 +127,16 @@ export class NilaiOpenAIClient extends OpenAI {
138127
}
139128

140129
if (!this._rootTokenEnvelope || isExpired(this._rootTokenEnvelope)) {
141-
const nilauthClient = await NilauthClient.from(
142-
this.nilAuthInstance,
143-
await new PayerBuilder()
144-
.chainUrl("https://rpc.testnet.nilchain-rpc-proxy.nilogy.xyz")
145-
.keypair(this.nilAuthPrivateKey)
146-
.build(),
147-
);
148-
const rootTokenResponse = await nilauthClient.requestToken(
149-
this.nilAuthPrivateKey,
150-
"nilai",
151-
);
152-
this._rootTokenEnvelope = rootTokenResponse.token;
130+
const expirationTime = Math.floor(Date.now() / 1000) + 3600; // 1 hour
131+
const selfDid = new DidClass(this.nilAuthPrivateKey.publicKey());
132+
const rootTokenString = NucTokenBuilder.delegation([])
133+
.command(new Command(["nil", "ai", "generate"]))
134+
.audience(selfDid)
135+
.subject(selfDid)
136+
.expiresAt(expirationTime)
137+
.build(this.nilAuthPrivateKey.privateKey());
138+
this._rootTokenEnvelope =
139+
NucTokenEnvelopeSchema.parse(rootTokenString);
153140
}
154141

155142
return this._rootTokenEnvelope;

src/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ export {
1010
type DelegationTokenRequest,
1111
type DelegationTokenResponse,
1212
type InvocationArgs,
13-
NilAuthInstance,
1413
type NilaiClientOptions,
1514
RequestType,
1615
} from "./types";

src/server.ts

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@ import {
33
DelegationBody,
44
Did as DidClass,
55
Keypair,
6-
NilauthClient,
76
NucTokenBuilder,
87
type NucTokenEnvelope,
9-
PayerBuilder,
8+
NucTokenEnvelopeSchema,
109
} from "@nillion/nuc";
1110

1211
import {
@@ -42,18 +41,16 @@ export class DelegationTokenServer {
4241
}
4342

4443
if (!this._rootTokenEnvelope || isExpired(this._rootTokenEnvelope)) {
45-
const nilauthClient = await NilauthClient.from(
46-
this.config.nilauthInstance,
47-
await new PayerBuilder()
48-
.chainUrl("https://rpc.testnet.nilchain-rpc-proxy.nilogy.xyz")
49-
.keypair(this.nilAuthPrivateKey)
50-
.build(),
51-
);
52-
const rootTokenResponse = await nilauthClient.requestToken(
53-
this.nilAuthPrivateKey,
54-
"nilai",
55-
);
56-
this._rootTokenEnvelope = rootTokenResponse.token;
44+
const expirationTime = Math.floor(Date.now() / 1000) + 3600; // 1 hour
45+
const selfDid = new DidClass(this.nilAuthPrivateKey.publicKey());
46+
const rootTokenString = NucTokenBuilder.delegation([])
47+
.command(new Command(["nil", "ai", "generate"]))
48+
.audience(selfDid)
49+
.subject(selfDid)
50+
.expiresAt(expirationTime)
51+
.build(this.nilAuthPrivateKey.privateKey());
52+
this._rootTokenEnvelope =
53+
NucTokenEnvelopeSchema.parse(rootTokenString);
5754
}
5855

5956
return this._rootTokenEnvelope;

src/types.ts

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ export const PromptDocumentInfoSchema = z.object({
3434
});
3535

3636
export const DelegationServerConfigSchema = z.object({
37-
nilauthInstance: NilAuthInstanceSchema.default(NilAuthInstance.SANDBOX),
3837
expirationTime: z.number().positive().default(60),
3938
tokenMaxUses: z.number().positive().default(1),
4039
prompt_document: PromptDocumentInfoSchema.optional(),
@@ -62,9 +61,6 @@ export type DelegationTokenResponse = z.infer<
6261

6362
export const NilaiClientOptionsSchema = z.object({
6463
authType: AuthTypeSchema.default(AuthType.DELEGATION_TOKEN).optional(),
65-
nilauthInstance: NilAuthInstanceSchema.default(
66-
NilAuthInstance.SANDBOX,
67-
).optional(),
6864
});
6965
export type NilaiClientOptions = z.infer<typeof NilaiClientOptionsSchema>;
7066

@@ -74,7 +70,6 @@ export type InvocationArgs = z.infer<typeof InvocationArgsSchema>;
7470
// Constants with validation
7571
export const DefaultDelegationTokenServerConfig: DelegationServerConfig =
7672
DelegationServerConfigSchema.parse({
77-
nilauthInstance: NilAuthInstance.SANDBOX,
7873
expirationTime: 60,
7974
tokenMaxUses: 1,
8075
});

0 commit comments

Comments
 (0)