Hướng dẫn sử dụng

Bước 1: Cài đặt Thư viện

Đầu tiên, bạn cần cài đặt thư viện openai nếu chưa có. Bạn có thể cài đặt nó bằng cách sử dụng pip:

pip install openai

Bước 2: Viết Mã Python

Sử dụng đoạn mã Python sau để gửi yêu cầu đến API của shop:


import openai
# Cập nhật base_url để trỏ đến https://api.keyai.shop/v1 thay vì https://api.openai.com/v1
client = openai.OpenAI(api_key="điền key trong đơn hàng vào đây", base_url="https://api.keyai.shop/v1")

response = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {
        "role": "user",
        "content": "hello"
    }
  ]
)

print(response)

Hoặc sử dụng thư viện request:

Đầu tiên, bạn cần cài đặt thư viện requests nếu chưa có. Bạn có thể cài đặt nó bằng cách sử dụng pip:

pip install requests

import requests
import json
headers = {
    'Authorization': 'Bearer thêm_key_api_của_bạn_vào_đây',
    'Content-Type': 'application/json'
}
data = {
    'model': 'gpt-4o-mini',
    'messages': [
        {'role': 'user', 'content': 'Giới thiệu về công nghệ AI.'}
    ],
    "stream": True
}
with requests.post('https://api.keyai.shop/v1/chat/completions', headers=headers, json=data, stream=True) as response:
    for line in response.iter_lines():
        if line:
            decoded_line = line.decode('utf-8')
            if decoded_line == 'data: [DONE]':
                break
            if decoded_line.startswith('data: '):
                data_str = decoded_line[len('data: '):]
                data_json = json.loads(data_str)
                choices = data_json.get('choices', [])
                if not choices:
                    continue
                finish_reason = choices[0].get('finish_reason', '')
                if finish_reason == 'stop':
                    break
                delta = choices[0].get('delta', {})
                content = delta.get('content', '')
                if content:
                    print(f'{content}', end="")
    print()

print('stream end')
        

Giải thích Mã

Chú ý

Hãy thay thế api_key bằng khóa API của bạn và đảm bảo rằng base_url đúng với địa chỉ https://api.keyai.shop/v1.