Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/agent-code-snippets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@truefoundry/trueforge": patch
---

Add GET /api/v1/agents/{agent_id}/code-snippets with TypeScript TrueForge SDK stream and non-stream samples.
112 changes: 112 additions & 0 deletions .github/fern/openapi/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -4426,6 +4426,118 @@
"x-fern-sdk-method-name": "update"
}
},
"/api/v1/agents/{agent_id}/code-snippets": {
"get": {
"description": "TypeScript TrueForge SDK samples (stream and non-stream) for creating a session and turn against this agent.",
"parameters": [
{
"description": "Immutable agent identifier.",
"in": "path",
"name": "agent_id",
"required": true,
"schema": {
"description": "Immutable agent identifier.",
"maxLength": 64,
"minLength": 1,
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"data": {
"additionalProperties": false,
"properties": {
"base_url": {
"description": "Origin to pass as the TrueForge SDK `baseUrl`.",
"format": "uri",
"type": "string"
},
"snippets": {
"items": {
"additionalProperties": false,
"properties": {
"icon": {
"format": "uri",
"type": "string"
},
"label_name": {
"minLength": 1,
"type": "string"
},
"language": {
"minLength": 1,
"type": "string"
},
"sample_code": {
"additionalProperties": false,
"properties": {
"non_stream": {
"description": "SDK sample that creates a turn without streaming.",
"type": "string"
},
"stream": {
"description": "SDK sample that streams turn events.",
"type": "string"
}
},
"required": [
"stream",
"non_stream"
],
"type": "object"
}
},
"required": [
"label_name",
"language",
"icon",
"sample_code"
],
"type": "object"
},
"type": "array"
}
},
"required": [
"base_url",
"snippets"
],
"type": "object"
}
},
"required": [
"data"
],
"type": "object"
}
}
},
"description": "TypeScript SDK samples and the origin to use as `baseUrl`."
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RequestErrorResponse"
}
}
},
"description": "Agent not found."
}
},
"summary": "Get agent SDK code snippets",
"tags": [
"Agents"
],
"x-excluded": true,
"x-fern-ignore": true
}
},
"/api/v1/auth/callback": {
"get": {
"description": "Browser-redirect target hit by the identity provider after login, never called directly by SDK consumers. In local/single-binary mode, redirects straight back into the app.",
Expand Down
112 changes: 112 additions & 0 deletions docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -4426,6 +4426,118 @@
"x-fern-sdk-method-name": "update"
}
},
"/api/v1/agents/{agent_id}/code-snippets": {
"get": {
"description": "TypeScript TrueForge SDK samples (stream and non-stream) for creating a session and turn against this agent.",
"parameters": [
{
"description": "Immutable agent identifier.",
"in": "path",
"name": "agent_id",
"required": true,
"schema": {
"description": "Immutable agent identifier.",
"maxLength": 64,
"minLength": 1,
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"data": {
"additionalProperties": false,
"properties": {
"base_url": {
"description": "Origin to pass as the TrueForge SDK `baseUrl`.",
"format": "uri",
"type": "string"
},
"snippets": {
"items": {
"additionalProperties": false,
"properties": {
"icon": {
"format": "uri",
"type": "string"
},
"label_name": {
"minLength": 1,
"type": "string"
},
"language": {
"minLength": 1,
"type": "string"
},
"sample_code": {
"additionalProperties": false,
"properties": {
"non_stream": {
"description": "SDK sample that creates a turn without streaming.",
"type": "string"
},
"stream": {
"description": "SDK sample that streams turn events.",
"type": "string"
}
},
"required": [
"stream",
"non_stream"
],
"type": "object"
}
},
"required": [
"label_name",
"language",
"icon",
"sample_code"
],
"type": "object"
},
"type": "array"
}
},
"required": [
"base_url",
"snippets"
],
"type": "object"
}
},
"required": [
"data"
],
"type": "object"
}
}
},
"description": "TypeScript SDK samples and the origin to use as `baseUrl`."
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RequestErrorResponse"
}
}
},
"description": "Agent not found."
}
},
"summary": "Get agent SDK code snippets",
"tags": [
"Agents"
],
"x-excluded": true,
"x-fern-ignore": true
}
},
"/api/v1/auth/callback": {
"get": {
"description": "Browser-redirect target hit by the identity provider after login, never called directly by SDK consumers. In local/single-binary mode, redirects straight back into the app.",
Expand Down
35 changes: 35 additions & 0 deletions packages/trueforge/src/apis/agentCodeSnippets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type { AgentCodeSnippets } from '../schemas/agent';
import { typescriptNonStreamTemplate, typescriptStreamTemplate } from './codesnippet-templates/typescript';

const TYPESCRIPT_ICON = 'https://assets.production.truefoundry.com/typescript.svg';

function renderSnippetTemplate(template: string, vars: { agentName: string; baseUrl: string }): string {
const literals: Record<string, string> = {
agentName: JSON.stringify(vars.agentName),
baseUrl: JSON.stringify(vars.baseUrl),
};
return template.replaceAll(/\{\{(\w+)\}\}/g, (match, key: string) => {
const value = literals[key];
if (value === undefined) {
throw new Error(`Unknown snippet template placeholder ${match}`);
}
return value;
});
}

export function buildAgentCodeSnippets(input: { agentName: string; baseUrl: string }): AgentCodeSnippets {
return {
base_url: input.baseUrl,
snippets: [
{
label_name: 'TypeScript',
language: 'typescript',
icon: TYPESCRIPT_ICON,
sample_code: {
stream: renderSnippetTemplate(typescriptStreamTemplate, input),
non_stream: renderSnippetTemplate(typescriptNonStreamTemplate, input),
},
},
],
};
}
20 changes: 20 additions & 0 deletions packages/trueforge/src/apis/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import type { WithTransaction } from '../db/transaction';
import {
createAgentRoute,
deleteAgentRoute,
getAgentCodeSnippetsRoute,
getAgentRoute,
listAgentsRoute,
putAgentRoute,
} from '../routes/agentRoutes';
import { validateAgentSpec } from '../runtime/sessionResources';
import { type Agent, type CreateAgentRequest } from '../schemas/agent';
import { buildAgentCodeSnippets } from './agentCodeSnippets';
import { TENANT_ID } from './sessions';

export interface AgentsRouterDeps<TTransaction> {
Expand Down Expand Up @@ -89,6 +91,23 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
return c.json({ data: toWireAgent(record) }, 200);
};

const getCodeSnippetsHandler: RouteHandler<typeof getAgentCodeSnippetsRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
const record = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, id: agentId });
if (record === undefined) {
return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
}
return c.json(
{
data: buildAgentCodeSnippets({
agentName: record.name,
baseUrl: new URL(c.req.url).origin,
}),
},
200,
);
};

const deleteHandler: RouteHandler<typeof deleteAgentRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
await deps.agentStore.deleteAgent({ tenant_id: TENANT_ID, id: agentId });
Expand All @@ -113,6 +132,7 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const router = new OpenAPIHono();
router.openapi(listAgentsRoute, listHandler);
router.openapi(createAgentRoute, createHandler);
router.openapi(getAgentCodeSnippetsRoute, getCodeSnippetsHandler);
router.openapi(getAgentRoute, getHandler);
router.openapi(deleteAgentRoute, deleteHandler);
router.openapi(putAgentRoute, putHandler);
Expand Down
55 changes: 55 additions & 0 deletions packages/trueforge/src/apis/codesnippet-templates/typescript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
export const typescriptStreamTemplate = `// npm install @truefoundry/trueforge-sdk
import { TrueForge, TrueForgeApi, isEventDelta, mergeEventDelta } from "@truefoundry/trueforge-sdk";

const client = new TrueForge({
baseUrl: {{baseUrl}},
timeoutInSeconds: 600,
});

const { data: session } = await client.sessions.create({
agent: { name: {{agentName}} },
});

const events = new Map<string, TrueForgeApi.TurnStreamingEvent>();
let turnId: string | undefined;
let lastSequenceNumber = 0;

const stream = await client.sessions.createTurnStream(session.id, {
input: [{ type: "user.message", content: "Hello!" }],
});

for await (const { data: event, id } of stream.withMetadata()) {
if (id != null) lastSequenceNumber = Number(id);
if (event.type === "turn.created") turnId = event.turnId;
if (isEventDelta(event)) {
const base = events.get(event.id);
if (base) mergeEventDelta(base, event);
} else {
events.set(event.id, event);
}
if (event.type === "turn.done") console.log("status:", event.state.status);
}
`;

export const typescriptNonStreamTemplate = `// npm install @truefoundry/trueforge-sdk
import { TrueForge } from "@truefoundry/trueforge-sdk";

const client = new TrueForge({
baseUrl: {{baseUrl}},
timeoutInSeconds: 600,
});

const { data: session } = await client.sessions.create({
agent: { name: {{agentName}} },
});

const { data: turn } = await client.sessions.createTurn(session.id, {
input: [{ type: "user.message", content: "Hello!" }],
});

console.log(turn.id, turn.state);

// Turn may still be running. Call getTurn to read a later state.
const { data: latest } = await client.sessions.getTurn(session.id, turn.id);
console.log(latest.state);
`;
Loading