repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
MoneyPrinterV2 | scripts/preflight_local.py | .py | #!/usr/bin/env python3
import json
import os
import sys
from typing import Tuple
import requests
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_PATH = os.path.join(ROOT_DIR, "config.json")
def ok(msg: str) -> None:
print(f"[OK] {msg}")
def warn(msg: str) -> None:
print(f"[W... | 125 | 3,662 |
MoneyPrinterV2 | src/llm_provider.py | .py | import ollama
from config import get_ollama_base_url
_selected_model: str | None = None
def _client() -> ollama.Client:
return ollama.Client(host=get_ollama_base_url())
def list_models() -> list[str]:
"""
Lists all models available on the local Ollama server.
Returns:
models (list[str]): ... | 64 | 1,490 |
MoneyPrinterV2 | src/main.py | .py | import schedule
import subprocess
from art import *
from cache import *
from utils import *
from config import *
from status import *
from uuid import uuid4
from constants import *
from classes.Tts import TTS
from termcolor import colored
from classes.Twitter import Twitter
from classes.YouTube import YouTube
from pre... | 494 | 19,511 |
MoneyPrinterV2 | src/utils.py | .py | import os
import random
import zipfile
import requests
import platform
from status import *
from config import *
DEFAULT_SONG_ARCHIVE_URLS = []
def close_running_selenium_instances() -> None:
"""
Closes any running Selenium instances.
Returns:
None
"""
try:
info(" => Closing run... | 160 | 4,754 |
MoneyPrinterV2 | src/constants.py | .py | """
This file contains all the constants used in the program.
"""
TWITTER_TEXTAREA_CLASS = "public-DraftStyleDefault-block public-DraftStyleDefault-ltr"
TWITTER_POST_BUTTON_XPATH = "/html/body/div[1]/div/div/div[2]/main/div/div/div/div[1]/div/div[3]/div/div[2]/div[1]/div/div/div/div[2]/div[2]/div[2]/div/div/div/div[3]... | 55 | 1,247 |
MoneyPrinterV2 | src/status.py | .py | from termcolor import colored
def error(message: str, show_emoji: bool = True) -> None:
"""
Prints an error message.
Args:
message (str): The error message
show_emoji (bool): Whether to show the emoji
Returns:
None
"""
emoji = "❌" if show_emoji else ""
print(colore... | 72 | 1,749 |
MoneyPrinterV2 | src/cron.py | .py | # RUN THIS N AMOUNT OF TIMES
import sys
from status import *
from cache import get_accounts
from config import get_verbose
from classes.Tts import TTS
from classes.Twitter import Twitter
from classes.YouTube import YouTube
from llm_provider import select_model
from post_bridge_integration import maybe_crosspost_youtub... | 101 | 3,399 |
MoneyPrinterV2 | src/config.py | .py | import os
import sys
import json
import srt_equalizer
from termcolor import colored
ROOT_DIR = os.path.dirname(sys.path[0])
def assert_folder_structure() -> None:
"""
Make sure that the nessecary folder structure is present.
Returns:
None
"""
# Create the .mp folder
if not os.path.ex... | 406 | 11,684 |
MoneyPrinterV2 | src/post_bridge_integration.py | .py | import os
from typing import Callable
from typing import Optional
from classes.PostBridge import PostBridge
from classes.PostBridge import PostBridgeClientError
from config import get_post_bridge_config
from status import info
from status import question
from status import success
from status import warning
def reso... | 223 | 7,168 |
MoneyPrinterV2 | src/cache.py | .py | import os
import json
from typing import List
from config import ROOT_DIR
def get_cache_path() -> str:
"""
Gets the path to the cache file.
Returns:
path (str): The path to the cache folder
"""
return os.path.join(ROOT_DIR, '.mp')
def get_afm_cache_path() -> str:
"""
Gets the pat... | 194 | 4,780 |
MoneyPrinterV2 | src/art.py | .py | from config import ROOT_DIR
from termcolor import colored
def print_banner() -> None:
"""
Prints the introductory ASCII Art Banner.
Returns:
None
"""
with open(f"{ROOT_DIR}/assets/banner.txt", "r") as file:
print(colored(file.read(), "green"))
| 13 | 282 |
MoneyPrinterV2 | src/classes/Outreach.py | .py | import os
import io
import re
import csv
import time
import glob
import shlex
import zipfile
import yagmail
import requests
import subprocess
import platform
from cache import *
from status import *
from config import *
class Outreach:
"""
Class that houses the methods to reach out to businesses.
"""
... | 294 | 9,774 |
MoneyPrinterV2 | src/classes/Tts.py | .py | import os
import soundfile as sf
from kittentts import KittenTTS as KittenModel
from config import ROOT_DIR, get_tts_voice
KITTEN_MODEL = "KittenML/kitten-tts-mini-0.8"
KITTEN_SAMPLE_RATE = 24000
class TTS:
def __init__(self) -> None:
self._model = KittenModel(KITTEN_MODEL)
self._voice = get_tts_... | 19 | 563 |
MoneyPrinterV2 | src/classes/AFM.py | .py | import os
from urllib.parse import urlparse
from typing import Any
from status import *
from config import *
from constants import *
from llm_provider import generate_text
from .Twitter import Twitter
from selenium_firefox import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from seleniu... | 177 | 5,340 |
MoneyPrinterV2 | src/classes/PostBridge.py | .py | import mimetypes
import os
import time
from typing import Optional
from typing import Sequence
import requests
class PostBridgeClientError(RuntimeError):
"""
Raised when a Post Bridge request fails.
"""
def __init__(self, message: str, status_code: Optional[int] = None) -> None:
super().__in... | 280 | 8,713 |
MoneyPrinterV2 | src/classes/YouTube.py | .py | import re
import base64
import json
import time
import os
import requests
import assemblyai as aai
from utils import *
from cache import *
from .Tts import TTS
from llm_provider import generate_text
from config import *
from status import *
from uuid import uuid4
from constants import *
from typing import List
from mo... | 879 | 28,711 |
MoneyPrinterV2 | src/classes/Twitter.py | .py | import re
import sys
import time
import os
import json
from cache import *
from config import *
from status import *
from llm_provider import generate_text
from typing import List, Optional
from datetime import datetime
from termcolor import colored
from selenium_firefox import *
from selenium import webdriver
from se... | 226 | 6,935 |
openai-python | noxfile.py | .py | import nox
@nox.session(reuse_venv=True, name="test-pydantic-v1")
def test_pydantic_v1(session: nox.Session) -> None:
session.install("-r", "requirements-dev.lock")
session.install("pydantic<2")
session.run("pytest", "--showlocals", "--ignore=tests/functional", *session.posargs)
| 10 | 295 |
openai-python | tests/test_streaming.py | .py | from __future__ import annotations
from typing import Iterator, AsyncIterator
import httpx2
import pytest
from openai import OpenAI, AsyncOpenAI
from openai._streaming import Stream, AsyncStream, ServerSentEvent
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
async def t... | 249 | 7,965 |
openai-python | tests/test_response.py | .py | import json
from typing import Any, List, Union, cast
from typing_extensions import Annotated
import httpx2
import pytest
import pydantic
from openai import OpenAI, BaseModel, AsyncOpenAI
from openai._response import (
APIResponse,
BaseAPIResponse,
AsyncAPIResponse,
BinaryAPIResponse,
AsyncBinaryA... | 325 | 9,692 |
openai-python | tests/test_client.py | .py | from __future__ import annotations
import gc
import os
import sys
import json
import asyncio
import inspect
import dataclasses
import tracemalloc
from typing import Any, Union, TypeVar, Callable, Iterable, Iterator, Optional, Coroutine, cast
from unittest import mock
from typing_extensions import Literal, AsyncIterato... | 3,041 | 117,181 |
openai-python | tests/test_send_queue.py | .py | from __future__ import annotations
import pytest
from openai._exceptions import WebSocketQueueFullError
from openai._send_queue import SendQueue
class TestSendQueue:
def test_enqueue_and_drain(self) -> None:
q = SendQueue()
q.enqueue('{"type": "session.update"}')
q.enqueue('{"type": "res... | 127 | 3,557 |
openai-python | tests/test_httpx2_workload.py | .py | from __future__ import annotations
import json
from typing import Any
import httpx2
import pytest
import openai._base_client as base_client
import openai.auth._workload as workload
from openai import (
OpenAI,
OAuthError,
AsyncOpenAI,
APITimeoutError,
APIConnectionError,
DefaultHttpx2Client,
... | 262 | 10,321 |
openai-python | tests/utils.py | .py | from __future__ import annotations
import io
import os
import inspect
import traceback
import contextlib
from typing import Any, TypeVar, Iterator, Sequence, ForwardRef, cast
from datetime import date, datetime
from typing_extensions import Literal, get_args, get_origin, assert_type
import rich
from openai._types im... | 185 | 5,403 |
openai-python | tests/test_transform.py | .py | from __future__ import annotations
import io
import pathlib
from typing import Any, Dict, List, Union, TypeVar, Iterable, Optional, cast
from datetime import date, datetime
from typing_extensions import Required, Annotated, TypedDict
import pytest
from openai._types import Base64FileInput, omit, not_given
from opena... | 461 | 15,605 |
openai-python | tests/test_httpx2.py | .py | from __future__ import annotations
import base64
from typing import Any
from typing_extensions import override
import httpx2
import pytest
import openai
from openai import (
OpenAI,
AsyncOpenAI,
AzureOpenAI,
OpenAIError,
APIStatusError,
APITimeoutError,
AsyncAzureOpenAI,
APIConnection... | 713 | 29,988 |
openai-python | tests/test_extract_files.py | .py | from __future__ import annotations
from typing import Sequence
import pytest
from openai._types import FileTypes, ArrayFormat
from openai._utils import extract_files
def test_removes_files_from_input() -> None:
query = {"foo": "bar"}
assert extract_files(query, paths=[]) == []
assert query == {"foo": "... | 92 | 3,280 |
openai-python | tests/test_auth.py | .py | import json
from typing import cast
from pathlib import Path
import httpx2
import pytest
from inline_snapshot import snapshot
from tests import respx2
from openai import OpenAI, OAuthError
from tests.respx2.models import Call
from openai.auth._workload import (
gcp_id_token_provider,
k8s_service_account_token... | 187 | 5,790 |
openai-python | tests/test_websocket_connection_options.py | .py | from openai import types
from openai.types import websocket_connection_options
def test_submodule_alias_is_preserved() -> None:
assert (
websocket_connection_options.WebsocketConnectionOptions
is websocket_connection_options.WebSocketConnectionOptions
)
def test_public_types_alias_is_preserv... | 21 | 661 |
openai-python | tests/test_httpx_compat.py | .py | from __future__ import annotations
import os
import asyncio
import importlib
import threading
from typing import Any, cast
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from typing_extensions import override
import pytest
from openai import OpenAI, AsyncOpenAI
pytestmark = pytest.mark.skipif(
... | 89 | 2,951 |
openai-python | tests/test_models.py | .py | import json
from typing import TYPE_CHECKING, Any, Dict, List, Union, Iterable, Optional, cast
from datetime import datetime, timezone
from collections import deque
from typing_extensions import Literal, Annotated, TypedDict, TypeAliasType
import pytest
import pydantic
from pydantic import Field
from openai._utils im... | 1,018 | 29,461 |
openai-python | tests/test_legacy_response.py | .py | import json
from typing import Any, Union, cast
from typing_extensions import Annotated
import httpx2
import pytest
import pydantic
from openai import OpenAI, BaseModel
from openai._streaming import Stream
from openai._base_client import FinalRequestOptions
from openai._legacy_response import LegacyAPIResponse
from ... | 154 | 4,358 |
openai-python | tests/test_httpx2_base.py | .py | from __future__ import annotations
import sys
import asyncio
import warnings
import threading
import subprocess
import importlib.util
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from typing_extensions import override
import httpx2
import pytest
import openai
from openai import OpenAI, AsyncOp... | 98 | 3,655 |
openai-python | tests/test_files.py | .py | from pathlib import Path
import anyio
import pytest
from dirty_equals import IsDict, IsList, IsBytes, IsTuple
from openai._files import to_httpx_files, deepcopy_with_paths, async_to_httpx_files
from openai._utils import extract_files
readme_path = Path(__file__).parent.parent.joinpath("README.md")
def test_pathlib... | 149 | 5,225 |
openai-python | tests/test_module_client.py | .py | from __future__ import annotations
import os as _os
import httpx2
import pytest
from httpx2 import URL
import openai
from openai import DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES
def reset_state() -> None:
openai._reset_client()
openai.api_key = None
openai.admin_api_key = None
openai.organization = None... | 317 | 10,418 |
openai-python | tests/test_qs.py | .py | from typing import Any, cast
from functools import partial
from urllib.parse import unquote
import pytest
from openai._qs import Querystring, stringify
def test_empty() -> None:
assert stringify({}) == ""
assert stringify({"a": {}}) == ""
assert stringify({"a": {"b": {"c": {}}}}) == ""
def test_basic(... | 79 | 3,200 |
openai-python | tests/test_httpx2_respx.py | .py | from __future__ import annotations
import os
import httpx2
import pytest
from openai import OpenAI, AsyncOpenAI, APITimeoutError
from tests.respx2 import MockRouter
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
@pytest.mark.respx2(base_url=base_url)
def test_respx2_preserves_native_sync_... | 62 | 2,216 |
openai-python | tests/test_required_args.py | .py | from __future__ import annotations
import pytest
from openai._utils import required_args
def test_too_many_positional_params() -> None:
@required_args(["a"])
def foo(a: str | None = None) -> str | None:
return a
with pytest.raises(TypeError, match=r"foo\(\) takes 1 argument\(s\) but 2 were give... | 112 | 3,057 |
openai-python | tests/test_mtls_http_client.py | .py | from __future__ import annotations
import os
import ssl
import sys
import threading
import subprocess
from typing import Any, cast
from pathlib import Path
from contextlib import contextmanager
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from collections.abc import Iterator
from typing_extensio... | 117 | 3,822 |
openai-python | tests/conftest.py | .py | from __future__ import annotations
import os
import logging
from typing import TYPE_CHECKING, Iterator, AsyncIterator
import httpx2
import pytest
from pytest_asyncio import is_async_test
from openai import OpenAI, AsyncOpenAI, DefaultHttpx2Client, DefaultAioHttpClient, DefaultAsyncHttpx2Client
from openai._utils imp... | 104 | 3,397 |
openai-python | tests/api_resources/beta/test_realtime.py | .py | from __future__ import annotations
import os
import pytest
# pyright: reportDeprecated=false
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
class TestRealtime:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
class TestAsyncRealt... | 20 | 491 |
openai-python | tests/respx2/types.py | .py | from typing import (
IO,
Any,
AsyncIterable,
Awaitable,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Pattern,
Sequence,
Tuple,
Type,
TypeVar,
Union,
)
import httpx2 as httpx
URL = Tuple[
bytes, # scheme
bytes, # host
Opt... | 72 | 1,829 |
openai-python | tests/respx2/transports.py | .py | from types import TracebackType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Coroutine,
List,
Optional,
Type,
Union,
cast,
)
from warnings import warn
import httpx2 as httpx
from httpx2 import AsyncBaseTransport, BaseTransport
from .models import PassThrough
if TYPE_CHECKING... | 94 | 2,759 |
openai-python | tests/respx2/utils.py | .py | import email
from collections import defaultdict
from datetime import datetime
from email.message import Message
from typing import (
Any,
Dict,
Iterable,
List,
Literal,
NamedTuple,
Optional,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from urllib.parse import parse_qsl
import ... | 158 | 4,710 |
openai-python | tests/respx2/models.py | .py | import inspect
from typing import (
Any,
Dict,
Iterator,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
Type,
Union,
)
from unittest import mock
from warnings import warn
import httpx2 as httpx
from tests.respx2.utils import SetCookie
from .patterns import M, Pattern
from .types... | 551 | 16,828 |
openai-python | tests/respx2/__init__.py | .py | from .__version__ import __version__
from .handlers import ASGIHandler, WSGIHandler
from .models import MockResponse, Route
from .router import MockRouter, Router
from .utils import SetCookie
from .api import ( # isort:skip
mock,
routes,
calls,
start,
stop,
clear,
reset,
pop,
route... | 57 | 803 |
openai-python | tests/respx2/fixtures.py | .py | try:
import pytest
except ImportError: # pragma: nocover
pass
else:
import asyncio
@pytest.fixture(scope="session")
def session_event_loop():
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
| 13 | 268 |
openai-python | tests/respx2/handlers.py | .py | from typing import Any, Callable
import httpx2 as httpx
class TransportHandler:
def __init__(self, transport: httpx.BaseTransport) -> None:
self.transport = transport
def __call__(self, request: httpx.Request) -> httpx.Response:
if not isinstance(
request.stream,
http... | 42 | 1,325 |
openai-python | tests/respx2/router.py | .py | import inspect
from contextlib import contextmanager
from functools import partial, update_wrapper, wraps
from types import TracebackType
from typing import (
Any,
Callable,
Dict,
Generator,
List,
NewType,
Optional,
Tuple,
Type,
Union,
cast,
overload,
)
import httpx2 as ... | 487 | 15,311 |
openai-python | tests/respx2/mocks.py | .py | import inspect
from abc import ABC
from types import MappingProxyType
from typing import TYPE_CHECKING, ClassVar, Dict, List, Type
from unittest import mock
import httpcore2 as httpcore
import httpx2 as httpx
from tests.respx2.patterns import parse_url
from .models import AllMockedAssertionError, PassThrough
from .t... | 340 | 10,782 |
openai-python | tests/respx2/api.py | .py | from typing import Any, Optional, Union, overload
from .models import CallList, Route
from .patterns import Pattern
from .router import MockRouter
from .types import DefaultType, URLPatternTypes
mock = MockRouter(assert_all_called=False)
routes = mock.routes
calls: CallList = mock.calls
def start() -> None:
gl... | 117 | 2,586 |
openai-python | tests/respx2/patterns.py | .py | import io
import json as jsonlib
import operator
import pathlib
import re
from abc import ABC
from enum import Enum
from functools import reduce
from http.cookies import SimpleCookie
from types import MappingProxyType
from typing import (
Any,
Callable,
ClassVar,
Dict,
List,
Mapping,
Optiona... | 783 | 23,206 |
openai-python | tests/respx2/plugin.py | .py | from typing import cast
import pytest
from tests import respx2 as respx
from .router import MockRouter
def pytest_configure(config):
config.addinivalue_line(
"markers",
"respx2(assert_all_called=False, assert_all_mocked=False, base_url=...): "
"configure the respx2_mock fixture. "
... | 31 | 701 |
openai-python | tests/lib/test_bedrock_credential_chain.py | .py | from __future__ import annotations
import sys
import json
import threading
from typing import Any, Iterator, cast
from pathlib import Path
from datetime import datetime, timezone, timedelta
from contextlib import contextmanager
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from typing_extensions ... | 390 | 14,736 |
openai-python | tests/lib/utils.py | .py | from __future__ import annotations
import re
from typing import Any, Iterable
from typing_extensions import TypeAlias
import pytest
import pydantic
from ..utils import rich_print_str
ReprArgs: TypeAlias = "Iterable[tuple[str | None, Any]]"
def print_obj(obj: object, monkeypatch: pytest.MonkeyPatch) -> str:
""... | 35 | 1,154 |
openai-python | tests/lib/test_bedrock.py | .py | from __future__ import annotations
import json
from typing import Any, Union, Protocol, cast
from pathlib import Path
import httpx2
import pytest
from httpx2 import URL
import openai.lib._bedrock_auth as bedrock_auth_module
from openai import OpenAIError, NotFoundError, DefaultHttpx2Client, DefaultAsyncHttpx2Client
... | 1,204 | 48,531 |
openai-python | tests/lib/test_bedrock_auth_conformance.py | .py | from __future__ import annotations
import json
import base64
import hashlib
import logging
import threading
from typing import Any, Iterator, AsyncIterator, cast
from pathlib import Path
from datetime import datetime
import httpx2
import pytest
import jsonschema
from openai import OpenAI, AsyncOpenAI, OpenAIError, A... | 439 | 16,813 |
openai-python | tests/lib/test_bedrock_provider.py | .py | from __future__ import annotations
import builtins
from typing import Any, Iterator, cast
import httpx2
import pytest
import openai.lib._bedrock_auth as bedrock_auth_module
from openai import OpenAI, AsyncOpenAI, OpenAIError
from tests.utils import update_env
from openai._types import Omit
from openai._provider impo... | 437 | 16,289 |
openai-python | tests/lib/test_audio.py | .py | from __future__ import annotations
import sys
import inspect
import typing_extensions
from typing import get_args
import pytest
from openai import OpenAI, AsyncOpenAI
from tests.utils import evaluate_forwardref
from openai._utils import assert_signatures_in_sync
from openai._compat import is_literal_type
from openai... | 94 | 3,744 |
openai-python | tests/lib/snapshots.py | .py | from __future__ import annotations
import os
import json
from typing import Any, Callable, Awaitable
from typing_extensions import TypeVar
import httpx2
from inline_snapshot import get_snapshot_value
from openai import OpenAI, AsyncOpenAI
from tests.respx2 import MockRouter
_T = TypeVar("_T")
def make_snapshot_re... | 101 | 2,372 |
openai-python | tests/lib/test_old_api.py | .py | import pytest
import openai
from openai.lib._old_api import APIRemovedInV1
def test_basic_attribute_access_works() -> None:
for attr in dir(openai):
getattr(openai, attr)
def test_helpful_error_is_raised() -> None:
with pytest.raises(APIRemovedInV1):
openai.Completion.create() # type: igno... | 18 | 419 |
openai-python | tests/lib/test_assistants.py | .py | from __future__ import annotations
import pytest
from openai import OpenAI, AsyncOpenAI
from openai._utils import assert_signatures_in_sync
@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
def test_create_and_run_poll_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpe... | 51 | 2,154 |
openai-python | tests/lib/test_pydantic.py | .py | from __future__ import annotations
from enum import Enum
from pydantic import Field, BaseModel
from inline_snapshot import snapshot
import openai
from openai._compat import PYDANTIC_V1
from openai.lib._pydantic import to_strict_json_schema
from .schema_types.query import Query
def test_most_types() -> None:
i... | 412 | 17,887 |
openai-python | tests/lib/test_azure.py | .py | from __future__ import annotations
import logging
from typing import Union, cast
from typing_extensions import Literal, Protocol
import httpx2
import pytest
from openai import OpenAIError
from tests.utils import update_env
from tests.respx2 import MockRouter
from openai._types import Omit
from openai._utils import S... | 958 | 38,249 |
openai-python | tests/lib/bedrock_live.py | .py | """Opt-in live test for the Amazon Bedrock provider.
This file is intentionally named ``bedrock_live.py`` so the standard pytest
suite does not collect it. Run it explicitly with:
rye run pytest -q -s tests/lib/bedrock_live.py
The test loads ``.env`` from the repository root when it exists. Set
``BEDROCK_LIVE_EN... | 101 | 3,585 |
openai-python | tests/lib/schema_types/query.py | .py | from enum import Enum
from typing import List, Union, Optional
from pydantic import BaseModel
class Table(str, Enum):
orders = "orders"
customers = "customers"
products = "products"
class Column(str, Enum):
id = "id"
status = "status"
expected_delivery_date = "expected_delivery_date"
de... | 53 | 935 |
openai-python | tests/lib/chat/test_completions_streaming.py | .py | from __future__ import annotations
import os
from typing import Any, Generic, Callable, Iterator, cast, overload
from typing_extensions import Literal, TypeVar
import rich
import httpx2
import pytest
from pydantic import BaseModel
from inline_snapshot import (
external,
snapshot,
outsource, # pyright: ig... | 1,194 | 37,641 |
openai-python | tests/lib/chat/test_completions.py | .py | from __future__ import annotations
from enum import Enum
from typing import List, Optional
from typing_extensions import Literal, TypeVar
import pytest
from pydantic import Field, BaseModel
from inline_snapshot import snapshot
import openai
from openai import OpenAI, AsyncOpenAI
from tests.respx2 import MockRouter
f... | 1,012 | 39,975 |
openai-python | tests/lib/responses/test_responses.py | .py | from __future__ import annotations
from typing_extensions import TypeVar
import pytest
from inline_snapshot import snapshot
from openai import OpenAI, AsyncOpenAI
from tests.respx2 import MockRouter
from openai._types import omit
from openai._utils import assert_signatures_in_sync
from openai._models import construc... | 95 | 4,399 |
openai-python | tests/test_utils/test_logging.py | .py | import logging
from typing import Any, Dict, cast
import pytest
from openai._utils import SensitiveHeadersFilter
from openai._utils._logs import setup_logging
@pytest.fixture
def logger_with_filter() -> logging.Logger:
logger = logging.getLogger("test_logger")
logger.setLevel(logging.DEBUG)
logger.addFi... | 116 | 4,452 |
openai-python | tests/test_utils/test_proxy.py | .py | import operator
from typing import Any
from typing_extensions import override
from openai._utils import LazyProxy
from openai._extras._common import MissingDependencyError
class RecursiveLazyProxy(LazyProxy[Any]):
@override
def __load__(self) -> Any:
return self
def __call__(self, *_args: Any, *... | 36 | 1,072 |
openai-python | tests/test_utils/test_datetime_parse.py | .py | """
Copied from https://github.com/pydantic/pydantic/blob/v1.10.22/tests/test_datetime_parse.py
with modifications so it works without pydantic v1 imports.
"""
from typing import Type, Union
from datetime import date, datetime, timezone, timedelta
import pytest
from openai._utils import parse_date, parse_datetime
... | 111 | 5,454 |
openai-python | tests/test_utils/test_typing.py | .py | from __future__ import annotations
from typing import Generic, TypeVar, cast
from openai._utils import extract_type_var_from_base
_T = TypeVar("_T")
_T2 = TypeVar("_T2")
_T3 = TypeVar("_T3")
class BaseGeneric(Generic[_T]): ...
class SubclassGeneric(BaseGeneric[_T]): ...
class BaseGenericMultipleTypeArgs(Generi... | 74 | 2,457 |
openai-python | tests/test_utils/test_path.py | .py | from __future__ import annotations
from typing import Any
import pytest
from openai._utils._path import path_template
@pytest.mark.parametrize(
"template, kwargs, expected",
[
("/v1/{id}", dict(id="abc"), "/v1/abc"),
("/v1/{a}/{b}", dict(a="x", b="y"), "/v1/x/y"),
("/v1/{a}{b}/path/... | 90 | 3,893 |
openai-python | tests/test_utils/test_json.py | .py | from __future__ import annotations
import datetime
from typing import Union
import pydantic
from openai import _compat
from openai._utils._json import openapi_dumps
class TestOpenapiDumps:
def test_basic(self) -> None:
data = {"key": "value", "number": 42}
json_bytes = openapi_dumps(data)
... | 127 | 4,969 |
openai-python | tests/compat/test_tool_param.py | .py | from openai.types.chat import ChatCompletionToolParam
def test_tool_param_can_be_instantiated() -> None:
assert ChatCompletionToolParam(type="function", function={"name": "test"}) == {
"function": {"name": "test"},
"type": "function",
}
| 9 | 263 |
openai-python | scripts/detect-breaking-changes.py | .py | from __future__ import annotations
import sys
from typing import Iterator
from pathlib import Path
import rich
import griffe
from rich.text import Text
from rich.style import Style
def public_members(obj: griffe.Object | griffe.Alias) -> dict[str, griffe.Object | griffe.Alias]:
if isinstance(obj, griffe.Alias):... | 80 | 2,481 |
openai-python | scripts/check-python-version-policy.py | .py | from __future__ import annotations
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SUPPORTED = ("3.10", "3.11", "3.12", "3.13", "3.14")
MINIMUM = SUPPORTED[0]
CURRENT_STABLE = SUPPORTED[-1]
PRERELEASE = "3.15"
UNMARKED_DEPENDENCIES = (
"aiohttp>=3.14.1",
"httpx2>=2.7.0, <3",
... | 143 | 5,579 |
openai-python | scripts/utils/validate-python-version-wheel.py | .py | from __future__ import annotations
import sys
import email
import tarfile
import zipfile
import argparse
import platform
import tempfile
import subprocess
from pathlib import Path
from email.message import Message
ROOT = Path(__file__).resolve().parents[2]
EXPECTED_REQUIRES_PYTHON = ">=3.10"
def wheel_metadata(whee... | 100 | 3,605 |
openai-python | scripts/utils/validate-bedrock-wheel.py | .py | from __future__ import annotations
import os
import sys
import email
import zipfile
import tempfile
import subprocess
from pathlib import Path
_SMOKE_TEST = r"""
import os
import sys
import importlib.abc
from pathlib import Path
import httpx2
class BlockBotocore(importlib.abc.MetaPathFinder):
def find_spec(sel... | 128 | 4,460 |
openai-python | scripts/utils/validate-httpx2-wheel.py | .py | from __future__ import annotations
import os
import re
import sys
import email
import zipfile
import tempfile
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
BASE_TEST = ROOT / "tests/test_httpx2_base.py"
HTTPX2_TEST = ROOT / "tests/test_httpx2.py"
LEGACY_TEST = ROOT / "tests/tes... | 121 | 5,089 |
openai-python | scripts/utils/ruffen-docs.py | .py | # fork of https://github.com/asottile/blacken-docs adapted for ruff
from __future__ import annotations
import re
import sys
import argparse
import textwrap
import contextlib
import subprocess
from typing import Match, Optional, Sequence, Generator, NamedTuple, cast
MD_RE = re.compile(
r"(?P<before>^(?P<indent> *)... | 168 | 5,216 |
openai-python | examples/responses_input_tokens.py | .py | from typing import List
from openai import OpenAI
from openai.types.responses.tool_param import ToolParam
from openai.types.responses.response_input_item_param import ResponseInputItemParam
def main() -> None:
client = OpenAI()
tools: List[ToolParam] = [
{
"type": "function",
... | 55 | 1,662 |
openai-python | examples/httpx2_client.py | .py | from openai import OpenAI, DefaultHttpx2Client
client = OpenAI(http_client=DefaultHttpx2Client())
response = client.responses.create(
model="gpt-5.2",
input="Say this is a test",
)
print(response.output_text)
| 11 | 220 |
openai-python | examples/async_demo.py | .py | #!/usr/bin/env -S poetry run python
import asyncio
from openai import AsyncOpenAI
# gets API Key from environment variable OPENAI_API_KEY
client = AsyncOpenAI()
async def main() -> None:
stream = await client.chat.completions.create(
model="gpt-5.5",
messages=[
{
"ro... | 31 | 606 |
openai-python | examples/image_stream.py | .py | #!/usr/bin/env python
import base64
from pathlib import Path
from openai import OpenAI
client = OpenAI()
def main() -> None:
"""Example of OpenAI image streaming with partial images."""
stream = client.images.generate(
model="gpt-image-1",
prompt="A cute baby sea otter",
n=1,
... | 54 | 1,644 |
openai-python | examples/bedrock.py | .py | from openai import OpenAI
from openai.providers import bedrock
client = OpenAI(
provider=bedrock(
region="us-west-2",
)
)
response = client.responses.create(
model="openai.gpt-5.4",
input="Say hello!",
)
print(response.output_text)
| 16 | 259 |
openai-python | examples/uploads.py | .py | import sys
from pathlib import Path
import rich
from openai import OpenAI
# generate this file using `./generate_file.sh`
file = Path("/tmp/big_test_file.txt")
client = OpenAI()
def from_disk() -> None:
print("uploading file from disk")
upload = client.uploads.upload_file_chunked(
file=file,
... | 47 | 886 |
openai-python | examples/text_to_speech.py | .py | #!/usr/bin/env rye run python
import time
import asyncio
from openai import AsyncOpenAI
from openai.helpers import LocalAudioPlayer
# gets OPENAI_API_KEY from your environment variables
openai = AsyncOpenAI()
async def main() -> None:
start_time = time.time()
async with openai.audio.speech.with_streaming_... | 32 | 952 |
openai-python | examples/azure_ad.py | .py | import asyncio
from openai.lib.azure import AzureOpenAI, AsyncAzureOpenAI, AzureADTokenProvider, AsyncAzureADTokenProvider
scopes = "https://cognitiveservices.azure.com/.default"
# May change in the future
# https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning
api_version = "2023-... | 68 | 1,949 |
openai-python | examples/parsing_tools_stream.py | .py | from __future__ import annotations
import rich
from pydantic import BaseModel
import openai
from openai import OpenAI
class GetWeather(BaseModel):
city: str
country: str
client = OpenAI()
with client.chat.completions.stream(
model="gpt-4o-2024-08-06",
messages=[
{
"role": "us... | 39 | 948 |
openai-python | examples/parsing_tools.py | .py | from enum import Enum
from typing import List, Union
import rich
from pydantic import BaseModel
import openai
from openai import OpenAI
class Table(str, Enum):
orders = "orders"
customers = "customers"
products = "products"
class Column(str, Enum):
id = "id"
status = "status"
expected_deli... | 81 | 1,740 |
openai-python | examples/mtls_httpx_async.py | .py | #!/usr/bin/env -S rye run python
import os
import ssl
import asyncio
from openai import AsyncOpenAI, DefaultAsyncHttpxClient
async def main() -> None:
ssl_context = ssl.create_default_context(
cafile=os.environ.get("OPENAI_MTLS_CA_BUNDLE"),
)
ssl_context.load_cert_chain(
# Leaf certifica... | 37 | 1,017 |
openai-python | examples/mtls_httpx2.py | .py | #!/usr/bin/env -S rye run python
import os
import ssl
from openai import OpenAI, DefaultHttpx2Client
ssl_context = ssl.create_default_context(
cafile=os.environ.get("OPENAI_MTLS_CA_BUNDLE"),
)
ssl_context.load_cert_chain(
# Leaf certificate first; if intermediate-chain support is enabled, follow
# it wit... | 31 | 835 |
openai-python | examples/parsing.py | .py | from typing import List
import rich
from pydantic import BaseModel
from openai import OpenAI
class Step(BaseModel):
explanation: str
output: str
class MathResponse(BaseModel):
steps: List[Step]
final_answer: str
client = OpenAI()
completion = client.chat.completions.parse(
model="gpt-4o-202... | 37 | 700 |
openai-python | examples/parsing_stream.py | .py | from typing import List
import rich
from pydantic import BaseModel
from openai import OpenAI
class Step(BaseModel):
explanation: str
output: str
class MathResponse(BaseModel):
steps: List[Step]
final_answer: str
client = OpenAI()
with client.chat.completions.stream(
model="gpt-4o-2024-08-06... | 43 | 1,036 |
openai-python | examples/demo.py | .py | #!/usr/bin/env -S poetry run python
from openai import OpenAI
# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI()
# Non-streaming:
print("----- standard request -----")
completion = client.chat.completions.create(
model="gpt-5.5",
messages=[
{
"role": "user",
... | 54 | 1,204 |
openai-python | examples/module_client.py | .py | import openai
# will default to `os.environ['OPENAI_API_KEY']` if not explicitly set
openai.api_key = "..."
# all client options can be configured just like the `OpenAI` instantiation counterpart
openai.base_url = "https://..."
openai.default_headers = {"x-foo": "true"}
# all API calls work in the exact same fashion... | 26 | 659 |
openai-python | examples/picture.py | .py | #!/usr/bin/env python
from openai import OpenAI
# gets OPENAI_API_KEY from your environment variables
openai = OpenAI()
prompt = "An astronaut lounging in a tropical resort in space, pixel art"
model = "dall-e-3"
def main() -> None:
# Generate an image based on the prompt
response = openai.images.generate(... | 22 | 462 |
openai-python | examples/video.py | .py | #!/usr/bin/env -S poetry run python
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def main() -> None:
video = await client.videos.create_and_poll( # pyright: ignore[reportDeprecated]
model="sora-2",
prompt="A video of the words 'Thank you' in sparkling letters",
... | 23 | 511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.