Yes, you can typically pass a user-owned API key to an AI SDK if the SDK exposes a method or parameter for setting the API key dynamically. In your example, if the SalesCoach class provides an apiKey() method, you can do:
$response = (new SalesCoach)
->prompt('Analyze this sales transcript...')
->apiKey('MyapiKey');
Just make sure not to hard-code user keys unless it's safe, and check the SDK docs to see if apiKey() sets it for each instance or globally. Security first—never expose user API keys to the frontend!
@madprabh The classes just read the API keys from configuration, so you would need to override those configuration values before invoking the agent (and provider) classes.
If this is some sort of multi-tenant application where tenants can bring their own API keys, then you could have some sort of middleware that sets the configuration values:
class ConfigureTenant
{
public function handle(Request $request, Closure $next)
{
// Resolve your tenant model instance however you need to...
$tenant = Tenant::resolve();
// Set tenant configuration values...
config([
'ai.providers.anthropic.key' => $tenant->anthropic_api_key,
'ai.providers.openai.key' => $tenant->openai_api_key,
]);
return $next($request);
}
}