forked from wso2/reference-implementations-afm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.bal
More file actions
372 lines (313 loc) · 12.9 KB
/
agent.bal
File metadata and controls
372 lines (313 loc) · 12.9 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import afm_ballerina.everit.validator;
import ballerina/ai;
import ballerina/log;
import ballerina/os;
import ballerina/http;
import ballerinax/ai.anthropic;
import ballerinax/ai.openai;
function createAgent(AFMRecord afmRecord) returns ai:Agent|error {
AFMRecord {metadata, role, instructions} = afmRecord;
ai:McpToolKit[] mcpToolkits = [];
MCPServer[]? mcpServers = metadata?.tools?.mcp;
if mcpServers is MCPServer[] {
foreach MCPServer mcpConn in mcpServers {
Transport transport = mcpConn.transport;
if transport is StdioTransport {
return error("Stdio transport is not yet supported by the Ballerina interpreter");
}
string[]? filteredTools = getFilteredTools(mcpConn.tool_filter);
mcpToolkits.push(check new ai:McpToolKit(
transport.url,
permittedTools = filteredTools,
auth = check mapToHttpClientAuth(transport.authentication)
));
}
}
ai:ModelProvider model = check getModel(metadata?.model);
ai:AgentConfiguration agentConfig = {
systemPrompt: {
role,
instructions
},
tools: mcpToolkits,
model
};
int? maxIterations = metadata?.max_iterations;
if maxIterations is int {
agentConfig.maxIter = maxIterations;
}
ai:Agent|ai:Error agent = new (agentConfig);
if agent is ai:Error {
return error("Failed to create agent", agent);
}
return agent;
}
function getModel(Model? model) returns ai:ModelProvider|error {
if model is () {
string? accessToken = os:getEnv("WSO2_MODEL_PROVIDER_TOKEN");
if accessToken is () {
return error("Environment variable WSO2_MODEL_PROVIDER_TOKEN must be set for Wso2ModelProvider");
}
return new ai:Wso2ModelProvider(
"https://dev-tools.wso2.com/ballerina-copilot/v2.0",
accessToken);
}
string? provider = model.provider;
if provider is () {
return error("This implementation requires the 'provider' of the model to be specified");
}
provider = provider.toLowerAscii();
if provider == "wso2" {
return new ai:Wso2ModelProvider(
model.url ?: "https://dev-tools.wso2.com/ballerina-copilot/v2.0",
check getToken(model.authentication)
);
}
string? name = model.name;
if name is () {
return error("This implementation requires the 'name' of the model to be specified");
}
match provider {
"openai" => {
return new openai:ModelProvider(
check getApiKey(model.authentication),
check name.ensureType(),
model.url ?: "https://api.openai.com/v1"
);
}
"anthropic" => {
return new anthropic:ModelProvider(
check getApiKey(model.authentication),
check name.ensureType(),
model.url ?: "https://api.anthropic.com/v1"
);
}
}
return error(string `Model provider: ${<string>provider} not yet supported`);
}
const DEFAULT_SESSION_ID = "sessionId";
function runAgent(ai:Agent agent, json payload, map<json>? inputSchema = (), map<json>? outputSchema = (), string sessionId = DEFAULT_SESSION_ID)
returns json|InputError|AgentError {
error? validateJsonSchemaResult = validateJsonSchema(inputSchema, payload);
if validateJsonSchemaResult is error {
log:printError("Invalid input payload", 'error = validateJsonSchemaResult);
return error InputError("Invalid input payload");
}
boolean isUpdatedSchema = false;
map<json>? effectiveOutputSchema = outputSchema;
if outputSchema is map<json> {
string|error schemaType = outputSchema["type"].ensureType();
if schemaType is error {
log:printError("Invalid output schema", 'error = schemaType);
return error AgentError("Invalid output schema, expected a 'type' field", schemaType);
}
if schemaType !is "object" {
effectiveOutputSchema = {
"type": "object",
"properties": { "value": outputSchema },
"required": ["value"]
};
isUpdatedSchema = true;
}
}
string|ai:Error run = agent.run(
outputSchema is map<json> ?
string `${payload.toJsonString()}
The final response MUST conform to the following JSON schema: ${effectiveOutputSchema.toJsonString()}
Respond only with the value enclosed between ${"```"} and ${"```"}.`
: payload.toJsonString(),
sessionId);
if run is ai:Error {
log:printError("Agent run failed", 'error = run);
return error AgentError("Agent run failed", run);
}
// If no output schema, return raw response without JSON parsing
if effectiveOutputSchema is () {
return run;
}
string responseJsonStr = extractJsonFromCodeBlock(run);
json|error responseJson = responseJsonStr.fromJsonString();
if responseJson is error {
log:printError("Failed to parse agent response JSON", 'error = responseJson);
return error AgentError("Failed to parse agent response JSON");
}
error? validateOutputSchemaResult = validateJsonSchema(effectiveOutputSchema, responseJson);
if validateOutputSchemaResult is error {
log:printError("Agent response does not conform to output schema", 'error = validateOutputSchemaResult);
return error AgentError("Agent response does not conform to output schema", validateOutputSchemaResult);
}
if !isUpdatedSchema {
return responseJson;
}
map<json>|error responseJsonObject = responseJson.ensureType();
if responseJsonObject is error {
log:printError("Expected agent response to be a JSON object", 'error = responseJsonObject);
return error AgentError("Expected agent response to be a JSON object");
}
return responseJsonObject.get("value");
}
function extractJsonFromCodeBlock(string response) returns string {
// Prioritize ```json block, fall back to generic ```
int? jsonBlockStart = response.indexOf("```json");
int? contentStart = jsonBlockStart is int ? jsonBlockStart + 7 : ();
if contentStart is () {
int? genericStart = response.indexOf("```");
contentStart = genericStart is int ? genericStart + 3 : ();
}
if contentStart is int {
int? blockEnd = response.indexOf("```", contentStart);
if blockEnd is int {
return response.substring(contentStart, blockEnd).trim();
}
}
return response;
}
function getFilteredTools(ToolFilter? toolFilter) returns string[]? {
if toolFilter is () {
return (); // No filtering - all tools allowed
}
string[]? allow = toolFilter.allow;
string[]? deny = toolFilter.deny;
// If no filters specified, return null (all tools)
if allow is () && deny is () {
return ();
}
// If only allow is specified, return it
if allow is string[] && deny is () {
return allow;
}
// If only deny is specified, we can't handle it with current API
// (would need to fetch all tools first, then filter)
if allow is () && deny is string[] {
log:printWarn("Deny-only tool filter not fully supported - ignoring deny list");
return (); // Return all for now
}
// If both specified: apply allow first, then remove denied tools
if allow is string[] && deny is string[] {
string[] filtered = [];
foreach string tool in allow {
boolean isDenied = false;
foreach string deniedTool in deny {
if tool == deniedTool {
isDenied = true;
break;
}
}
if !isDenied {
filtered.push(tool);
}
}
return filtered;
}
return ();
}
isolated function validateJsonSchema(map<json>? jsonSchemaVal, json sampleJson) returns error? {
if jsonSchemaVal is () {
return ();
}
string schemaType = check jsonSchemaVal["type"].ensureType();
if schemaType == "object" {
validator:JSONObject schemaObject = validator:newJSONObject7(jsonSchemaVal.toJsonString());
validator:SchemaLoaderBuilder builder = validator:newSchemaLoaderBuilder1();
validator:SchemaLoader schemaLoader = builder.schemaJson(schemaObject).build();
validator:Schema schema = schemaLoader.load().build();
validator:JSONObject jsonObject = validator:newJSONObject7(sampleJson.toJsonString());
error? validationResult = trap schema.validate(jsonObject);
if validationResult is error {
return error("JSON validation failed: " + validationResult.message());
}
return ();
}
// Wrap value and validate using generated object schema
map<json> valueSchema = {
"type": "object",
"properties": { "value": jsonSchemaVal },
"required": ["value"]
};
validator:JSONObject schemaObject = validator:newJSONObject7(valueSchema.toJsonString());
validator:SchemaLoaderBuilder builder = validator:newSchemaLoaderBuilder1();
validator:SchemaLoader schemaLoader = builder.schemaJson(schemaObject).build();
validator:Schema schema = schemaLoader.load().build();
map<json> wrapped = { "value": sampleJson };
validator:JSONObject jsonObject = validator:newJSONObject7(wrapped.toJsonString());
error? validationResult = trap schema.validate(jsonObject);
if validationResult is error {
return error("JSON validation failed: " + validationResult.message());
}
}
function getApiKey(ClientAuthentication? auth) returns string|error =>
getAuthTokenOrApiKey(auth, "api-key", "api_key");
function getToken(ClientAuthentication? auth) returns string|error =>
getAuthTokenOrApiKey(auth, "bearer", "token");
function getAuthTokenOrApiKey(ClientAuthentication? auth, string expectedType, string expectedKey) returns string|error {
if auth is () {
return error("No authentication provided");
}
if auth.'type.toLowerAscii() != expectedType {
return error(string `Unsupported authentication type for ${expectedType}: ${auth.'type}`);
}
if !auth.hasKey(expectedKey) {
return error(string `${expectedKey} not found in 'authentication'`);
}
return auth.get(expectedKey).ensureType();
}
function mapToHttpClientAuth(ClientAuthentication? auth) returns http:ClientAuthConfig|error? {
if auth is () {
return ();
}
ClientAuthentication {'type, ...rest} = auth;
'type = 'type.toLowerAscii();
match 'type {
"basic" => {
return rest.cloneWithType(http:CredentialsConfig);
}
"bearer" => {
return rest.cloneWithType(http:BearerTokenConfig);
}
"oauth2" => {
// record {string grantType;}|error oauth2Config = check rest.cloneWithType();
// if oauth2Config is error {
// return error("OAuth2 authentication requires 'grantType' field", oauth2Config);
// }
// var {grantType, ...oauth2ConfigRest} = oauth2Config;
// match grantType.toLowerAscii() {
// "client_credentials" => {
// return oauth2ConfigRest.cloneWithType(http:OAuth2ClientCredentialsGrantConfig);
// }
// "password" => {
// return oauth2ConfigRest.cloneWithType(http:OAuth2PasswordGrantConfig);
// }
// "refresh_token" => {
// return oauth2ConfigRest.cloneWithType(http:OAuth2RefreshTokenGrantConfig);
// }
// "jwt" => {
// return oauth2Config.cloneWithType(http:OAuth2JwtBearerGrantConfig);
// }
// }
// panic error(string `Unsupported OAuth2 grant type: ${grantType}`);
return error("OAuth2 authentication not yet supported");
}
"jwt" => {
// return rest.cloneWithType(http:JwtIssuerConfig);
return error("JWT authentication not yet supported");
}
_ => {
return error(string `Unsupported authentication type: ${'type}`);
}
}
}