Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenAi Api request with proxy

`I need to make a request for OpenAi by proxy. Proxy - IPv4 Python error: 407 Proxy Authentication Required Access to requested resource disallowed by administrator or you need valid username/password to use this resource

My code

import config
from openai import OpenAI

proxies = 
{
    'https': 'http://M0k0EN:[email protected]:9943'
}

client = OpenAI
(
    api_key=config.api_key,
    base_url=proxies.get('https'),
)
completion = client.completions.create
(
    model="gpt-3.5-turbo-instruct",
    prompt="Say this is a test",
    max_tokens=7,
    temperature=0
)

print(completion.choices[0].text)
like image 468
SajCrew Avatar asked Oct 20 '25 06:10

SajCrew


1 Answers

  1. create .env in your project directory
    OPENAI_API_KEY=your api key
    OPENAI_PROXY_URL=http://127.0.0.1:1080
  1. invoke api
import httpx
from openai import OpenAI
from dotenv import load_dotenv
import os

load_dotenv()

proxy_url = os.environ.get("OPENAI_PROXY_URL")

client = OpenAI() if proxy_url is None or proxy_url == "" else OpenAI(http_client=httpx.Client(proxy=proxy_url))


completion = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system",
         "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
        {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
    ]
)

print(completion.choices[0].message)
like image 127
Yadong Xu Avatar answered Oct 22 '25 21:10

Yadong Xu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!