|
| 1 | +import type { AgentRequest, AgentResponse, AgentContext } from "@agentuity/sdk"; |
| 2 | +import { streamText } from "ai"; |
| 3 | +import { openai } from "@ai-sdk/openai"; |
| 4 | +import { createTools } from "./tools"; |
| 5 | +import { createAgentState } from "./state"; |
| 6 | +import { getTutorialList, type Tutorial } from "./tutorial"; |
| 7 | +import { parseAgentRequest } from "./request/parser"; |
| 8 | +import { buildSystemPrompt } from "./context/builder"; |
| 9 | +import { createStreamingProcessor } from "./streaming/processor"; |
| 10 | +import type { ConversationMessage, TutorialState } from "./request/types"; |
| 11 | + |
| 12 | +/** |
| 13 | + * Builds a context string containing available tutorials for the system prompt |
| 14 | + */ |
| 15 | +async function buildContext( |
| 16 | + ctx: AgentContext, |
| 17 | + tutorialState?: TutorialState |
| 18 | +): Promise<string> { |
| 19 | + try { |
| 20 | + const tutorials = await getTutorialList(ctx); |
| 21 | + |
| 22 | + // Handle API failure early |
| 23 | + if (!tutorials.success || !tutorials.data) { |
| 24 | + ctx.logger.warn("Failed to load tutorial list"); |
| 25 | + return defaultFallbackContext(); |
| 26 | + } |
| 27 | + |
| 28 | + const tutorialContent = JSON.stringify(tutorials.data, null, 2); |
| 29 | + const currentTutorialInfo = buildCurrentTutorialInfo( |
| 30 | + tutorials.data, |
| 31 | + tutorialState |
| 32 | + ); |
| 33 | + |
| 34 | + return `===AVAILABLE TUTORIALS==== |
| 35 | +
|
| 36 | + ${tutorialContent} |
| 37 | +
|
| 38 | + ${currentTutorialInfo} |
| 39 | +
|
| 40 | + Note: You should not expose the details of the tutorial IDs to the user. |
| 41 | +`; |
| 42 | + } catch (error) { |
| 43 | + ctx.logger.error("Error building tutorial context: %s", error); |
| 44 | + return defaultFallbackContext(); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Builds current tutorial information string if user is in a tutorial |
| 50 | + */ |
| 51 | +function buildCurrentTutorialInfo( |
| 52 | + tutorials: Tutorial[], |
| 53 | + tutorialState?: TutorialState |
| 54 | +): string { |
| 55 | + if (!tutorialState?.tutorialId) { |
| 56 | + return ""; |
| 57 | + } |
| 58 | + |
| 59 | + const currentTutorial = tutorials.find( |
| 60 | + (t) => t.id === tutorialState.tutorialId |
| 61 | + ); |
| 62 | + if (!currentTutorial) { |
| 63 | + return "\nWarning: User appears to be in an unknown tutorial."; |
| 64 | + } |
| 65 | + if (tutorialState.currentStep > currentTutorial.totalSteps) { |
| 66 | + return `\nUser has completed the tutorial: ${currentTutorial.title} (${currentTutorial.totalSteps} steps)`; |
| 67 | + } |
| 68 | + return `\nUser is currently on this tutorial: ${currentTutorial.title} (Step ${tutorialState.currentStep} of ${currentTutorial.totalSteps})`; |
| 69 | +} |
| 70 | + |
| 71 | +/** |
| 72 | + * Returns fallback context when tutorial list can't be loaded |
| 73 | + */ |
| 74 | +function defaultFallbackContext(): string { |
| 75 | + return `===AVAILABLE TUTORIALS==== |
| 76 | +Unable to load tutorial list. Please try again later or contact support.`; |
| 77 | +} |
| 78 | + |
| 79 | +export default async function Agent( |
| 80 | + req: AgentRequest, |
| 81 | + resp: AgentResponse, |
| 82 | + ctx: AgentContext |
| 83 | +) { |
| 84 | + try { |
| 85 | + const parsedRequest = parseAgentRequest(await req.data.json(), ctx); |
| 86 | + |
| 87 | + // Create state manager |
| 88 | + const state = createAgentState(); |
| 89 | + |
| 90 | + // Build messages for the conversation |
| 91 | + const messages: ConversationMessage[] = [ |
| 92 | + ...parsedRequest.conversationHistory, |
| 93 | + { author: "USER", content: parsedRequest.message }, |
| 94 | + ]; |
| 95 | + |
| 96 | + let tools: any; |
| 97 | + let systemPrompt: string = ""; |
| 98 | + // Direct LLM access won't require any tools or system prompt |
| 99 | + if (!parsedRequest.useDirectLLM) { |
| 100 | + // Create tools with state context |
| 101 | + tools = await createTools({ |
| 102 | + state, |
| 103 | + agentContext: ctx, |
| 104 | + }); |
| 105 | + |
| 106 | + // Build tutorial context and system prompt |
| 107 | + const tutorialContext = await buildContext( |
| 108 | + ctx, |
| 109 | + parsedRequest.tutorialData |
| 110 | + ); |
| 111 | + systemPrompt = await buildSystemPrompt(tutorialContext, ctx); |
| 112 | + } |
| 113 | + |
| 114 | + // Generate streaming response |
| 115 | + const result = await streamText({ |
| 116 | + model: openai("gpt-4o"), |
| 117 | + messages: messages.map((msg) => ({ |
| 118 | + role: msg.author === "USER" ? "user" : "assistant", |
| 119 | + content: msg.content, |
| 120 | + })), |
| 121 | + tools, |
| 122 | + maxSteps: 3, |
| 123 | + system: systemPrompt, |
| 124 | + }); |
| 125 | + |
| 126 | + // Create and return streaming response |
| 127 | + const stream = createStreamingProcessor(result, state, ctx); |
| 128 | + return resp.stream(stream, "text/event-stream"); |
| 129 | + } catch (error) { |
| 130 | + ctx.logger.error( |
| 131 | + "Agent request failed: %s", |
| 132 | + error instanceof Error ? error.message : String(error) |
| 133 | + ); |
| 134 | + return resp.json( |
| 135 | + { |
| 136 | + error: |
| 137 | + "Sorry, I encountered an error while processing your request. Please try again.", |
| 138 | + details: error instanceof Error ? error.message : String(error), |
| 139 | + }, |
| 140 | + { status: 500 } |
| 141 | + ); |
| 142 | + } |
| 143 | +} |
0 commit comments