Skip to content

Commit 66d1fa1

Browse files
authored
Merge pull request #77 from nevermined-io/fix/library
fix: adaptations to integrate with client
2 parents dfd850b + 7d4e784 commit 66d1fa1

File tree

14 files changed

+352
-124
lines changed

14 files changed

+352
-124
lines changed

CHANGELOG.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file. Dates are d
44

55
Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
66

7+
#### [v0.5.2](https://github.com/nevermined-io/payments/compare/v0.5.1...v0.5.2)
8+
9+
> 22 October 2024
10+
11+
- feat: createAgent method [`60d8332`](https://github.com/nevermined-io/payments/commit/60d8332bbcdd0d8f1014a7e1f49b7092d20c8bab)
12+
- fix: adaptations to integrate with client [`f833203`](https://github.com/nevermined-io/payments/commit/f83320361a6dbb2cf880277f462914fd493dfb07)
13+
- chore: format [`1dc16fd`](https://github.com/nevermined-io/payments/commit/1dc16fdbf7be2974dd7bb6495b9a00244f339c0f)
14+
715
#### [v0.5.1](https://github.com/nevermined-io/payments/compare/v0.5.0...v0.5.1)
816

917
> 18 October 2024

package.json

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@nevermined-io/payments",
3-
"version": "0.5.1",
3+
"version": "0.5.3",
44
"description": "Typescript SDK to interact with the Nevermined Payments Protocol",
55
"main": "./dist/index.js",
66
"types": "./dist/index.d.ts",
@@ -30,6 +30,7 @@
3030
},
3131
"devDependencies": {
3232
"@types/node": "^20.11.19",
33+
"@types/uuid": "10.0.0",
3334
"@typescript-eslint/eslint-plugin": "^7.0.2",
3435
"@typescript-eslint/parser": "^7.0.2",
3536
"eslint": "^8.56.0",
@@ -51,6 +52,7 @@
5152
"socket.io-client": "4.7.5",
5253
"axios": "^1.7.7",
5354
"jose": "^5.2.4",
54-
"js-file-download": "^0.4.12"
55+
"js-file-download": "^0.4.12",
56+
"uuid": "^10.0.0"
5557
}
5658
}

src/api/nvm-backend.ts

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import axios from 'axios'
22
import { io } from 'socket.io-client'
33
import { decodeJwt } from 'jose'
4-
import { isEthereumAddress, sleep } from '../common/utils'
54
import { AgentExecutionStatus } from '../common/types'
5+
import { isEthereumAddress } from '../utils'
6+
import { sleep } from '../common/helper'
67

78
export interface BackendApiOptions {
89
/**
@@ -161,12 +162,11 @@ export class NVMBackendApi {
161162
throw new Error('Unable to subscribe to the server becase a key was not provided')
162163

163164
if (this.socketClient && this.socketClient.connected) {
164-
console.log('nvm-backend:: Already connected to the websocket server')
165+
// nvm-backend:: Already connected to the websocket server
165166
return
166167
}
167168
try {
168-
console.log(`nvm-backend:: Connecting to websocket server: ${this.opts.webSocketHost}`)
169-
console.log(JSON.stringify(this.opts.webSocketOptions))
169+
// nvm-backend:: Connecting to websocket server: ${this.opts.webSocketHost}
170170
this.socketClient = io(this.opts.webSocketHost!, this.opts.webSocketOptions)
171171
await this.socketClient.connect()
172172
for (let i = 0; i < 5; i++) {
@@ -178,7 +178,6 @@ export class NVMBackendApi {
178178
if (!this.socketClient.connected) {
179179
throw new Error('Unable to connect to the websocket server')
180180
}
181-
console.log('is connected: ', this.socketClient.connected)
182181
} catch (error) {
183182
throw new Error(
184183
`Unable to initialize websocket client: ${this.opts.webSocketHost} - ${(error as Error).message}`,
@@ -204,9 +203,8 @@ export class NVMBackendApi {
204203
await this.connectSocket()
205204
// await this.socketClient.emit('subscribe-agent', '')
206205
await this.socketClient.on('connect', async () => {
207-
console.log(`nvm-backend:: On:: ${this.socketClient.id} Connected to the server`)
206+
// nvm-backend:: On:: ${this.socketClient.id} Connected to the server
208207
})
209-
console.log(`Subscription Options: ${JSON.stringify(opts)}`)
210208
await this.socketClient.emit('_join-rooms', JSON.stringify(opts))
211209

212210
// await this.socketClient.on('task-updated', (data: any) => {
@@ -215,21 +213,13 @@ export class NVMBackendApi {
215213
// })
216214
opts.subscribeEventTypes.forEach(async (eventType) => {
217215
await this.socketClient.on(eventType, (data: any) => {
218-
// console.log(`RECEIVED STEP data: ${JSON.stringify(data)}`)
219216
_callback(data)
220217
})
221218
})
222219
}
223220

224221
private async eventHandler(data: any, _callback: (err?: any) => any, _opts: SubscriptionOptions) {
225222
_callback(data)
226-
// if (opts.subscribeEventTypes.length > 0) {
227-
// if (opts.subscribeEventTypes.includes(data.event)) {
228-
// _callback(data)
229-
// }
230-
// } else {
231-
// _callback(data)
232-
// }
233223
}
234224

235225
protected async _emitStepEvents(
@@ -246,7 +236,7 @@ export class NVMBackendApi {
246236

247237
disconnect() {
248238
this.disconnectSocket()
249-
console.log('nvm-backend:: Disconnected from the server')
239+
// nvm-backend:: Disconnected from the server
250240
}
251241

252242
parseUrl(uri: string, reqOptions: HTTPRequestOptions) {
@@ -284,9 +274,6 @@ export class NVMBackendApi {
284274
}
285275

286276
async post(url: string, data: any, reqOptions: HTTPRequestOptions) {
287-
console.log('POST URL', this.parseUrl(url, reqOptions))
288-
console.log('POST DATA', data)
289-
console.log('POST HEADERS', this.parseHeaders(reqOptions.headers || {}))
290277
return axios({
291278
method: 'POST',
292279
url: this.parseUrl(url, reqOptions),

src/api/query-api.ts

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { AgentExecutionStatus } from '../common/types'
1+
import { AgentExecutionStatus, Step } from '../common/types'
22
import {
33
BackendApiOptions,
44
DefaultSubscriptionOptions,
@@ -49,7 +49,7 @@ export class AIQueryOptions {
4949
/**
5050
* The Nevermined Proxy that needs to be used to interact with the AI Agent/Service.
5151
*/
52-
proxyHost?: string
52+
neverminedProxyUri?: string
5353
}
5454

5555
/**
@@ -78,15 +78,15 @@ export class AIQueryApi extends NVMBackendApi {
7878
opts: SubscriptionOptions = DefaultSubscriptionOptions,
7979
) {
8080
await super._subscribe(_callback, opts).then(() => {
81-
console.log('query-api:: Subscribed to server')
81+
// query-api:: Subscribed to server
8282
})
8383
try {
8484
if (opts.getPendingEventsOnSubscribe) {
85-
console.log('query-api:: Emitting pending events')
85+
// query-api:: Emitting pending events
8686
await super._emitStepEvents(AgentExecutionStatus.Pending, opts.joinAgentRooms)
8787
}
8888
} catch {
89-
console.warn('query-api:: Unable to get pending events')
89+
// query-api:: Unable to get pending events
9090
}
9191
}
9292

@@ -129,15 +129,13 @@ export class AIQueryApi extends NVMBackendApi {
129129
*/
130130
async createTask(did: string, task: any, queryOpts: AIQueryOptions) {
131131
const endpoint = TASK_ENDPOINT.replace('{did}', did)
132-
console.log('endpoint', endpoint)
133132
const reqOptions: HTTPRequestOptions = {
134133
sendThroughProxy: true,
135-
...(queryOpts.proxyHost && { proxyHost: queryOpts.proxyHost }),
134+
...(queryOpts.neverminedProxyUri && { proxyHost: queryOpts.neverminedProxyUri }),
136135
...(queryOpts.accessToken && {
137136
headers: { Authorization: `Bearer ${queryOpts.accessToken}` },
138137
}),
139138
}
140-
console.log('reqOptions', reqOptions)
141139
return this.post(endpoint, task, reqOptions)
142140
}
143141

@@ -172,12 +170,11 @@ export class AIQueryApi extends NVMBackendApi {
172170
async getTaskWithSteps(did: string, taskId: string, queryOpts: AIQueryOptions) {
173171
const reqOptions: HTTPRequestOptions = {
174172
sendThroughProxy: true,
175-
...(queryOpts.proxyHost && { proxyHost: queryOpts.proxyHost }),
173+
...(queryOpts.neverminedProxyUri && { proxyHost: queryOpts.neverminedProxyUri }),
176174
...(queryOpts.accessToken && {
177175
headers: { Authorization: `Bearer ${queryOpts.accessToken}` },
178176
}),
179177
}
180-
console.log('reqOptions', reqOptions)
181178
return this.get(GET_TASK_ENDPOINT.replace('{did}', did).replace('{taskId}', taskId), reqOptions)
182179
}
183180

@@ -207,6 +204,7 @@ export class AIQueryApi extends NVMBackendApi {
207204
* const result = await payments.query.updateStep(step.did, step.task_id, step.step_id, {
208205
* step_id: step.step_id,
209206
* task_id: step.task_id,
207+
* did: step.did,
210208
* step_status: AgentExecutionStatus.Completed,
211209
* is_last: true,
212210
* output: 'LFG!',
@@ -215,12 +213,14 @@ export class AIQueryApi extends NVMBackendApi {
215213
* ```
216214
*
217215
* @param did - Agent DID
218-
* @param taskId - Task ID
219-
* @param stepId - Step ID
220216
* @param step - The Step object to update. @see https://docs.nevermined.io/docs/protocol/query-protocol#steps-attributes
221217
* @returns The result of the operation
222218
*/
223-
async updateStep(did: string, taskId: string, stepId: string, step: any) {
219+
async updateStep(did: string, step: Partial<Step>) {
220+
const { task_id: taskId, step_id: stepId } = step
221+
if (!taskId || !stepId)
222+
throw new Error('The step object must contain the task_id and step_id attributes')
223+
224224
const endpoint = UPDATE_STEP_ENDPOINT.replace('{did}', did)
225225
.replace('{taskId}', taskId)
226226
.replace('{stepId}', stepId)
@@ -263,6 +263,28 @@ export class AIQueryApi extends NVMBackendApi {
263263
return this.post(SEARCH_STEPS_ENDPOINT, searchParams, { sendThroughProxy: false })
264264
}
265265

266+
/**
267+
* It retrieves the complete information of a specific step given a stepId
268+
*
269+
* @remarks
270+
* This method is used by the AI Agent to retrieve information about the steps part of tasks created by users to the agents owned by the user
271+
*
272+
* @example
273+
* ```
274+
* await paymentsBuilder.query.getStep('step-1234')
275+
* ```
276+
*
277+
* @param stepId - the id of the step to retrieve
278+
* @returns The complete step information
279+
*/
280+
async getStep(stepId: string) {
281+
const result = await this.searchSteps({ step_id: stepId })
282+
if (result.status === 200 && result.data && result.data.steps && result.data.steps.length > 0) {
283+
return result.data.steps[0]
284+
}
285+
throw new Error(`Step with id ${stepId} not found`)
286+
}
287+
266288
/**
267289
* It retrieves all the steps that the agent needs to execute to complete a specific task associated to the user.
268290
*

src/common/helper.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Endpoint } from '../payments'
2+
3+
export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
4+
5+
export const jsonReplacer = (_key: any, value: { toString: () => any }) => {
6+
return typeof value === 'bigint' ? value.toString() : value
7+
}
8+
9+
export const getServiceHostFromEndpoints = (endpoints: Endpoint[]): string => {
10+
let serviceHost = ''
11+
endpoints.some((endpoint) => {
12+
const _endpoint = Object.values(endpoint)[0]
13+
serviceHost = new URL(_endpoint).origin
14+
})
15+
return serviceHost
16+
}

src/common/types.ts

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
export const FIRST_STEP_NAME = 'init'
2+
13
/**
24
* A task defines something that the agent should execute.
35
*/
@@ -7,6 +9,11 @@ export interface Task extends ExecutionOptions {
79
*/
810
task_id: string
911

12+
/**
13+
* The status of the execution
14+
*/
15+
task_status: AgentExecutionStatus
16+
1017
/**
1118
* The steps executed by the agent to complete the task
1219
*/
@@ -29,6 +36,11 @@ export interface Step extends ExecutionOptions {
2936
*/
3037
task_id: string
3138

39+
/**
40+
* The status of the execution
41+
*/
42+
step_status: AgentExecutionStatus
43+
3244
/**
3345
* Whether this is the last step in the task.
3446
*/
@@ -40,25 +52,7 @@ export interface Step extends ExecutionOptions {
4052
name?: string
4153
}
4254

43-
export const FIRST_STEP_NAME = 'init'
44-
export const LAST_STEP_NAME = 'init'
45-
46-
export interface ExecutionOptions {
47-
/**
48-
* The input for the task. It can be a prompt, a question, etc
49-
*/
50-
input: ExecutionInput
51-
52-
/**
53-
* The status of the execution
54-
*/
55-
status: AgentExecutionStatus
56-
57-
/**
58-
* The output of the step
59-
*/
60-
output?: ExecutionOutput
61-
55+
export interface ExecutionOptions extends ExecutionInput, ExecutionOutput {
6256
/**
6357
* When the execution was created
6458
*/
@@ -73,6 +67,11 @@ export interface ExecutionOptions {
7367
* The number of retries for the task or step
7468
*/
7569
retries?: number
70+
71+
/**
72+
* The cost in credits resulting from the execution of the task or the step
73+
*/
74+
cost?: number
7675
}
7776

7877
/**
@@ -82,39 +81,38 @@ export interface ExecutionInput {
8281
/**
8382
* The input for the task. It can be a prompt, a question, etc
8483
*/
85-
query: string
84+
input_query: string
8685

8786
/**
8887
* Additional parameters required for the task
8988
*/
90-
additional_params?: { [name: string]: string }[]
89+
input_params?: { [name: string]: string }[]
9190

9291
/**
9392
* List of artifact ids that are associated with the task
9493
*/
95-
artifacts?: Artifact[]
94+
input_artifacts?: Artifact[]
9695
}
9796

9897
/**
9998
* Output of the task or step execution
10099
*/
101100
export interface ExecutionOutput {
102101
/**
103-
* The main output of the task
102+
* The main output generated by a task or step
104103
*/
105-
106104
output: any
107105

108106
/**
109107
* Additional output generated
110108
*/
111109

112-
additional_output?: { [name: string]: any }[]
110+
output_additional?: { [name: string]: any }[]
113111

114112
/**
115113
* List of artifact generated by the task or step
116114
*/
117-
artifacts?: string[]
115+
output_artifacts?: any[]
118116
}
119117

120118
/**

src/common/utils.ts

Lines changed: 0 additions & 10 deletions
This file was deleted.

src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
export * from './environments'
22
export * from './payments'
3+
export * from './utils'
34
export * from './common/types'
45
export * from './common/payments.error'
5-
export * from './common/utils'
6+
export * from './common/helper'
67
export * from './api/query-api'
78
export { BackendApiOptions, BackendWebSocketOptions } from './api/nvm-backend'

0 commit comments

Comments
 (0)