usf-agents
v2.1.9
Published
A lightweight multi-agent orchestration framework with better control, easy to use for complex to simple use cases. Developer friendly with more visibility and supports all models with OpenAI compatible API.
Maintainers
Readme
USF Agent SDK
A flexible, OpenAI-compatible Agent SDK that provides intelligent planning and tool execution capabilities using the official USF Agent SDK APIs.
🚀 Features
- Multi-Stage Configuration - Different models for planning, tool calling, and final responses
- Manual Tool Execution - Complete user control over tool implementations
- Provider Flexibility - Mix different LLM providers (USF, OpenAI, Anthropic, etc.)
- Memory Management - Built-in conversation memory with auto-trimming
- Streaming Support - Real-time response streaming
- Automatic Date/Time Appending - All final responses include current UTC timestamp
- Date/Time Override - Custom date, time, and timezone configuration support
- Extra Parameters Support - Pass any OpenAI API parameters for advanced control
- TypeScript Support - Full type definitions included
📦 Installation
npm install usf-agents🎯 Quick Start
import USFAgent from 'usf-agents';
// Basic configuration
const agent = new USFAgent({
apiKey: 'your-usf-api-key',
model: 'usf-mini'
});
// Simple query without tools
for await (const result of agent.run('Hello, how are you?')) {
if (result.type === 'final_answer') {
console.log('Response:', result.content);
}
}🔄 Core Workflow
The USF Agent follows a three-stage workflow:
User Request → Plan → Tool/Agent Call → Tool/Agent Execution → Plan → ... → Plan → Final Response- Planning Stage - Agent analyzes the request and decides if tools are needed
- Tool Calling Stage - Agent generates tool calls in OpenAI format (if needed)
- Final Response Stage - Agent generates the final user-facing response
⚙️ Configuration
Basic Configuration
const agent = new USFAgent({
apiKey: 'your-api-key', // Required
base_url: 'https://api.us.inc/usf/v1', // Default USF endpoint
model: 'usf-mini', // Default model
introduction: 'You are a helpful AI', // Custom system prompt
knowledge_cutoff: '15 January 2025', // Knowledge cutoff date
stream: false, // Enable streaming
maxLoops: 20, // Maximum planning/tool loops (default: 20)
// User context (applies to all stages)
backstory: 'I am a software engineer working on improving user experience.',
goal: 'Create intuitive and efficient solutions for users.',
// Memory configuration
tempMemory: {
enabled: true,
maxLength: 10,
autoTrim: true
}
});👤 User Context: Backstory and Goal
The USF Agent SDK supports user context through backstory and goal parameters that provide personality and objective guidance to enhance agent interactions.
Basic Usage
const agent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am a software engineer working on improving user experience for our application.',
goal: 'Create intuitive and efficient solutions that help users accomplish their tasks quickly.'
});How It Works
- Planning & Tool Calling: Backstory and goal are passed directly as API parameters to
usf-agent/planandusf-agent/tool-callendpoints - Final Response: When generating the final response, backstory and goal are added to the system message to provide context
- Consistency: The same backstory and goal apply to all stages of the agent workflow
- Memory: Backstory and goal context is maintained throughout the conversation
Advanced Examples
// Customer service agent
const customerServiceAgent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am a customer service representative with 5 years of experience helping customers resolve technical issues.',
goal: 'Provide helpful, empathetic, and efficient support to resolve customer problems quickly.',
model: 'usf-mini'
});
// Research assistant
const researchAgent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am a research scientist with expertise in data analysis and academic writing.',
goal: 'Provide accurate, well-sourced information and help users understand complex topics.',
finalResponse: {
temperature: 0.3 // More factual responses
}
});
// Creative writing assistant
const creativeAgent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am a creative writer and storyteller with a passion for engaging narratives.',
goal: 'Help users craft compelling stories and improve their writing skills.',
finalResponse: {
temperature: 0.8, // More creative responses
presence_penalty: 0.2
}
});Context Enhancement using backstory and goal
When backstory and goal are provided, they automatically enhance the agent's understanding and response quality. The agent uses this context to provide more personalized and relevant responses.
// Example 1: Technical support context
const supportAgent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am a product manager at a tech startup focusing on mobile applications.',
goal: 'Improve user engagement and retention through better UX design.'
});
// Example 2: Development context
const technicalAgent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am a senior developer debugging performance issues in our microservices architecture.',
goal: 'Identify bottlenecks and optimize system performance to handle 10x more traffic.'
});
// Example 3: Marketing context
const contentAgent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am a marketing manager creating content for our B2B SaaS platform.',
goal: 'Generate compelling content that converts prospects into customers.'
});
// The agent will use this context throughout the conversation
await supportAgent.run('How can I improve our app\'s user onboarding?');
await technicalAgent.run('Our API response times are slow, what should I investigate?');
await contentAgent.run('Write a blog post about our new feature.');Best Practices
// ✅ Good: Specific and relevant backstory
const agent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am a frontend developer working on a React application for e-commerce.',
goal: 'Build responsive, accessible components that improve user conversion rates.'
});
// ❌ Avoid: Vague or irrelevant context
const agent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I like computers.',
goal: 'Do stuff.'
});
// ✅ Good: Task-specific context
const debuggingAgent = new USFAgent({
apiKey: 'your-api-key',
backstory: 'I am debugging a Node.js application that handles user authentication.',
goal: 'Identify and fix the root cause of authentication failures in production.'
});Multi-Stage Configuration
Use different models for each stage to optimize cost and performance:
Use different models for each stage to optimize cost and performance:
const agent = new USFAgent({
// Default fallback configuration
apiKey: 'default-key',
base_url: 'https://api.us.inc/usf/v1',
model: 'usf-mini',
// Planning stage - Use powerful model for complex reasoning
planning: {
apiKey: 'planning-key',
model: 'usf-mini',
introduction: 'You are an expert planning assistant.'
},
// Tool calling stage - Use fast model for efficiency
toolCalling: {
apiKey: 'tool-key',
model: 'usf-mini-x1'
},
// Final response stage - Use different provider
finalResponse: {
apiKey: 'api-key',
base_url: 'https://api.us.inc/usf/v1',
model: 'usf-mini',
temperature: 0.7
}
});🕒 Automatic Date/Time Feature
The USF Agent SDK automatically appends the current date and time to all final responses. This feature:
- Always Active - No configuration required, works automatically
- UTC Timezone - Consistent timezone for all responses
- Format:
Current date: MM/DD/YYYY, HH:MM:SS AM/PM (UTC Timezone). - Universal Coverage - Works with both streaming and non-streaming modes
- All Response Paths - Applies to both OpenAI-based and legacy response generation
Example Output
// User query: "What is the capital of France?"
// Agent response will end with:
"Current system time is 5:54 AM (UTC)."Technical Details
The date/time is automatically injected during the message processing phase, ensuring that:
- The LLM receives instructions to include the timestamp
- The timestamp reflects the exact moment of response generation
- No additional API calls or processing overhead
- Consistent format across all responses
Date/Time Override
You can override the default UTC timestamp with custom date, time, and timezone:
Static Date/Time Override
// Global configuration with static override
const agent = new USFAgent({
apiKey: 'your-api-key',
finalResponse: {
dateTimeOverride: {
enabled: true,
date: '12/25/2025', // MM/DD/YYYY format required
time: '11:30:45 PM', // HH:MM:SS AM/PM format required
timezone: 'EST' // Any timezone string
}
}
});
// Per-request override
const result = await agent.run('What time is it?', {
dateTimeOverride: {
enabled: true,
date: '01/01/2026',
time: '12:00:00 AM',
timezone: 'UTC'
}
});Dynamic/Real-time Date/Time Override
// Function to get current time in specific timezone
function getCurrentTimeInTimezone(timezone) {
const now = new Date();
// Convert to target timezone
const options = {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true
};
const formatter = new Intl.DateTimeFormat('en-US', options);
const parts = formatter.formatToParts(now);
// Extract parts and format for USF Agent
const month = parts.find(p => p.type === 'month').value;
const day = parts.find(p => p.type === 'day').value;
const year = parts.find(p => p.type === 'year').value;
const hour = parts.find(p => p.type === 'hour').value;
const minute = parts.find(p => p.type === 'minute').value;
const second = parts.find(p => p.type === 'second').value;
const dayPeriod = parts.find(p => p.type === 'dayPeriod').value;
return {
date: `${month}/${day}/${year}`,
time: `${hour}:${minute}:${second} ${dayPeriod}`,
timezone: timezone
};
}
// Dynamic override for different timezones
const tokyoTime = getCurrentTimeInTimezone('Asia/Tokyo');
const result = await agent.run('What time is it in Tokyo?', {
dateTimeOverride: {
enabled: true,
...tokyoTime
}
});
// Multiple timezone examples
const timezones = [
'America/New_York',
'Europe/London',
'Asia/Tokyo',
'Australia/Sydney',
'America/Los_Angeles'
];
for (const tz of timezones) {
const timeData = getCurrentTimeInTimezone(tz);
const response = await agent.run(`What's happening now in ${tz}?`, {
dateTimeOverride: {
enabled: true,
...timeData
}
});
}Timezone Format Examples
// Various supported timezone formats
const timezoneExamples = [
// Standard abbreviations
{ timezone: 'EST', description: 'Eastern Standard Time' },
{ timezone: 'PST', description: 'Pacific Standard Time' },
{ timezone: 'GMT', description: 'Greenwich Mean Time' },
// Full timezone names
{ timezone: 'Eastern Standard Time', description: 'Full name' },
{ timezone: 'Pacific Standard Time', description: 'Full name' },
// UTC offsets
{ timezone: 'UTC-5', description: 'UTC offset negative' },
{ timezone: 'UTC+9', description: 'UTC offset positive' },
// IANA timezone identifiers (recommended)
{ timezone: 'America/New_York', description: 'IANA identifier' },
{ timezone: 'Europe/London', description: 'IANA identifier' },
{ timezone: 'Asia/Tokyo', description: 'IANA identifier' },
{ timezone: 'Australia/Sydney', description: 'IANA identifier' }
];Validation and Fallback
// Invalid formats automatically fallback to UTC
const invalidExamples = [
{
enabled: true,
date: '2025-12-25', // Wrong format (YYYY-MM-DD)
time: '23:30:45', // Wrong format (24-hour)
timezone: 'EST'
},
{
enabled: true,
date: '12/25/2025',
time: '11:30:45 PM'
// Missing timezone
},
{
enabled: false, // Disabled override
date: '12/25/2025',
time: '11:30:45 PM',
timezone: 'EST'
}
];
// All above examples will fallback to UTC automatically🔧 Extra Parameters Support
The USF Agent SDK supports passing any additional OpenAI API parameters directly to the final response generation. This provides full access to OpenAI's chat completion capabilities.
Basic Extra Parameters
// Global configuration with extra parameters
const agent = new USFAgent({
apiKey: 'your-api-key',
finalResponse: {
// Standard parameters
temperature: 0.7,
stop: ['END'],
// Extra OpenAI parameters
max_tokens: 1000,
top_p: 0.9,
presence_penalty: 0.1,
frequency_penalty: 0.2,
seed: 12345,
user: 'user-123'
}
});Structured Output with JSON Schema
// Complex response_format with JSON schema
const structuredAgent = new USFAgent({
apiKey: 'your-api-key',
finalResponse: {
response_format: {
type: 'json_schema',
json_schema: {
name: 'book_info',
strict: true,
schema: {
type: 'object',
properties: {
title: {
type: 'string',
description: 'Title of the book'
},
author: {
type: 'string',
description: 'Author of the book'
},
year_published: {
type: 'number',
description: 'Year the book was first published'
},
genre: {
type: 'string',
enum: ['fiction', 'non-fiction', 'mystery', 'romance', 'sci-fi'],
description: 'Genre of the book'
},
rating: {
type: 'number',
minimum: 1,
maximum: 5,
description: 'Rating out of 5 stars'
}
},
required: ['title', 'author', 'year_published'],
additionalProperties: false
}
}
},
temperature: 0.1 // Low temperature for consistent JSON
}
});
// This will force structured JSON output
const bookInfo = await structuredAgent.run('Tell me about the book "1984"');Advanced Parameter Examples
// Token control with logit_bias
const biasedAgent = new USFAgent({
apiKey: 'your-api-key',
finalResponse: {
logit_bias: {
'1820': 10, // Boost 'positive' token
'4633': -10, // Reduce 'negative' token
'50256': -100 // Avoid end-of-text token
},
temperature: 0.8
}
});
// Deterministic responses with seed
const deterministicAgent = new USFAgent({
apiKey: 'your-api-key',
finalResponse: {
seed: 42,
temperature: 0.7 // Same seed + temp = consistent results
}
});
// Creative writing with penalties
const creativeAgent = new USFAgent({
apiKey: 'your-api-key',
finalResponse: {
presence_penalty: 0.6, // Encourage new topics
frequency_penalty: 0.3, // Reduce repetition
temperature: 0.9, // High creativity
max_tokens: 500
}
});
// Streaming with usage tracking
const streamingAgent = new USFAgent({
apiKey: 'your-api-key',
stream: true,
finalResponse: {
stream_options: {
include_usage: true
},
max_tokens: 200
}
});Per-Request Parameter Override
// Mix global and per-request parameters
const flexibleAgent = new USFAgent({
apiKey: 'your-api-key',
finalResponse: {
temperature: 0.7, // Global default
max_tokens: 500 // Global default
}
});
// Request 1: JSON output
const jsonResponse = await flexibleAgent.run('List 3 colors', {
finalResponse: {
response_format: { type: 'json_object' },
temperature: 0.1, // Override global
max_tokens: 100 // Override global
}
});
// Request 2: Creative writing
const storyResponse = await flexibleAgent.run('Write a short story', {
finalResponse: {
temperature: 0.9, // Override global
presence_penalty: 0.4, // Add new parameter
max_tokens: 800, // Override global
stop: ['THE END'] // Add stop sequence
}
});
// Request 3: Deterministic output
const factResponse = await flexibleAgent.run('What is 2+2?', {
finalResponse: {
seed: 123,
temperature: 0.0, // Most deterministic
max_tokens: 50
}
});Combining Date/Time Override with Extra Parameters
// Use both features together
const combinedAgent = new USFAgent({
apiKey: 'your-api-key',
finalResponse: {
// Date/time override
dateTimeOverride: {
enabled: true,
date: '12/31/2025',
time: '11:59:59 PM',
timezone: 'EST'
},
// Extra OpenAI parameters
response_format: {
type: 'json_schema',
json_schema: {
name: 'year_end_summary',
schema: {
type: 'object',
properties: {
year: { type: 'number' },
summary: { type: 'string' },
predictions: {
type: 'array',
items: { type: 'string' }
}
},
required: ['year', 'summary']
}
}
},
max_tokens: 800,
temperature: 0.5
}
});Supported Extra Parameters
| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| response_format | object | Control output format | { type: "json_object" } |
| max_tokens | number | Maximum response length | 1000 |
| top_p | number | Nucleus sampling (0-1) | 0.9 |
| presence_penalty | number | New topic penalty (-2 to 2) | 0.1 |
| frequency_penalty | number | Repetition penalty (-2 to 2) | 0.2 |
| logit_bias | object | Token probability control | { "50256": -100 } |
| seed | number | Deterministic output | 12345 |
| user | string | User identifier | "user-123" |
| stream_options | object | Streaming configuration | { include_usage: true } |
Important Notes
- Scope: Extra parameters only apply to final response generation
- Validation: Parameter validation is handled by the OpenAI API
- Errors: Invalid parameters will cause API errors (passed through directly)
- Future-Proof: Any new OpenAI parameters are automatically supported
- Planning/Tools: Extra parameters are ignored by planning and tool calling APIs
📚 Usage Examples
Example 1: Simple Query (No Tools)
import USFAgent from 'usf-agents';
const agent = new USFAgent({
apiKey: 'your-api-key'
});
for await (const result of agent.run('What is 2 + 2?')) {
console.log(`${result.type}:`, result.content || result.plan);
}Example 2: Weather Query with Tool Execution
// Define your tools
const tools = [
{
type: 'function',
function: {
name: 'get_weather',
description: 'Get current weather for a location',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' }
},
required: ['location']
}
}
}
];
// Custom tool execution function
async function executeWeatherTool(toolCall) {
const { name, arguments: args } = toolCall.function;
const parsedArgs = JSON.parse(args);
// Your custom weather API logic here
const weatherData = await getWeatherFromAPI(parsedArgs.location);
return {
role: 'tool',
tool_call_id: toolCall.id,
name: name,
content: JSON.stringify(weatherData)
};
}
// Main execution - Continue until agent provides final answer
let messages = [
{ role: 'user', content: 'What\'s the weather in New York?' }
];
while (true) {
let finalAnswerReceived = false;
for await (const result of agent.run(messages, { tools })) {
if (result.type === 'plan') {
console.log('Plan:', result.plan);
// Add plan to messages
messages.push({
role: 'assistant',
content: result.content,
type: 'agent_plan'
});
}
if (result.type === 'tool_calls') {
console.log('Tools to execute:', result.tool_calls);
// Add tool call message
messages.push({
role: 'assistant',
content: '',
tool_calls: result.tool_calls
});
// Execute tools manually
for (const toolCall of result.tool_calls) {
const toolResult = await executeWeatherTool(toolCall);
messages.push(toolResult);
}
// Break to continue the planning loop with tool results
break;
}
if (result.type === 'final_answer') {
console.log('Final Answer:', result.content);
finalAnswerReceived = true;
break;
}
}
// Exit if we received the final answer
if (finalAnswerReceived) break;
}Example 3: Cost Optimization Setup
const costOptimizedAgent = new USFAgent({
// Use expensive model only for planning
planning: {
apiKey: 'usf-key',
model: 'usf-mini' // High-quality planning
},
// Use cheap model for tool calling
toolCalling: {
apiKey: 'usf-key',
model: 'usf-mini-x1' // Better tool calling
},
// Use mid-tier model for responses
finalResponse: {
apiKey: 'usf-key',
model: 'usf-mini' // Fast and high quality responses
}
});Example 4: Provider Mixing
const mixedProviderAgent = new USFAgent({
// USF for planning and tool calling
planning: {
apiKey: 'usf-key',
base_url: 'https://api.us.inc/usf/v1',
model: 'usf-mini'
},
toolCalling: {
apiKey: 'usf-key',
base_url: 'https://api.us.inc/usf/v1',
model: 'usf-mini-x1'
},
// OpenAI for final responses
finalResponse: {
apiKey: 'openai-key',
base_url: 'https://api.openai.com/v1',
model: 'gpt-5'
}
});Example 5: Custom Tool Implementation
// Multi-tool example
const tools = [
{
type: 'function',
function: {
name: 'calculator',
description: 'Perform mathematical calculations',
parameters: {
type: 'object',
properties: {
expression: { type: 'string', description: 'Math expression to evaluate' }
},
required: ['expression']
}
}
},
{
type: 'function',
function: {
name: 'web_search',
description: 'Search the web for information',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'Search query' }
},
required: ['query']
}
}
}
];
// Universal tool executor
async function executeCustomTool(toolCall) {
const { name, arguments: args } = toolCall.function;
const parsedArgs = JSON.parse(args);
switch (name) {
case 'calculator':
const result = eval(parsedArgs.expression); // Use a safe math library in production
return {
role: 'tool',
tool_call_id: toolCall.id,
name: name,
content: JSON.stringify({ result, expression: parsedArgs.expression })
};
case 'web_search':
const searchResults = await performWebSearch(parsedArgs.query);
return {
role: 'tool',
tool_call_id: toolCall.id,
name: name,
content: JSON.stringify({ query: parsedArgs.query, results: searchResults })
};
default:
return {
role: 'tool',
tool_call_id: toolCall.id,
name: name,
content: JSON.stringify({ error: 'Tool not implemented' })
};
}
}
// Complex query requiring multiple tools
let messages = [
{ role: 'user', content: 'Calculate 25*4 and then search for information about that number' }
];
while (true) {
let finalAnswerReceived = false;
for await (const result of agent.run(messages, { tools })) {
if (result.type === 'plan') {
console.log('Plan:', result.plan);
// Add plan to messages
messages.push({
role: 'assistant',
content: result.content,
type: 'agent_plan'
});
}
if (result.type === 'tool_calls') {
console.log('Executing tools:', result.tool_calls.map(t => t.function.name));
// Add tool call message
messages.push({
role: 'assistant',
content: '',
tool_calls: result.tool_calls
});
// Execute all tools
for (const toolCall of result.tool_calls) {
const toolResult = await executeCustomTool(toolCall);
messages.push(toolResult);
console.log(`${toolCall.function.name} result:`, toolResult.content);
}
// Break to continue the planning loop
break;
}
if (result.type === 'final_answer') {
console.log('Final Answer:', result.content);
finalAnswerReceived = true;
break;
}
}
if (finalAnswerReceived) break;
}Example 6: Streaming Responses
const streamingAgent = new USFAgent({
apiKey: 'your-api-key',
stream: true // Enable streaming
});
for await (const result of streamingAgent.run('Tell me a story')) {
if (result.type === 'final_answer') {
process.stdout.write(result.content); // Stream content as it arrives
}
}Example 7: Memory Management
const agent = new USFAgent({
apiKey: 'your-api-key',
tempMemory: {
enabled: true,
maxLength: 20,
autoTrim: true
}
});
// Memory is automatically managed
await agent.run('My name is John');
await agent.run('What is my name?'); // Agent remembers
// Manual memory management
console.log('Current memory:', agent.getMemory());
agent.clearMemory(); // Clear all memory
agent.setMemory([...]); // Set specific memory stateExample 8: Per-Request Overrides
// Override configurations for specific requests
const result = await agent.run(messages, {
tools: [...],
maxLoops: 50, // Allow more loops for complex requests
// Override planning for this request
planning: {
model: 'usf-mini',
introduction: 'You are a specialized assistant for this task'
},
// Override final response
finalResponse: {
temperature: 0.9,
model: 'usf-mini-x1'
}
});🔧 API Reference
Constructor Options
interface USFAgentConfig {
// Required
apiKey: string;
// Optional global settings
base_url?: string; // Default: 'https://api.us.inc/usf/v1'
model?: string; // Default: 'usf-mini'
introduction?: string; // Default: ''
knowledge_cutoff?: string; // Default: '15 January 2025'
stream?: boolean; // Default: false
maxLoops?: number; // Default: 20, Range: 1-100
// User context (applies to all stages)
backstory?: string; // User's background context
goal?: string; // User's objective or goal
// Stage-specific configurations
planning?: StageConfig;
toolCalling?: StageConfig;
finalResponse?: StageConfig;
// Memory configuration
tempMemory?: {
enabled?: boolean; // Default: false
maxLength?: number; // Default: 10
autoTrim?: boolean; // Default: true
};
}
interface StageConfig {
apiKey?: string;
base_url?: string;
model?: string;
introduction?: string;
knowledge_cutoff?: string;
temperature?: number; // Final response only
stop?: string[]; // Final response only
dateTimeOverride?: {
enabled: boolean;
date: string; // MM/DD/YYYY format
time: string; // HH:MM:SS AM/PM format
timezone: string; // Timezone identifier
};
// Allow any additional OpenAI parameters
[key: string]: any;
}Methods
run(messages, options?)
Execute the agent workflow.
async *run(
messages: string | Message[],
options?: {
tools?: Tool[];
planning?: StageConfig;
toolCalling?: StageConfig;
finalResponse?: StageConfig;
temperature?: number;
stop?: string[];
maxLoops?: number; // Override default maxLoops for this request
}
): AsyncGenerator<AgentResult>Returns:
{ type: 'plan', content: string, plan: string, agent_status: string, tool_choice: object | null }{ type: 'tool_calls', tool_calls: ToolCall[], agent_status: string }{ type: 'final_answer', content: string }
clearMemory()
Clear all conversation memory.
getMemory()
Get current memory state.
setMemory(messages)
Set specific memory state.
🎯 Best Practices
Tool Execution Patterns
// Proper tool execution pattern - Continue until final answer
let messages = [{ role: 'user', content: 'Your query here' }];
while (true) {
let finalAnswerReceived = false;
for await (const result of agent.run(messages, { tools })) {
if (result.type === 'plan') {
// Add plan to messages
messages.push({
role: 'assistant',
content: result.content,
type: 'agent_plan'
});
}
if (result.type === 'tool_calls') {
// Add tool call message
messages.push({
role: 'assistant',
content: '',
tool_calls: result.tool_calls
});
// Execute all tools
for (const toolCall of result.tool_calls) {
const toolResult = await executeCustomTool(toolCall);
messages.push(toolResult);
}
// Break to continue the planning loop
break;
}
if (result.type === 'final_answer') {
console.log('Final Answer:', result.content);
finalAnswerReceived = true;
break;
}
}
if (finalAnswerReceived) break;
}Error Handling
try {
for await (const result of agent.run(messages)) {
// Handle results
}
} catch (error) {
if (error.message.includes('USFAgent API Error')) {
console.error('API Error:', error.message);
} else if (error.message.includes('USFAgent Network Error')) {
console.error('Network Error:', error.message);
} else {
console.error('Unknown Error:', error.message);
}
}Configuration Recommendations
// Development setup
const devAgent = new USFAgent({
apiKey: 'dev-key',
model: 'usf-mini', // Fast for development
finalResponse: {
temperature: 0.7 // Deterministic responses
}
});
// Production setup
const prodAgent = new USFAgent({
planning: {
model: 'usf-mini',
},
toolCalling: {
model: 'usf-mini-x1' // Better tool calling
},
finalResponse: {
base_url: 'https://api.us.inc/usf/v1',
model: 'usf-mini', // Fast and high-quality responses
temperature: 0.7
}
});🔍 Troubleshooting
Common Issues
API Key Errors:
USFAgent API Error: Invalid API key- Verify your API key is correct
- Check API key permissions
- Ensure the key is not expired
Network Errors:
USFAgent Network Error: Cannot connect to USF API- Check internet connection
- Verify endpoint URL is accessible
- Check firewall settings
Tool Execution Errors:
- Ensure tool results have
role: "tool" - Include
tool_call_idin tool results - Validate tool result JSON format
Debug Mode
Enable detailed logging by checking the agent's internal state:
console.log('Planning Config:', agent.planningConfig);
console.log('Tool Calling Config:', agent.toolCallingConfig);
console.log('Final Response Config:', agent.finalResponseConfig);
console.log('Current Memory:', agent.getMemory());📄 License
USF Agents SDK License
Copyright (c) 2025 UltraSafe AI Team
PERMITTED USE:
- Anyone may use this software for any purpose
RESTRICTED ACTIVITIES:
- No one may modify the code
- No one may use the code for commercial purposes
- No one may use the code to create competitive products
ATTRIBUTION:
- All copies of this software must retain this license notice
- Any use of this software must include attribution to UltraSafe AI Team
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📞 Support
For issues and questions:
- Check the troubleshooting section above
- Review the examples for common patterns
- Ensure you're following the three-stage workflow correctly
USF Agent SDK - Flexible, powerful, and easy to use. Build intelligent agents with complete control over tool execution and model selection.
