-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathlyzr.ts
More file actions
167 lines (138 loc) · 5.35 KB
/
lyzr.ts
File metadata and controls
167 lines (138 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { randomBytes } from 'node:crypto';
import { exportToLyzr } from '../adapters/lyzr.js';
import { AgentManifest } from '../utils/loader.js';
import { error, info, success, label, heading, divider } from '../utils/format.js';
import { ensureLyzrAuth } from '../utils/auth-provision.js';
const LYZR_AGENT_BASE_URL = 'https://agent-prod.studio.lyzr.ai';
export interface LyzrRunOptions {
prompt?: string;
apiKey?: string;
userId?: string;
}
/**
* Create a new Lyzr agent from a gitagent directory.
* Returns the agent_id from Lyzr Studio.
*/
export async function createLyzrAgent(agentDir: string, options: LyzrRunOptions = {}): Promise<string> {
const apiKey = ensureLyzrAuth(options.apiKey);
const payload = exportToLyzr(agentDir);
info('Creating Lyzr agent "' + String(payload.name) + '"...');
label('Provider', payload.provider_id);
label('Model', payload.model);
const resp = await fetch(`${LYZR_AGENT_BASE_URL}/v3/agents/template/single-task`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
},
body: JSON.stringify(payload),
});
if (!resp.ok) {
const body = await resp.text();
error('Failed to create agent (' + String(resp.status) + '): ' + body);
process.exit(1);
}
const data = await resp.json() as { agent_id?: string; [key: string]: unknown };
if (!data.agent_id) {
error('No agent_id returned from Lyzr API');
error(JSON.stringify(data, null, 2));
process.exit(1);
}
success('Agent created: ' + String(data.agent_id));
return data.agent_id;
}
/**
* Update an existing Lyzr agent with the current gitagent definition.
* Fetches the existing agent, merges with the local export, then PUTs.
*/
export async function updateLyzrAgent(agentDir: string, agentId: string, options: LyzrRunOptions = {}): Promise<void> {
const apiKey = ensureLyzrAuth(options.apiKey);
// Fetch existing agent to merge
const safeAgentId = encodeURIComponent(agentId);
info('Fetching existing agent ' + agentId + '...');
const getResp = await fetch(LYZR_AGENT_BASE_URL + '/v3/agents/' + safeAgentId, {
headers: { 'x-api-key': apiKey },
});
if (!getResp.ok) {
const fetchErrBody = await getResp.text();
error('Failed to fetch agent (' + String(getResp.status) + '): ' + fetchErrBody);
process.exit(1);
}
const existing = await getResp.json() as Record<string, unknown>;
const payload = exportToLyzr(agentDir);
// Merge: new payload overrides existing
const merged = { ...existing, ...payload };
info('Updating agent "' + String(payload.name) + '" (' + agentId + ')...');
const resp = await fetch(LYZR_AGENT_BASE_URL + '/v3/agents/template/single-task/' + safeAgentId, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
},
body: JSON.stringify(merged),
});
if (!resp.ok) {
const updateErrBody = await resp.text();
error('Failed to update agent (' + String(resp.status) + '): ' + updateErrBody);
process.exit(1);
}
success('Agent updated: ' + agentId);
}
/**
* Run/chat with a Lyzr agent.
*
* If no .lyzr_agent_id file exists in the agent directory, the agent is
* created on Lyzr Studio first and the ID is saved for reuse.
* Then sends the prompt via the inference chat endpoint.
*/
export async function runWithLyzr(agentDir: string, manifest: AgentManifest, options: LyzrRunOptions = {}): Promise<void> {
const apiKey = ensureLyzrAuth(options.apiKey);
// Lyzr requires a prompt (no interactive mode)
if (!options.prompt) {
error('Lyzr requires a prompt. Use -p "your message" to provide one.');
info('Example: gitagent run -r <url> -a lyzr -p "Review my auth module"');
process.exit(1);
}
// Resolve or create agent on Lyzr
const agentIdFile = join(agentDir, '.lyzr_agent_id');
let agentId: string;
if (existsSync(agentIdFile)) {
agentId = readFileSync(agentIdFile, 'utf-8').trim();
info('Using existing Lyzr agent: ' + agentId);
} else {
info('No .lyzr_agent_id found — creating agent on Lyzr...');
agentId = await createLyzrAgent(agentDir, options);
writeFileSync(agentIdFile, agentId, 'utf-8');
info(`Saved agent ID to .lyzr_agent_id`);
}
divider();
// Build chat request
const userId = options.userId || apiKey;
const sessionId = encodeURIComponent(agentId) + '-' + randomBytes(4).toString('hex');
info('Launching Lyzr agent "' + String(manifest.name) + '"...');
const resp = await fetch(`${LYZR_AGENT_BASE_URL}/v3/inference/chat/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
},
body: JSON.stringify({
user_id: userId,
agent_id: agentId,
session_id: sessionId,
message: options.prompt,
}),
});
if (!resp.ok) {
const body = await resp.text();
error('Chat failed (' + String(resp.status) + '): ' + body);
info('Make sure your LYZR_API_KEY is valid and the agent exists on Lyzr Studio');
process.exit(1);
}
const data = await resp.json() as { response?: string; result?: string; message?: string; [key: string]: unknown };
// The API may return the response in different fields
const response = data.response || data.result || data.message || JSON.stringify(data, null, 2);
console.log(response);
}