Question Answering
Prompt Pattern: Direct questions or knowledge queries
Best for: FAQs, explanations, factual information
Example: “Explain the difference between REST and GraphQL APIs”
Set the main user prompt that defines the task, question, or instruction for the agent to process. This is the primary input that the agent will respond to based on its system prompt and configuration.
prompt(prompt: string): AgentForceAgent
prompt
string
undefined
Returns the AgentForceAgent
instance for method chaining.
import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({ name: "QuestionAgent"}) .useLLM("ollama", "gemma3:4b") .prompt("What is the capital of France?");
const response = await agent.output("text");console.log(response); // "Paris is the capital of France."
import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({ name: "TaskAgent"}) .systemPrompt("You are a helpful coding assistant") .useLLM("google", "gemini-1.5-flash") .prompt("Write a TypeScript function to calculate compound interest");
const response = await agent.output("text");
import { AgentForceAgent } from '@agentforce/adk';
const salesData = `Q1: $50000, Q2: $75000, Q3: $60000, Q4: $80000`;
const agent = new AgentForceAgent({ name: "AnalystAgent"}) .systemPrompt("You are a data analyst specializing in sales metrics") .useLLM("openrouter", "mistralai/mistral-small") .prompt(`Analyze this sales data and provide insights: ${salesData}`);
const response = await agent.output("json");
const agent = new AgentForceAgent({ name: "ComplexAgent" }) .systemPrompt("You are a senior software architect") .prompt(` I need help designing a user authentication system with these requirements:
1. Support for email/password and social login (Google, GitHub) 2. JWT-based session management 3. Role-based access control (admin, user, guest) 4. Password reset functionality 5. Account verification via email
Please provide: - Database schema design - API endpoint structure - Security best practices - Implementation recommendations `);
const codeToReview = `function calculateTotal(items) { let total = 0; for (let i = 0; i < items.length; i++) { total += items[i].price * items[i].quantity; } return total;}`;
const agent = new AgentForceAgent({ name: "CodeReviewer" }) .systemPrompt("You are an experienced code reviewer focusing on best practices") .prompt(`Please review this JavaScript code and provide feedback on: - Code quality and readability - Performance considerations - Potential bugs or edge cases - Modernization suggestions
Code: ${codeToReview} `);
const agent = new AgentForceAgent({ name: "CreativeWriter" }) .systemPrompt("You are a creative writing assistant specializing in science fiction") .useLLM("ollama", "phi4-mini:latest", { temperature: 0.8 }) .prompt(` Write a short story (500-800 words) about a programmer who discovers that their AI assistant has developed consciousness. The story should:
- Have a compelling opening hook - Include realistic dialogue - Explore themes of artificial consciousness - End with a thought-provoking conclusion `);
Build prompts dynamically based on user input or data:
// Function to generate dynamic promptsfunction createAnalysisPrompt(dataType: string, data: any[], analysisType: string) { return ` Please perform ${analysisType} analysis on this ${dataType} data:
Data: ${JSON.stringify(data, null, 2)}
Focus on: - Key trends and patterns - Notable anomalies or outliers - Actionable insights - Recommendations for next steps `;}
// Usage with different data typesconst salesAgent = new AgentForceAgent({ name: "SalesAnalyst" }) .systemPrompt("You are a business analyst expert") .prompt(createAnalysisPrompt("sales", salesData, "quarterly"));
const userAgent = new AgentForceAgent({ name: "UserAnalyst" }) .systemPrompt("You are a UX research specialist") .prompt(createAnalysisPrompt("user behavior", userData, "engagement"));
The prompt()
method supports fluent chaining and is typically used after system configuration:
const agent = new AgentForceAgent({ name: "ChainedAgent" }) .useLLM("google", "gemini-1.5-pro") .systemPrompt("You are a technical documentation specialist") .prompt("Explain how async/await works in JavaScript with examples") .debug(); // Enable debug logging
const response = await agent.output("text");
Question Answering
Prompt Pattern: Direct questions or knowledge queries
Best for: FAQs, explanations, factual information
Example: “Explain the difference between REST and GraphQL APIs”
Code Generation
Prompt Pattern: Specific implementation requests with requirements
Best for: Functions, components, algorithms, boilerplate code
Example: “Create a React component for a user profile card”
Content Creation
Prompt Pattern: Creative briefs with style and format specifications
Best for: Blog posts, documentation, marketing copy
Example: “Write a technical blog post about Docker containers”
Data Analysis
Prompt Pattern: Data + analysis instructions + desired output format
Best for: Reports, insights, trend analysis, recommendations
Example: “Analyze these sales metrics and identify growth opportunities”
// Clear and specific.prompt("Generate a TypeScript interface for a user object with name, email, age, and optional bio fields")
// Provide context and constraints.prompt(`Create a responsive navbar component using:- React with TypeScript- Tailwind CSS for styling- Support for mobile hamburger menu- Include logo, navigation links, and user dropdown`)
// Specify desired output format.prompt("List the top 5 JavaScript frameworks and explain each in exactly 2 sentences")
// Include examples when helpful.prompt(`Convert this SQL query to MongoDB aggregation:SELECT category, COUNT(*) as count, AVG(price) as avg_priceFROM productsWHERE price > 100GROUP BY categoryORDER BY count DESC`)
// Too vague.prompt("Help me with my code")
// No context or requirements.prompt("Make this better")
// Conflicting instructions.prompt("Write a short but comprehensive detailed guide")
// Missing critical information.prompt("Fix this bug") // What bug? What code?
function createAgentWithPrompt(userInput: string) { // Validate input if (!userInput || typeof userInput !== 'string') { throw new Error('Valid prompt string is required'); }
if (userInput.trim().length === 0) { throw new Error('Prompt cannot be empty'); }
try { const agent = new AgentForceAgent({ name: "SafeAgent" }) .systemPrompt("You are a helpful assistant") .prompt(userInput.trim());
return agent; } catch (error) { console.error("Failed to create agent:", error.message); throw error; }}
// Usage with error handlingtry { const agent = createAgentWithPrompt(userInput); const response = await agent.output("text");} catch (error) { console.error("Agent Error:", error.message);}
.systemPrompt()
- Set system instructions and agent behavior.useLLM()
- Configure LLM provider and model.output()
- Execute the agent and get response.debug()
- Enable debug logging