aiChatRequest
Create a reusable AI Chat Request object that can be sent to any AI service provider. This is useful for building requests programmatically, managing conversations, or testing AI workflows.
Syntax
aiChatRequest(messages, params, options, headers)Parameters
messages
any
No
null
Initial message(s) to add. Can be a string, struct, array of messages, or AiMessage object
params
struct
No
{}
Request parameters for the AI provider (e.g., { temperature: 0.5, max_tokens: 100, model: "gpt-3.5-turbo" })
options
struct
No
{}
Request options (e.g., { provider: "openai", apiKey: "...", returnFormat: "single" })
headers
struct
No
{}
Custom HTTP headers to include with the request
Message Format
Messages can be:
String: Added as a user message
Struct: With
roleandcontentkeysArray: Array of message structs
AiMessage: Fluent message object
Options Structure
provider
string
(config)
The AI provider to use (openai, claude, etc.)
apiKey
string
(config/env)
API key for the provider
returnFormat
string
"single"
Response format: "single", "all", "raw", "json", "xml"
timeout
numeric
30
Request timeout in seconds
logResponse
boolean
false
Log the AI response
logRequest
boolean
false
Log the AI request
Returns
Returns an AiRequest object with fluent API for:
Adding messages:
addMessage(),addSystemMessage(),addUserMessage()Setting parameters:
setParams(),setOptions(),setHeaders()Inspecting:
getMessages(),getParams(),getOptions()Sending: Use with
aiService().invoke(request)oraiChat()equivalents
Examples
Basic Request Object
Request with Initial Message
Multi-Turn Conversation
Reusable Request Template
Different Providers
Custom Headers
Testing and Debugging
Working with AiMessage
Structured Output Request
Notes
📦 Reusability: Request objects are reusable - great for templates and testing
🔄 Immutability: Methods return the request object for fluent chaining
🎯 Provider Agnostic: Same request works with any provider by changing options
🔍 Debugging: Enable logging options to inspect request/response data
🎨 Flexibility: Build requests incrementally or clone and customize templates
🚀 Events: Fires
onAIRequestCreateevent for interceptor integration
Related Functions
aiChat()- Send chat requests synchronouslyaiChatAsync()- Send chat requests asynchronouslyaiChatStream()- Stream chat responsesaiMessage()- Build message structures fluentlyaiService()- Get AI service provider instances
Best Practices
✅ Use for complex workflows - When you need full control over request lifecycle
✅ Template common requests - Create base requests and clone for variations
✅ Separate concerns - Build requests separately from sending them
✅ Test without API calls - Inspect request structure before sending
✅ Add request tracking - Use custom headers for logging and debugging
❌ Don't overcomplicate simple cases - Use aiChat() directly for one-off requests
❌ Don't modify shared requests - Clone before customizing to avoid side effects
Last updated