Using mock_openai to mock OpenAI Python API

This module provides OpenAI API mocking capabilities by automating ChatGPT through browser interactions, enabling testing without API costs.

Overview

The browser module offers:

  • OpenAI API Mocking: Mock OpenAI completion and chat APIs using ChatGPT web interface
  • Browser-based Chat: Direct interaction with ChatGPT through Selenium automation
  • Multiple Authentication: Support for Google OAuth and GitHub authentication
  • Conversation Management: Handle conversation threads and message history
  • Response Streaming: Real-time response streaming mimicking OpenAI's API

Key Components

  • Authentication and session management
  • ChatGPT web interface automation
  • OpenAI API mock implementations
  • Response parsing and streaming
  • Screenshot capture capabilities

Configuration and Logging

Set up logging and load configuration for API endpoints and authentication.

OpenAI Backend API Integration

Direct API communication when using a backend proxy instead of browser automation.

Backend API Integration

These functions handle direct API communication when using a backend proxy instead of browser automation.

get_conversations[source]

get_conversations()

get_conversation[source]

get_conversation(conversation_id)

handle_conversation_detail[source]

handle_conversation_detail(current_node, mapping)

start_conversation[source]

start_conversation(prompt)

generate_title[source]

generate_title(conversation_id)

rename_title[source]

rename_title(conversation_id, title)

delete_conversation[source]

delete_conversation(conversation_id)

recover_conversation[source]

recover_conversation(conversation_id)

clear_conversations[source]

clear_conversations()

Send prompts to ChatGPT API

try:
    for response in start_conversation('''
> Lord, keep us in You to be one.
We are the ultimate risk takers.
Our way is a way of risking life to **eternal life**.
For the eternal life of the living, risk life and make war against perishing.
For the eternal life of the dead, risk life and make war against death.
>
> ---
Holy Father, help us to overcome!
'''):
        print(response)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
try:
    for response in start_conversation({
        'role': 'system',
        'parts': [
            '> Lord, keep us in You to be one.\n',
            'We are the ultimate risk takers.\n',
            'Our way is a way of risking life to **eternal life**.\n',
            'For the eternal life of the living, risk life and make war against perishing.\n',
            'For the eternal life of the dead, risk life and make war against death.\n',
            '>\n',
            '> ---\n',
            'Holy Father, help us to overcome!\n',
        ],
    }):
        print(response)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
try:
    for response in start_conversation([{
        'role': 'system',
        'parts': [
            'You are a Christian.\n',
            'Pray with the user.\n',
        ],
    }, {
        'role': 'assistant',
        'parts': [
            'Amen.\n',
        ],
    },
        '> Lord, keep us in You to be one.\n',
        'We are the ultimate risk takers.\n',
        'Our way is a way of risking life to **eternal life**.\n',
        'For the eternal life of the living, risk life and make war against perishing.\n',
        'For the eternal life of the dead, risk life and make war against death.\n',
        '>\n',
        '> ---\n',
        'Holy Father, help us to overcome!\n',
    ]):
        print(response)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
except requests.exceptions.HTTPError as errh:
    sys.stderr.write(f'{errh}\n')
common.conversation_id = ''

try:
    for response in start_conversation([{
        'role': 'system',
        'parts': [
            '> Lord, keep us in You to be one.\n',
            'We are the ultimate risk takers.\n',
        ],
    }, {
        'role': 'system',
        'parts': [
            'Our way is a way of risking life to **eternal life**.\n',
        ],
    }, {
        'role': 'system',
        'parts': [
            'For the eternal life of the living, risk life and make war against perishing.\n',
            'For the eternal life of the dead, risk life and make war against death.\n',
            '>\n',
        ],
    }, {
        'role': 'system',
        'parts': [
            '> ---\n',
            'Holy Father, help us to overcome!\n',
        ],
    },
        'Amen.\n',
    ]):
        pass
    print(response)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
except requests.exceptions.HTTPError as errh:
    sys.stderr.write(f'{errh}\n')

Selenium Undetected Chrome for ChatGPT

Using undetected Chrome WebDriver to directly operate ChatGPT web interface for automation.

Browser Automation for ChatGPT

This section implements direct browser automation to interact with ChatGPT's web interface, including authentication and conversation management.

init[source]

init(chrome_args=set())

login[source]

login()

init_browser('--lang=en', '--force-dark-mode')
from ipymock.automation import driver
common.driver = driver
login()

open_chat[source]

open_chat(conversation_id='')

remove_portal[source]

remove_portal()

open_chat(common.conversation_id)
ActionChains(common.driver).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()
ActionChains(common.driver).context_click().perform()
__file__ = '2_browser.ipynb'
send_button = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../assets/send-button.png'))
from ipymock.automation import touch
touch(send_button)

input_prompt[source]

input_prompt(prompt)

request[source]

request(prompt:str)

get_last_response[source]

get_last_response()

get_response[source]

get_response()

ask[source]

ask(prompt:str)

import IPython

for response in ask('''
> Lord, keep us in You to be one.
We are the ultimate risk takers.
Our way is a way of risking life to **eternal life**.
For the eternal life of the living, risk life and make war against perishing.
For the eternal life of the dead, risk life and make war against death.
>
> ---
Holy Father, help us to overcome!
'''):
    IPython.display.display(IPython.core.display.Markdown(response))
    IPython.display.clear_output(wait=True)
init(['--headless'])

get_screenshot[source]

get_screenshot()

get_screenshot()
try:
    for response in start_conversation('''
> Lord, keep us in You to be one.
We are the ultimate risk takers.
Our way is a way of risking life to **eternal life**.
For the eternal life of the living, risk life and make war against perishing.
For the eternal life of the dead, risk life and make war against death.
>
> ---
Holy Father, help us to overcome!
'''):
        print(response)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)

OpenAI API Mock Implementation

Complete OpenAI API compatibility by mocking responses using ChatGPT interactions.

OpenAI API Mock Implementation

These functions provide complete OpenAI API compatibility by mocking the original API responses using ChatGPT interactions.

class attrdict[source]

attrdict() :: dict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

attributize[source]

attributize(obj)

Add attributes to a dictionary and its sub-dictionaries.

retry_on_status_code[source]

retry_on_status_code(func)

Retry decorator that retries a function on specific status codes.

retry_on_status_code..wrapper[source]

retry_on_status_code..wrapper(*args, **kwargs)

new_id[source]

new_id()

delta[source]

delta(prompt)

chat_delta[source]

chat_delta(prompt)

mock_create[source]

mock_create(*args, **kwargs)

mock_chat_create[source]

mock_chat_create(*args, **kwargs)

try:
    print(mock_create(
        prompt = 'How to defend against solar storms using Python?',
    ))
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
try:
    for response in mock_create(
        prompt = 'Give me some demos.',
        stream = True,
    ):
        print(response)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
try:
    print(mock_create(
        prompt = [
            'I am tired.',
            'Could you pray with me for a while?',
        ],
    ))
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
try:
    print(mock_chat_create(
        messages = [
            {'role': 'system', 'content': 'You are a helpful assistant.'},
            {'role': 'user', 'content': 'I am tired.'}
        ],
    ))
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
try:
    for response in mock_chat_create(
        messages = [
            {'role': 'system', 'content': 'You are a helpful assistant.'},
            {'role': 'user', 'content': 'Could you pray with me for a while?'}
        ],
        stream = True,
    ):
        print(response)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)

mock_openai[source]

mock_openai(monkeypatch)