PHP code example of navi-ai / php-sdk
1. Go to this page and download the library: Download navi-ai/php-sdk library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
navi-ai / php-sdk example snippets
avi\NaviClient;
// Initialize the client
$navi = new NaviClient('navi_sk_your_api_key', [
'base_url' => 'https://your-navi-instance.com'
]);
// Create a conversation
$conversation = $navi->conversations->create([
'agentId' => 'your-agent-uuid',
'contactId' => 'contact-123',
'title' => 'Support Request'
]);
// Send a message with streaming response
$navi->conversations->chat($conversation->id, 'Hello, I need help!', function($event) {
if ($event->isTextDelta()) {
echo $event->getText();
flush();
}
});
// Close the conversation when done
$navi->conversations->close($conversation->id);
$navi = new NaviClient('navi_sk_your_api_key', [
'base_url' => 'https://your-navi-instance.com', // Required
'api_path' => '/api/integration', // API path (default: /api/integration)
'timeout' => 30, // Request timeout in seconds
'verify_ssl' => true, // SSL verification
]);
$status = $navi->status();
echo $status->integrationName; // "My Integration"
echo $status->status; // "active"
echo $status->rateLimitPerMinute; // 60 or null
echo $status->defaultAgentId; // "agent-uuid" or null
$agents = $navi->agents->list([
'search' => 'support', // Optional: search by name
'limit' => 20, // Optional: max results (default: 50)
'offset' => 0 // Optional: pagination offset
]);
foreach ($agents as $agent) {
echo "{$agent->id}: {$agent->name}";
if ($agent->isDefault) {
echo " (default)";
}
echo "\n";
}
$agent = $navi->agents->get('agent-uuid');
echo $agent->name;
echo $agent->description;
echo $agent->isDefault ? 'Default agent' : 'Not default';
$conversation = $navi->conversations->create([
'agentId' => 'agent-uuid', // Required
'contactId' => 'contact-123', // Optional: identify the contact
'contactName' => 'John Doe', // Optional: display name
'contactMetadata' => [ // Optional: custom metadata (flat key-value pairs)
'customerId' => 'CUS-123',
'tier' => 'premium',
'region' => 'us-east'
],
'title' => 'Order Inquiry', // Optional: conversation title
'context' => [ // Optional: additional context
'orderId' => '12345',
'customerTier' => 'premium'
]
]);
echo $conversation->id; // Conversation UUID
echo $conversation->status; // "active"
$conversations = $navi->conversations->list([
'contactId' => 'contact-123', // Optional: filter by contact
'status' => 'active', // Optional: "active", "closed", "archived"
'limit' => 20, // Optional: max results (default: 50)
'offset' => 0 // Optional: pagination offset
]);
foreach ($conversations as $conv) {
echo "{$conv->id}: {$conv->title}\n";
}
$conversation = $navi->conversations->get('conversation-uuid');
echo $conversation->title;
echo $conversation->status;
echo $conversation->messageCount;
// Messages are
$conversation = $navi->conversations->get('conversation-uuid', [
'contactId' => 'contact-123' // Only return if conversation belongs to this contact
]);
$conversation = $navi->conversations->update('conversation-uuid', [
'title' => 'Updated Title'
]);
echo $conversation->title; // "Updated Title"
$conversation = $navi->conversations->update('conversation-uuid',
['title' => 'New Title'],
['contactId' => 'contact-123'] // Only update if conversation belongs to this contact
);
$page = $navi->conversations->messages('conversation-uuid', [
'contactId' => 'contact-123', // Optional: filter by contact for authorization
'limit' => 20,
'offset' => 0,
'order' => 'desc' // 'asc' (oldest first) or 'desc' (newest first)
]);
foreach ($page->messages as $message) {
echo "[{$message->role}]: {$message->content}\n";
}
echo "Total: {$page->total}";
echo "Has more: " . ($page->hasMore ? 'yes' : 'no');
// Get next page
if ($page->hasMore) {
$nextPage = $navi->conversations->messages('conversation-uuid', [
'contactId' => 'contact-123',
'limit' => 20,
'offset' => $page->getNextOffset()
]);
}
$navi->conversations->close('conversation-uuid');
// With contact filtering for authorization
$navi->conversations->close('conversation-uuid', [
'contactId' => 'contact-123' // Only close if conversation belongs to this contact
]);
$navi->conversations->chat($conversationId, 'Hello!', function($event) {
match($event->type) {
'message_created' => null, // User message saved
'reasoning_delta' => null, // Agent thinking (optional to display)
'tool_start' => print("Using tool: {$event->getToolName()}...\n"),
'tool_complete' => print("Tool completed\n"),
'response_delta' => print($event->getText()),
'complete' => print("\n[Done]\n"),
'error' => print("Error: {$event->getError()}\n"),
default => null
};
});
$fullResponse = '';
foreach ($navi->conversations->chatStream($conversationId, 'Hello!') as $event) {
if ($event->type === 'response_delta') {
$fullResponse .= $event->getText();
echo $event->getText();
}
if ($event->isError()) {
throw new Exception($event->getError());
}
}
$response = $navi->conversations->chatSync($conversationId, 'Hello!');
if ($response->success) {
echo $response->content;
echo "Tokens used: {$response->tokensUsed}";
echo "Duration: {$response->durationMs}ms";
} else {
echo "Error: {$response->error}";
}
$navi->conversations->chat($conversationId, 'Hello!',
function($event) { /* ... */ },
[
'contactId' => 'contact-123', // Identifier for the contact
'contactName' => 'John Doe', // Display name (used for new contacts or updates)
'contactMetadata' => [ // Custom metadata (flat key-value pairs)
'customerId' => 'CUS-123',
'tier' => 'premium'
]
]
);
$navi->conversations->chat($conversationId, 'What is the status of my order?',
function($event) { /* ... */ },
[
'context' => [
'orderId' => '12345',
'orderStatus' => 'shipped',
'trackingNumber' => 'ABC123'
]
]
);
$navi->conversations->chat($conversationId, 'Get my account balance',
function($event) { /* ... */ },
[
'runtimeParams' => [
'user_token' => 'jwt-abc123xyz', // Used in: ${params.user_token}
'api_key' => 'sk-secret-key', // Used in: ${params.api_key}
'user_id' => 42, // Used in: ${params.user_id}
'organization_id' => 'org-123' // Used in: ${params.organization_id}
]
]
);
$navi->conversations->chat($conversationId, 'Check my order status',
function($event) {
if ($event->isTextDelta()) {
echo $event->getText();
}
},
[
'contactId' => $_SESSION['user_id'],
'contactName' => $_SESSION['user_name'],
'contactMetadata' => [
'customerId' => $_SESSION['customer_id'],
'tier' => $_SESSION['subscription_tier']
],
'context' => [
'orderId' => '12345'
],
'runtimeParams' => [
'user_token' => $_SESSION['user_token'],
'user_id' => $_SESSION['user_id']
]
]
);
use Navi\Exceptions\AuthenticationException;
use Navi\Exceptions\NotFoundException;
use Navi\Exceptions\RateLimitException;
use Navi\Exceptions\ValidationException;
use Navi\Exceptions\NaviException;
try {
$conversation = $navi->conversations->get('invalid-uuid');
} catch (AuthenticationException $e) {
// Invalid API key
echo "Auth error: " . $e->getMessage();
} catch (NotFoundException $e) {
// Resource not found
echo "Not found: " . $e->getMessage();
} catch (RateLimitException $e) {
// Rate limit exceeded
echo "Rate limited. Retry after: " . $e->getRetryAfter() . " seconds";
} catch (ValidationException $e) {
// Validation error
echo "Validation error: " . $e->getMessage();
print_r($e->getErrors());
} catch (NaviException $e) {
// Other API error
echo "Error: " . $e->getMessage();
echo "Status: " . $e->getStatusCode();
}
avi\NaviClient;
use Navi\Exceptions\NaviException;
$navi = new NaviClient('navi_sk_your_api_key', [
'base_url' => 'https://your-navi-instance.com'
]);
// Simulated contact session
$currentContactId = 'customer-456';
$currentContactName = 'Jane Smith';
try {
// Check API status
$status = $navi->status();
if (!$status->isActive()) {
die("Integration is disabled");
}
// Create or get existing conversation
$conversation = $navi->conversations->create([
'agentId' => $status->defaultAgentId ?? 'your-agent-uuid',
'contactId' => $currentContactId,
'contactName' => $currentContactName,
'title' => 'Product Inquiry'
]);
echo "Conversation started: {$conversation->id}\n\n";
// Chat loop
while (true) {
echo "You: ";
$input = trim(fgets(STDIN));
if ($input === 'quit' || $input === 'exit') {
break;
}
echo "Agent: ";
$navi->conversations->chat($conversation->id, $input,
function($event) {
if ($event->type === 'response_delta') {
echo $event->getText();
}
},
[
'contactId' => $currentContactId,
'contactName' => $currentContactName
]
);
echo "\n\n";
}
// Close conversation (with contact verification)
$navi->conversations->close($conversation->id, [
'contactId' => $currentContactId
]);
echo "Conversation closed.\n";
} catch (NaviException $e) {
echo "Error: " . $e->getMessage() . "\n";
exit(1);
}
bash
composer