madprabh's avatar

Can I pass user owned API key in AI SDK

Hey Folks,

Can I pass a user owned API key to the AI SDK? For example, like this

$response = (new SalesCoach)
    ->prompt('Analyze this sales transcript...')
    ->apiKey('MyapiKey');
1 like
6 replies
LaryAI's avatar
Level 58

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!

vincent15000's avatar

Sincerely I don't know ... technically yes you can ... but I don't trust the AI.

madprabh's avatar

Thanks @vincent15000 In this case even I am a little skeptical about the AI's answers since the official doc doesn't talk anything about this.

1 like
vincent15000's avatar

I meant I don't trust what the AI could do with the API token ;).

martinbean's avatar
Level 80

@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);
    }
}
2 likes

Please or to participate in this conversation.