groq api 용량 부족할 때 > 코딩 스토리

groq api 용량 부족할 때

본문

계정을 여러개 파서 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]

 

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

좋아요103 이 글을 좋아요하셨습니다
url 복사 카카오톡 공유 라인 공유 페이스북 공유 트위터 공유

카테고리 분류 학습 시스템 (총 0개 학습됨)

예측 카테고리: 지역-로컬 (랜덤 - 학습 데이터 없음)

이 분류가 맞나요? 학습시켜주세요!

등록된 댓글이 없습니다.

  • RSS
  • _  글쓰기 글쓰기
전체 87건
게시물 검색

접속자집계

오늘
1,241
어제
3,897
최대
42,418
전체
939,469