테스트 사이트 - 개발 중인 베타 버전입니다

groq api 용량 부족할 때

· 9개월 전 · 1103 · 5

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

 

api들을 전송해주는 파일:

[code]

<?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();

}

?>

[/code]

 

설명서:

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

  1. 설치 및 초기 설정 [code] // api_provider.php 파일을 웹 서버에 업로드 // cache 디렉토리 권한 설정: chmod 755 cache [/code]
  2. API 키 설정 [code] private $config = [ 'access_key' => '원하는액세스키입력', // 이 값을 안전한 키로 변경 'api_keys' => [ '계정1의groq_api키', '계정2의groq_api키', '계정3의groq_api키' ] ]; [/code]
  3. 기존 코드 수정 방법 [code] // 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 ); [/code]

  1. cURL 구현 예시 [code] 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(); } [/code]

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

댓글 5개

3개 정도 개정을 파서 테스트 해봤는데 잘 작동하네요

*!*!!!** 이 코드는 참고용으로만 보시는게 좋을 듯 합니다. 이용약관 위반으로 차단당했거든요. ^^

8개월 전

좋은 레퍼런스 감사합니다 :) 

@박긍정 사용한 지 5분만에 모든 계정 차단당했었어요. 꼼수가 안통하는 것 같습니다.

8개월 전

@Tak2 헐 ㅜㅜ 정보 감사합니다.. 좋은하루되세요~!

게시글 목록

번호 제목
17927
17926
17922
17921
17915
17910
17907
17892
17888
17879
17878
17874
17873
17872
17871
17870
17869
17868
17866
17865
17864
17863
17862
17859
17856
17845
17835
17834
17826
17823