├── .DS_Store ├── .editorconfig ├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── .travis.yml ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── README.rst ├── requirements.txt ├── requirements_dev.txt ├── setup.cfg ├── setup.py ├── tox.ini └── vapi_python ├── __init__.py ├── daily_call.py └── vapi_python.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VapiAI/client-sdk-python/ba16f2b23cd4222cdbf3348d4aab67a59bca7e4d/.DS_Store -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * Vapi Python SDK version: 2 | * Python version: 3 | * Operating System: 4 | 5 | ### Description 6 | 7 | Describe what you were trying to get done. 8 | Tell us what happened, what went wrong, and what you expected to happen. 9 | 10 | ### What I Did 11 | 12 | ``` 13 | Paste the command(s) you ran and the output. 14 | If there was a crash, please include the traceback here. 15 | ``` 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # dotenv 84 | .env 85 | 86 | # virtualenv 87 | .venv 88 | venv/ 89 | ENV/ 90 | 91 | # Spyder project settings 92 | .spyderproject 93 | .spyproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | # mkdocs documentation 99 | /site 100 | 101 | # mypy 102 | .mypy_cache/ 103 | 104 | # IDE settings 105 | .vscode/ 106 | .idea/ 107 | 108 | test.py -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.com 2 | 3 | language: python 4 | python: 5 | - 3.8 6 | - 3.7 7 | - 3.6 8 | 9 | # Command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 10 | install: 11 | - pip install -U tox-travis 12 | - pip install -r requirements.txt 13 | 14 | # Command to run tests, e.g. python setup.py test 15 | script: tox 16 | 17 | # Assuming you have installed the travis-ci CLI tool, after you 18 | # create the Github repo and add it to Travis, run the 19 | # following command to finish PyPI deployment setup: 20 | # $ travis encrypt --add deploy.password 21 | deploy: 22 | provider: pypi 23 | distributions: sdist bdist_wheel 24 | user: jordan.cde 25 | password: 26 | secure: PLEASE_REPLACE_ME 27 | on: 28 | tags: true 29 | repo: jordan.cde/vapi_python 30 | python: 3.8 31 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | History 3 | ======= 4 | 5 | 0.1.0 (2023-11-17) 6 | ------------------ 7 | 8 | * First release on PyPI. 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023, Vapi AI 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | 7 | recursive-include tests * 8 | recursive-exclude * __pycache__ 9 | recursive-exclude * *.py[co] 10 | 11 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 12 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean clean-build clean-pyc clean-test coverage dist docs help install lint lint/flake8 2 | .DEFAULT_GOAL := help 3 | 4 | define BROWSER_PYSCRIPT 5 | import os, webbrowser, sys 6 | 7 | from urllib.request import pathname2url 8 | 9 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 10 | endef 11 | export BROWSER_PYSCRIPT 12 | 13 | define PRINT_HELP_PYSCRIPT 14 | import re, sys 15 | 16 | for line in sys.stdin: 17 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 18 | if match: 19 | target, help = match.groups() 20 | print("%-20s %s" % (target, help)) 21 | endef 22 | export PRINT_HELP_PYSCRIPT 23 | 24 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 25 | 26 | help: 27 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 28 | 29 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 30 | 31 | clean-build: ## remove build artifacts 32 | rm -fr build/ 33 | rm -fr dist/ 34 | rm -fr .eggs/ 35 | find . -name '*.egg-info' -exec rm -fr {} + 36 | find . -name '*.egg' -exec rm -f {} + 37 | 38 | clean-pyc: ## remove Python file artifacts 39 | find . -name '*.pyc' -exec rm -f {} + 40 | find . -name '*.pyo' -exec rm -f {} + 41 | find . -name '*~' -exec rm -f {} + 42 | find . -name '__pycache__' -exec rm -fr {} + 43 | 44 | clean-test: ## remove test and coverage artifacts 45 | rm -fr .tox/ 46 | rm -f .coverage 47 | rm -fr htmlcov/ 48 | rm -fr .pytest_cache 49 | 50 | lint/flake8: ## check style with flake8 51 | flake8 vapi_python tests 52 | 53 | lint: lint/flake8 ## check style 54 | 55 | test: ## run tests quickly with the default Python 56 | python setup.py test 57 | 58 | test-all: ## run tests on every Python version with tox 59 | tox 60 | 61 | coverage: ## check code coverage quickly with the default Python 62 | coverage run --source vapi_python setup.py test 63 | coverage report -m 64 | coverage html 65 | $(BROWSER) htmlcov/index.html 66 | 67 | docs: ## generate Sphinx HTML documentation, including API docs 68 | rm -f docs/vapi_python.rst 69 | rm -f docs/modules.rst 70 | sphinx-apidoc -o docs/ vapi_python 71 | $(MAKE) -C docs clean 72 | $(MAKE) -C docs html 73 | $(BROWSER) docs/_build/html/index.html 74 | 75 | servedocs: docs ## compile the docs watching for changes 76 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 77 | 78 | release: dist ## package and upload a release 79 | twine upload dist/* 80 | 81 | dist: clean ## builds source and wheel package 82 | python setup.py sdist 83 | python setup.py bdist_wheel 84 | ls -l dist 85 | 86 | install: clean ## install the package to the active Python's site-packages 87 | python setup.py install 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vapi Python SDK 2 | 3 | This package lets you start Vapi calls directly in your Python application. 4 | 5 | ## Installation 6 | 7 | You can install the package via pip: 8 | 9 | ```bash 10 | pip install vapi_python 11 | ``` 12 | 13 | On Mac, you might need to install `brew install portaudio` to satisfy `pyaudio`'s dependency requirement. 14 | 15 | ## Usage 16 | 17 | First, import the Vapi class from the package: 18 | 19 | ```python 20 | from vapi_python import Vapi 21 | ``` 22 | 23 | Then, create a new instance of the Vapi class, passing your Public Key as a parameter to the constructor: 24 | 25 | ```python 26 | vapi = Vapi(api_key='your-public-key') 27 | ``` 28 | 29 | You can start a new call by calling the `start` method and passing an `assistant` object or `assistantId`. You can find the available options here: [docs.vapi.ai](https://docs.vapi.ai/api-reference/assistants/create-assistant) 30 | 31 | ```python 32 | vapi.start(assistant_id='your-assistant-id') 33 | ``` 34 | 35 | or 36 | 37 | ```python 38 | assistant = { 39 | 'firstMessage': 'Hey, how are you?', 40 | 'context': 'You are an employee at a drive thru...', 41 | 'model': 'gpt-3.5-turbo', 42 | 'voice': 'jennifer-playht', 43 | "recordingEnabled": True, 44 | "interruptionsEnabled": False 45 | } 46 | 47 | vapi.start(assistant=assistant) 48 | ``` 49 | 50 | The `start` method will initiate a new call. 51 | 52 | You can override existing assistant parameters or set variables with the `assistant_overrides` parameter. 53 | Assume the first message is `Hey, {{name}} how are you?` and you want to set the value of `name` to `John`: 54 | 55 | ```python 56 | assistant_overrides = { 57 | "recordingEnabled": False, 58 | "variableValues": { 59 | "name": "John" 60 | } 61 | } 62 | 63 | vapi.start(assistant_id='your-assistant-id', assistant_overrides=assistant_overrides) 64 | ``` 65 | 66 | You can stop the session by calling the `stop` method: 67 | 68 | ```python 69 | vapi.stop() 70 | ``` 71 | 72 | This will stop the recording and close the connection. 73 | 74 | ## License 75 | 76 | ``` 77 | MIT License 78 | 79 | Copyright (c) 2023 Vapi Labs Inc. 80 | 81 | Permission is hereby granted, free of charge, to any person obtaining a copy 82 | of this software and associated documentation files (the "Software"), to deal 83 | in the Software without restriction, including without limitation the rights 84 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 85 | copies of the Software, and to permit persons to whom the Software is 86 | furnished to do so, subject to the following conditions: 87 | 88 | The above copyright notice and this permission notice shall be included in all 89 | copies or substantial portions of the Software. 90 | 91 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 92 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 93 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 94 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 95 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 96 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 97 | SOFTWARE. 98 | ``` 99 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============== 2 | Vapi Python SDK 3 | =============== 4 | 5 | 6 | .. image:: https://img.shields.io/pypi/v/vapi_python.svg 7 | :target: https://pypi.python.org/pypi/vapi_python 8 | 9 | .. image:: https://img.shields.io/travis/jordan.cde/vapi_python.svg 10 | :target: https://travis-ci.com/jordan.cde/vapi_python 11 | 12 | .. image:: https://readthedocs.org/projects/vapi-python/badge/?version=latest 13 | :target: https://vapi-python.readthedocs.io/en/latest/?version=latest 14 | :alt: Documentation Status 15 | 16 | 17 | This package lets you start Vapi calls directly from Python. 18 | 19 | Installation 20 | ------------ 21 | 22 | You can install the package via pip: 23 | 24 | .. code-block:: bash 25 | 26 | pip install vapi_python 27 | 28 | Usage 29 | ----- 30 | 31 | First, import the Vapi class from the package: 32 | 33 | .. code-block:: python 34 | 35 | from vapi_python import Vapi 36 | 37 | Then, create a new instance of the Vapi class, passing your API Key as a parameter to the constructor: 38 | 39 | .. code-block:: python 40 | 41 | vapi = Vapi(api_key='your-api-key') 42 | 43 | You can start a new call by calling the `start` method and passing an `assistant` object or `assistantId`. You can find the available options here: `docs.vapi.ai ` 44 | 45 | .. code-block:: python 46 | 47 | vapi.start(assistant_id='your-assistant-id') 48 | 49 | or 50 | 51 | .. code-block:: python 52 | 53 | assistant = { 54 | 'firstMessage': 'Hey, how are you?', 55 | 'context': 'You are a shopping assistant...', 56 | 'model': 'gpt-3.5-turbo', 57 | 'voice': 'jennifer-playht', 58 | "recordingEnabled": True, 59 | "interruptionsEnabled": False, 60 | "functions": [ 61 | { 62 | "name": "setColor", 63 | "description": "Used to set the color", 64 | "parameters": { 65 | "type": "object", 66 | "properties": { 67 | "color": { 68 | "type": "string" 69 | } 70 | } 71 | } 72 | } 73 | ] 74 | } 75 | 76 | vapi.start(assistant=assistant) 77 | 78 | The `start` method will initiate a new call. 79 | 80 | You can override existing assistant parameters or set variables with the `assistant_overrides` parameter. 81 | Assume the first message is `Hey, {{name}} how are you?` and you want to set the value of `name` to `John`: 82 | 83 | .. code-block:: python 84 | 85 | assistant_overrides = { 86 | "recordingEnabled": False, 87 | "variableValues": { 88 | "name": "John" 89 | } 90 | } 91 | 92 | vapi.start(assistant_id='your-assistant-id', assistant_overrides=assistant_overrides) 93 | 94 | You can stop the session by calling the `stop` method: 95 | 96 | .. code-block:: python 97 | 98 | vapi.stop() 99 | 100 | This will stop the recording and close the connection. 101 | 102 | License 103 | ------- 104 | 105 | MIT License 106 | 107 | Copyright (c) 2023 Vapi Labs Inc. 108 | 109 | Permission is hereby granted, free of charge, to any person obtaining a copy 110 | of this software and associated documentation files (the "Software"), to deal 111 | in the Software without restriction, including without limitation the rights 112 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 113 | copies of the Software, and to permit persons to whom the Software is 114 | furnished to do so, subject to the following conditions: 115 | 116 | The above copyright notice and this permission notice shall be included in all 117 | copies or substantial portions of the Software. 118 | 119 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 120 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 121 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 122 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 123 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 124 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 125 | SOFTWARE. 126 | 127 | Credits 128 | ------- 129 | 130 | This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. 131 | 132 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 133 | .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage 134 | 135 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | daily-python 2 | pyaudio 3 | requests 4 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | pip==23.3 2 | bump2version==0.5.11 3 | wheel==0.38.1 4 | watchdog==0.9.0 5 | flake8==3.7.8 6 | tox==3.14.0 7 | coverage==4.5.4 8 | Sphinx==1.8.5 9 | twine==1.14.0 10 | Click==7.1.2 11 | 12 | 13 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.1.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version='{current_version}' 8 | replace = version='{new_version}' 9 | 10 | [bumpversion:file:vapi_python/__init__.py] 11 | search = __version__ = '{current_version}' 12 | replace = __version__ = '{new_version}' 13 | 14 | [bdist_wheel] 15 | universal = 1 16 | 17 | [flake8] 18 | exclude = docs 19 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """The setup script.""" 4 | 5 | from setuptools import setup, find_packages 6 | 7 | with open('README.rst') as readme_file: 8 | readme = readme_file.read() 9 | 10 | with open('HISTORY.rst') as history_file: 11 | history = history_file.read() 12 | 13 | 14 | def read_requirements(file): 15 | with open(file) as f: 16 | return f.read().splitlines() 17 | 18 | 19 | requirements = read_requirements('requirements.txt') 20 | test_requirements = read_requirements('requirements.txt') 21 | 22 | setup( 23 | author="Vapi AI", 24 | author_email='team@vapi.ai', 25 | python_requires='>=3.6', 26 | classifiers=[ 27 | 'Development Status :: 2 - Pre-Alpha', 28 | 'Intended Audience :: Developers', 29 | 'License :: OSI Approved :: MIT License', 30 | 'Natural Language :: English', 31 | 'Programming Language :: Python :: 3', 32 | 'Programming Language :: Python :: 3.6', 33 | 'Programming Language :: Python :: 3.7', 34 | 'Programming Language :: Python :: 3.8', 35 | ], 36 | description="This package lets you start Vapi calls directly from Python.", 37 | entry_points={ 38 | 'console_scripts': [ 39 | 'vapi_python=vapi_python.cli:main', 40 | ], 41 | }, 42 | install_requires=requirements, 43 | license="MIT license", 44 | long_description=readme + '\n\n' + history, 45 | include_package_data=True, 46 | keywords='vapi_python', 47 | name='vapi_python', 48 | packages=find_packages(include=['vapi_python', 'vapi_python.*']), 49 | test_suite='tests', 50 | tests_require=test_requirements, 51 | url='https://github.com/jordan.cde/vapi_python', 52 | version='0.1.9', 53 | zip_safe=False, 54 | ) 55 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py36, py37, py38, flake8 3 | 4 | [travis] 5 | python = 6 | 3.8: py38 7 | 3.7: py37 8 | 3.6: py36 9 | 10 | [testenv:flake8] 11 | basepython = python 12 | deps = flake8 13 | commands = flake8 vapi_python tests 14 | 15 | [testenv] 16 | setenv = 17 | PYTHONPATH = {toxinidir} 18 | 19 | commands = python setup.py test 20 | -------------------------------------------------------------------------------- /vapi_python/__init__.py: -------------------------------------------------------------------------------- 1 | """Top-level package for Vapi Python SDK.""" 2 | 3 | from .vapi_python import Vapi 4 | 5 | __author__ = """Vapi AI""" 6 | __email__ = 'team@vapi.ai' 7 | __version__ = '0.1.0' 8 | -------------------------------------------------------------------------------- /vapi_python/daily_call.py: -------------------------------------------------------------------------------- 1 | import daily 2 | import threading 3 | import pyaudio 4 | import json 5 | 6 | SAMPLE_RATE = 16000 7 | NUM_CHANNELS = 1 8 | CHUNK_SIZE = 640 9 | 10 | 11 | def is_playable_speaker(participant): 12 | is_speaker = "userName" in participant["info"] and participant["info"]["userName"] == "Vapi Speaker" 13 | mic = participant["media"]["microphone"] 14 | is_subscribed = mic["subscribed"] == "subscribed" 15 | is_playable = mic["state"] == "playable" 16 | return is_speaker and is_subscribed and is_playable 17 | 18 | 19 | class DailyCall(daily.EventHandler): 20 | def __init__(self): 21 | daily.Daily.init() 22 | 23 | self.__audio_interface = pyaudio.PyAudio() 24 | 25 | self.__input_audio_stream = self.__audio_interface.open( 26 | format=pyaudio.paInt16, 27 | channels=NUM_CHANNELS, 28 | rate=SAMPLE_RATE, 29 | input=True, 30 | frames_per_buffer=CHUNK_SIZE, 31 | ) 32 | 33 | self.__output_audio_stream = self.__audio_interface.open( 34 | format=pyaudio.paInt16, 35 | channels=NUM_CHANNELS, 36 | rate=SAMPLE_RATE, 37 | output=True, 38 | frames_per_buffer=CHUNK_SIZE 39 | ) 40 | 41 | self.__mic_device = daily.Daily.create_microphone_device( 42 | "my-mic", 43 | sample_rate=SAMPLE_RATE, 44 | channels=NUM_CHANNELS 45 | ) 46 | 47 | self.__speaker_device = daily.Daily.create_speaker_device( 48 | "my-speaker", 49 | sample_rate=SAMPLE_RATE, 50 | channels=NUM_CHANNELS 51 | ) 52 | daily.Daily.select_speaker_device("my-speaker") 53 | 54 | self.__call_client = daily.CallClient(event_handler=self) 55 | 56 | self.__call_client.update_inputs({ 57 | "camera": False, 58 | "microphone": { 59 | "isEnabled": True, 60 | "settings": { 61 | "deviceId": "my-mic", 62 | "customConstraints": { 63 | "autoGainControl": {"exact": True}, 64 | "noiseSuppression": {"exact": True}, 65 | "echoCancellation": {"exact": True}, 66 | } 67 | } 68 | } 69 | }) 70 | 71 | self.__call_client.update_subscription_profiles({ 72 | "base": { 73 | "camera": "unsubscribed", 74 | "microphone": "subscribed" 75 | } 76 | }) 77 | 78 | self.__participants = dict(self.__call_client.participants()) 79 | del self.__participants["local"] 80 | 81 | self.__app_quit = False 82 | self.__app_error = None 83 | self.__app_joined = False 84 | self.__app_inputs_updated = False 85 | 86 | self.__start_event = threading.Event() 87 | self.__receive_bot_audio_thread = threading.Thread( 88 | target=self.receive_bot_audio) 89 | self.__send_user_audio_thread = threading.Thread( 90 | target=self.send_user_audio) 91 | 92 | self.__receive_bot_audio_thread.start() 93 | self.__send_user_audio_thread.start() 94 | 95 | def on_inputs_updated(self, inputs): 96 | self.__app_inputs_updated = True 97 | self.maybe_start() 98 | 99 | def on_joined(self, data, error): 100 | if error: 101 | print(f"Unable to join call: {error}") 102 | self.__app_error = error 103 | else: 104 | self.__app_joined = True 105 | print("Joined call!") 106 | self.maybe_start() 107 | 108 | def on_participant_joined(self, participant): 109 | self.__participants[participant["id"]] = participant 110 | 111 | def on_participant_left(self, participant, _): 112 | del self.__participants[participant["id"]] 113 | self.leave() 114 | 115 | def on_participant_updated(self, participant): 116 | self.__participants[participant["id"]] = participant 117 | if is_playable_speaker(participant): 118 | self.__call_client.send_app_message("playable") 119 | 120 | def join(self, meeting_url): 121 | self.__call_client.join(meeting_url, completion=self.on_joined) 122 | 123 | def leave(self): 124 | self.__app_quit = True 125 | self.__receive_bot_audio_thread.join() 126 | self.__send_user_audio_thread.join() 127 | self.__call_client.leave() 128 | 129 | def maybe_start(self): 130 | if self.__app_error: 131 | self.__start_event.set() 132 | 133 | if self.__app_inputs_updated and self.__app_joined: 134 | self.__start_event.set() 135 | 136 | def send_user_audio(self): 137 | self.__start_event.wait() 138 | 139 | if self.__app_error: 140 | print(f"Unable to receive mic audio!") 141 | return 142 | 143 | while not self.__app_quit: 144 | buffer = self.__input_audio_stream.read( 145 | CHUNK_SIZE, exception_on_overflow=False) 146 | if len(buffer) > 0: 147 | try: 148 | self.__mic_device.write_frames(buffer) 149 | except Exception as e: 150 | print(e) 151 | 152 | def receive_bot_audio(self): 153 | self.__start_event.wait() 154 | 155 | if self.__app_error: 156 | print(f"Unable to receive bot audio!") 157 | return 158 | 159 | while not self.__app_quit: 160 | buffer = self.__speaker_device.read_frames(CHUNK_SIZE) 161 | 162 | if len(buffer) > 0: 163 | self.__output_audio_stream.write(buffer, CHUNK_SIZE) 164 | 165 | def send_app_message(self, message): 166 | """ 167 | Send an application message to the assistant. 168 | 169 | :param message: The message to send (expects a dictionary). 170 | """ 171 | try: 172 | serialized_message = json.dumps(message) 173 | self.__call_client.send_app_message(serialized_message) 174 | except Exception as e: 175 | print(f"Failed to send app message: {e}") 176 | -------------------------------------------------------------------------------- /vapi_python/vapi_python.py: -------------------------------------------------------------------------------- 1 | from daily import * 2 | import requests 3 | from .daily_call import DailyCall 4 | 5 | SAMPLE_RATE = 16000 6 | CHANNELS = 1 7 | 8 | 9 | def create_web_call(api_url, api_key, payload): 10 | url = f"{api_url}/call/web" 11 | headers = { 12 | 'Authorization': 'Bearer ' + api_key, 13 | 'Content-Type': 'application/json' 14 | } 15 | response = requests.post(url, headers=headers, json=payload) 16 | data = response.json() 17 | if response.status_code == 201: 18 | call_id = data.get('id') 19 | web_call_url = data.get('webCallUrl') 20 | return call_id, web_call_url 21 | else: 22 | raise Exception(f"Error: {data['message']}") 23 | 24 | 25 | class Vapi: 26 | def __init__(self, *, api_key, api_url="https://api.vapi.ai"): 27 | self.api_key = api_key 28 | self.api_url = api_url 29 | 30 | def start( 31 | self, 32 | *, 33 | assistant_id=None, 34 | assistant=None, 35 | assistant_overrides=None, 36 | squad_id=None, 37 | squad=None, 38 | ): 39 | # Start a new call 40 | if assistant_id: 41 | payload = {'assistantId': assistant_id, 'assistantOverrides': assistant_overrides} 42 | elif assistant: 43 | payload = {'assistant': assistant, 'assistantOverrides': assistant_overrides} 44 | elif squad_id: 45 | payload = {'squadId': squad_id} 46 | elif squad: 47 | payload = {'squad': squad} 48 | else: 49 | raise Exception("Error: No assistant specified.") 50 | 51 | call_id, web_call_url = create_web_call( 52 | self.api_url, self.api_key, payload) 53 | 54 | if not web_call_url: 55 | raise Exception("Error: Unable to create call.") 56 | 57 | print('Joining call... ' + call_id) 58 | 59 | self.__client = DailyCall() 60 | self.__client.join(web_call_url) 61 | 62 | def stop(self): 63 | self.__client.leave() 64 | self.__client = None 65 | 66 | def send(self, message): 67 | """ 68 | Send a generic message to the assistant. 69 | 70 | :param message: A dictionary containing the message type and content. 71 | """ 72 | if not self.__client: 73 | raise Exception("Call not started. Please start the call first.") 74 | 75 | # Check message format here instead of serialization 76 | if not isinstance(message, dict) or 'type' not in message: 77 | raise ValueError("Invalid message format.") 78 | 79 | try: 80 | self.__client.send_app_message(message) # Send dictionary directly 81 | except Exception as e: 82 | print(f"Failed to send message: {e}") 83 | 84 | def add_message(self, role, content): 85 | """ 86 | method to send text messages with specific parameters. 87 | """ 88 | message = { 89 | 'type': 'add-message', 90 | 'message': { 91 | 'role': role, 92 | 'content': content 93 | } 94 | } 95 | self.send(message) 96 | --------------------------------------------------------------------------------