groq api 용량 부족할 때 > 개발자팁

개발자팁

개발과 관련된 유용한 정보를 공유하세요.
질문은 QA에서 해주시기 바랍니다.

groq api 용량 부족할 때 정보

기타 groq api 용량 부족할 때

본문

계정을 여러개 파서 api 여러개를 돌려가면서 사용할 수 있도록 했습니다. (클로드의 작품)

 

api들을 전송해주는 파일:


<?php
class APIKeyProvider {
    private $config = [
        'access_key' => '원하는액세스키입력',
        'api_keys' => [
            '계정1의groq_api키', 
            '계정2의groq_api키',
            '계정3의groq_api키'
        ]
    ];
    
    private $state_dir;
    private $state_file;
    
    public function __construct() {
        $this->state_dir = dirname(__FILE__) . '/cache';
        $this->state_file = $this->state_dir . '/api_key_state.json';
        $this->initStateFile();
    }
    
    private function initStateFile() {
        if (!file_exists($this->state_dir)) {
            mkdir($this->state_dir, 0755, true);
        }
        if (!file_exists($this->state_file)) {
            $this->saveState(0);
        }
    }
    
    private function loadState() {
        if (!is_readable($this->state_file)) {
            return 0;
        }
        $content = file_get_contents($this->state_file);
        return $content === false ? 0 : (int)$content;
    }
    
    private function saveState($current_index) {
        if (!is_writable($this->state_dir)) {
            error_log("Cache directory is not writable: " . $this->state_dir);
            return false;
        }
        return file_put_contents($this->state_file, $current_index);
    }
    
    private function validateAccessKey($provided_key) {
        return hash_equals($this->config['access_key'], $provided_key);
    }
    
    private function getNextKey() {
        $current_index = $this->loadState();
        $next_index = ($current_index + 1) % count($this->config['api_keys']);
        $this->saveState($next_index);
        return $this->config['api_keys'][$next_index];
    }
    
    public function handleRequest() {
        header('Content-Type: application/json');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET');
        
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit;
        }
        
        try {
            $access_key = $_GET['access_key'] ?? '';
            if (!$this->validateAccessKey($access_key)) {
                throw new Exception('Invalid access key');
            }
            
            $api_key = $this->getNextKey();
            if (!$api_key) {
                throw new Exception('Failed to get next API key');
            }
            
            $this->sendResponse(true, 'Success', ['api_key' => $api_key]);
        } catch (Exception $e) {
            $this->sendResponse(false, $e->getMessage());
        }
    }
    
    private function sendResponse($success, $message, $data = []) {
        echo json_encode([
            'success' => $success,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ]);
        exit;
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    $provider = new APIKeyProvider();
    $provider->handleRequest();
}
?>

 

설명서:

API 키 로테이션 시스템 사용 가이드입니다.

  1. 설치 및 초기 설정
     // api_provider.php 파일을 웹 서버에 업로드 // cache 디렉토리 권한 설정: chmod 755 cache 
  2. API 키 설정
     private $config = [ 'access_key' => '원하는액세스키입력', // 이 값을 안전한 키로 변경 'api_keys' => [ '계정1의groq_api키', '계정2의groq_api키', '계정3의groq_api키' ] ]; 
  3. 기존 코드 수정 방법
     // 1. API 키 가져오기 $api_key_url = "http://your-domain.com/api_provider.php?access_key=원하는액세스키입력"; $response = file_get_contents($api_key_url); $result = json_decode($response, true);
    
    
    if (!$result['success']) { die('API 키 획득 실패: ' . $result['message']); }
    // 2. 획득한 API 키로 Groq API 호출 $url = 'https://api.groq.com/openai/v1/chat/completions'; $api_key = $result['data']['api_key'];
    $data = array( 'model' => 'whisper-large-v3-turbo', 'messages' => array( array( 'role' => 'user', 'content' => "다음 게시글의 내용을 핵심적인 내용만 간단히 요약해주세요:\n\n제목: {$title}\n내용: {$content}" ) ), 'max_tokens' => 500, 'temperature' => 0.3 ); 
    1. cURL 구현 예시
       function getGroqResponse($title, $content) { // API 키 획득 $api_key_url = "http://your-domain.com/api_provider.php?access_key=원하는액세스키입력"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_key_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); if (!$result['success']) { throw new Exception('API 키 획득 실패: ' . $result['message']); } // Groq API 호출 $api_key = $result['data']['api_key']; $url = 'https://api.groq.com/openai/v1/chat/completions'; $data = array( 'model' => 'whisper-large-v3-turbo', 'messages' => array( array( 'role' => 'user', 'content' => "다음 게시글의 내용을 핵심적인 내용만 간단히 요약해주세요:\n\n제목: {$title}\n내용: {$content}" ) ), 'max_tokens' => 500, 'temperature' => 0.3 ); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key )); $response = curl_exec($ch); curl_close($ch); return json_decode($response, true); }
      
      
      // 사용 예시 try { $result = getGroqResponse("제목", "내용"); print_r($result); } catch (Exception $e) { echo "에러: " . $e->getMessage(); } 
추천
1

댓글 5개

전체 5,383
개발자팁 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT