Skip to content

Commit

Permalink
migrate openai audio api (#13557)
Browse files Browse the repository at this point in the history
for issue #13162
migrate openai audio api, as [openai v1.0.0 Migration
Guide](openai/openai-python#742)

<!-- Thank you for contributing to LangChain!

Replace this entire comment with:
  - **Description:** a description of the change, 
  - **Issue:** the issue # it fixes (if applicable),
  - **Dependencies:** any dependencies required for this change,
- **Tag maintainer:** for a quicker response, tag the relevant
maintainer (see below),
- **Twitter handle:** we announce bigger features on Twitter. If your PR
gets announced, and you'd like a mention, we'll gladly shout you out!

Please make sure your PR is passing linting and testing before
submitting. Run `make format`, `make lint` and `make test` to check this
locally.

See contribution guidelines for more information on how to write/run
tests, lint, etc:

https://github.com/langchain-ai/langchain/blob/master/.github/CONTRIBUTING.md

If you're adding a new integration, please include:
1. a test for the integration, preferably unit tests that do not rely on
network access,
2. an example notebook showing its use. It lives in `docs/extras`
directory.

If no one reviews your PR within a few days, please @-mention one of
@baskaryan, @eyurtsev, @hwchase17.
 -->

---------

Co-authored-by: Double Max <max@ground-map.com>
  • Loading branch information
redheli and Double Max committed Dec 5, 2023
1 parent abbba6c commit 74c7b79
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions libs/langchain/langchain/document_loaders/parsers/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.utils.openai import is_openai_v1

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -36,9 +37,13 @@ def lazy_parse(self, blob: Blob) -> Iterator[Document]:
"pydub package not found, please install it with " "`pip install pydub`"
)

# Set the API key if provided
if self.api_key:
openai.api_key = self.api_key
if is_openai_v1():
# api_key optional, defaults to `os.environ['OPENAI_API_KEY']`
client = openai.OpenAI(api_key=self.api_key)
else:
# Set the API key if provided
if self.api_key:
openai.api_key = self.api_key

# Audio file from disk
audio = AudioSegment.from_file(blob.path)
Expand All @@ -63,7 +68,12 @@ def lazy_parse(self, blob: Blob) -> Iterator[Document]:
attempts = 0
while attempts < 3:
try:
transcript = openai.Audio.transcribe("whisper-1", file_obj)
if is_openai_v1():
transcript = client.audio.transcriptions.create(
model="whisper-1", file=file_obj
)
else:
transcript = openai.Audio.transcribe("whisper-1", file_obj)
break
except Exception as e:
attempts += 1
Expand Down

0 comments on commit 74c7b79

Please sign in to comment.