├── chatgpt_ros ├── resource │ └── chatgpt_ros ├── chatgpt_ros │ ├── __init__.py │ ├── chatgpt_ros.py │ ├── chatgpt_ros_service_client.py │ ├── chatgpt_ros_service_server.py │ └── chatgpt.py ├── param │ └── param.yaml ├── setup.cfg ├── package.xml ├── setup.py └── test │ ├── test_pep257.py │ ├── test_flake8.py │ ├── test_copyright.py │ └── test_chatgpt.py ├── chatgpt_ros_interfaces ├── srv │ └── ChatGptService.srv ├── CMakeLists.txt └── package.xml ├── .github └── workflows │ └── foxy.yaml ├── README.md ├── .gitignore └── LICENSE /chatgpt_ros/resource/chatgpt_ros: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /chatgpt_ros/chatgpt_ros/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /chatgpt_ros_interfaces/srv/ChatGptService.srv: -------------------------------------------------------------------------------- 1 | string text 2 | int64 length 3 | --- 4 | string response -------------------------------------------------------------------------------- /chatgpt_ros/param/param.yaml: -------------------------------------------------------------------------------- 1 | chatgpt_service_server: 2 | ros__parameters: 3 | system_role: 4 | use_system_role : false 5 | content : "You have to return JSON format" 6 | assistant_role: 7 | hold_passed_response : false 8 | num_passed_response : 5 9 | -------------------------------------------------------------------------------- /.github/workflows/foxy.yaml: -------------------------------------------------------------------------------- 1 | name: ros2_humble 2 | on: [push, pull_request] 3 | jobs: 4 | workflows-test: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checking out 8 | uses: actions/checkout@v2.3.4 9 | - name: Build and test 10 | uses: OUXT-Polaris/ros2-ci@master 11 | with: 12 | apt-packages: python3-requests 13 | ros2-distro: foxy 14 | -------------------------------------------------------------------------------- /chatgpt_ros/setup.cfg: -------------------------------------------------------------------------------- 1 | [develop] 2 | script_dir=$base/lib/chatgpt_ros 3 | [install] 4 | install_scripts=$base/lib/chatgpt_ros 5 | [flake8] 6 | extend-ignore = B902,C816,D100,D101,D102,D103,D104,D105,D106,D107,D203,D212,D404,I202,CNL100,E203,E501,Q000 7 | import-order-style = pep8 8 | max-line-length = 150 9 | show-source = true 10 | statistics = true 11 | 12 | [pycodestyle] 13 | ignore = '' 14 | max-line-length = 120 15 | -------------------------------------------------------------------------------- /chatgpt_ros_interfaces/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.8) 2 | project(chatgpt_ros_interfaces) 3 | 4 | if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") 5 | add_compile_options(-Wall -Wextra -Wpedantic) 6 | endif() 7 | 8 | # find dependencies 9 | find_package(ament_cmake REQUIRED) 10 | find_package(rosidl_default_generators REQUIRED) 11 | 12 | set(srv_files 13 | "srv/ChatGptService.srv" 14 | ) 15 | rosidl_generate_interfaces(${PROJECT_NAME} 16 | ${srv_files} 17 | ) 18 | ament_export_dependencies(rosidl_default_runtime) 19 | 20 | ament_package() 21 | -------------------------------------------------------------------------------- /chatgpt_ros_interfaces/package.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | chatgpt_ros_interfaces 5 | 0.0.0 6 | TODO: Package description 7 | koichi 8 | TODO: License declaration 9 | 10 | ament_cmake 11 | rosidl_default_generators 12 | rosidl_default_runtime 13 | rosidl_interface_packages 14 | 15 | 16 | ament_cmake 17 | 18 | 19 | -------------------------------------------------------------------------------- /chatgpt_ros/package.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | chatgpt_ros 5 | 0.0.0 6 | TODO: Package description 7 | koichi 8 | TODO: License declaration 9 | 10 | rclpy 11 | ament_flake8 12 | 13 | ament_copyright 14 | ament_flake8 15 | ament_pep257 16 | python3-pytest 17 | 18 | 19 | ament_python 20 | 21 | 22 | -------------------------------------------------------------------------------- /chatgpt_ros/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | package_name = 'chatgpt_ros' 4 | 5 | setup( 6 | name=package_name, 7 | version='0.0.0', 8 | packages=[package_name], 9 | data_files=[ 10 | ('share/ament_index/resource_index/packages', 11 | ['resource/' + package_name]), 12 | ], 13 | install_requires=['setuptools'], 14 | zip_safe=True, 15 | maintainer='koichi', 16 | maintainer_email='k.koichiro0222@gmail.com', 17 | description='ChattGPT API ROS2 wrapper', 18 | license='Apache 2.0', 19 | tests_require=['pytest'], 20 | entry_points={ 21 | 'console_scripts': [ 22 | 'chatgpt_ros = ' + package_name + '.chatgpt_ros:main', 23 | 'chatgpt_ros_service = ' + package_name + '.chatgpt_ros_service_server:main', 24 | 'client_sample = ' + package_name + '.chatgpt_ros_service_client:main', 25 | ], 26 | }, 27 | ) 28 | -------------------------------------------------------------------------------- /chatgpt_ros/test/test_pep257.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Open Source Robotics Foundation, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from ament_pep257.main import main 16 | import pytest 17 | 18 | 19 | @pytest.mark.skip() 20 | @pytest.mark.linter 21 | @pytest.mark.pep257 22 | def test_pep257(): 23 | rc = main(argv=[".", "test"]) 24 | assert rc == 0, "Found code style errors / warnings" 25 | -------------------------------------------------------------------------------- /chatgpt_ros/test/test_flake8.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Open Source Robotics Foundation, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from ament_flake8.main import main_with_errors 16 | import pytest 17 | 18 | 19 | @pytest.mark.flake8 20 | @pytest.mark.linter 21 | def test_flake8(): 22 | rc, errors = main_with_errors(argv=[]) 23 | assert rc == 0, "Found %d code style errors / warnings:\n" % len( 24 | errors 25 | ) + "\n".join(errors) 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # chatgpt_ros 2 | ROS wrapper for ChatGPT API 3 | 4 | 日本語でQiitaの記事を投稿しました。併せてご覧ください。 5 | Below link is about this repository, in Janapese. 6 | https://qiita.com/koichi_baseball/items/0a29bbe846f9e3fdfd5a 7 | 8 | ## Dependencies 9 | Python requests modeule. 10 | 11 | ``` 12 | $ sudo apt-get install python3-requests 13 | ``` 14 | 15 | ## Setup 16 | You have to set ChatGPT API for environment value of `ChatGPT_API`. 17 | 18 | ## Usage 19 | ### Publish and Subscribe 20 | `chatgpt_ros` node subscribe ` /input_text` topic and publish `/output_text` topic. 21 | 22 | ### Run 23 | 24 | ``` 25 | $ ros2 run chatgpt_ros chatgpt_ros 26 | ``` 27 | 28 | ## ROS Service 29 | `chatgpt_ros_service` node is the server of ros service of `chatgpt_service`. 30 | You can see srv file is in `chatgpt_ros_interfaces/srv`. 31 | 32 | ### Run 33 | 34 | ``` 35 | $ ros2 run chatgpt_ros chatgpt_ros_service 36 | ``` 37 | 38 | ## Referene 39 | This node was created based on a question to ChatGPT (creating a ROS node using the ChatGPT API). 40 | -------------------------------------------------------------------------------- /chatgpt_ros/test/test_copyright.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Open Source Robotics Foundation, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from ament_copyright.main import main 16 | import pytest 17 | 18 | 19 | # Remove the `skip` decorator once the source file(s) have a copyright header 20 | @pytest.mark.skip( 21 | reason="No copyright header has been placed in the generated source file." 22 | ) 23 | @pytest.mark.copyright 24 | @pytest.mark.linter 25 | def test_copyright(): 26 | rc = main(argv=[".", "test"]) 27 | assert rc == 0, "Found errors" 28 | -------------------------------------------------------------------------------- /chatgpt_ros/chatgpt_ros/chatgpt_ros.py: -------------------------------------------------------------------------------- 1 | import rclpy 2 | from rclpy.node import Node 3 | from std_msgs.msg import String 4 | from chatgpt_ros import chatgpt 5 | 6 | import os 7 | 8 | 9 | class ChatGPTNode(Node): 10 | def __init__(self): 11 | """ 12 | constructer 13 | """ 14 | super().__init__("chatgpt_node") 15 | self.sub = self.create_subscription( 16 | String, "/input_text", self.listener_callback, 10 17 | ) 18 | self.pub = self.create_publisher(String, "/output_text", 10) 19 | self.chatgpt = chatgpt.ChatGPT(api_key=os.environ["ChatGPT_API"]) 20 | 21 | def listener_callback(self, msg): 22 | """ 23 | Subscribe callback function 24 | 25 | Parameters 26 | ---------- 27 | msg : std_msgs.msg.String 28 | subscribe message 29 | """ 30 | self.get_logger().info(f"Subscribed Text: {msg.data}") 31 | prompt = msg.data 32 | response = self.chatgpt.generate_text(prompt) 33 | self.get_logger().info(response) 34 | output_msg = String() 35 | output_msg.data = response 36 | self.pub.publish(output_msg) 37 | 38 | 39 | def main(args=None): 40 | """ 41 | main function 42 | """ 43 | rclpy.init(args=args) 44 | node = ChatGPTNode() 45 | rclpy.spin(node) 46 | rclpy.shutdown() 47 | 48 | 49 | if __name__ == "__main__": 50 | main() 51 | -------------------------------------------------------------------------------- /chatgpt_ros/chatgpt_ros/chatgpt_ros_service_client.py: -------------------------------------------------------------------------------- 1 | import rclpy 2 | from chatgpt_ros_interfaces.srv import ChatGptService 3 | 4 | 5 | def main(args=None): 6 | """ 7 | sample service client 8 | """ 9 | rclpy.init(args=args) 10 | 11 | node = rclpy.create_node("chat_gpt_service_client") 12 | 13 | client = node.create_client(ChatGptService, "chatgpt_service") 14 | while not client.wait_for_service(timeout_sec=1.0): 15 | node.get_logger().info("Waiting for service") 16 | 17 | node.get_logger().info( 18 | 'Please enter your prompt for ChatGPT API. \ 19 | If you want to exit, please enter "quit"' 20 | ) 21 | while True: 22 | request = ChatGptService.Request() 23 | prompt = input(">") 24 | if prompt == "quit": 25 | node.get_logger().info("Exit") 26 | break 27 | if len(prompt) == 0: 28 | continue 29 | request.text = prompt 30 | request.length = 50 31 | 32 | future = client.call_async(request) 33 | rclpy.spin_until_future_complete(node, future) 34 | response = future.result() 35 | 36 | if response is not None: 37 | print(f"Response: {response.response}") 38 | else: 39 | node.get_logger().info("Service call failed") 40 | 41 | node.destroy_node() 42 | rclpy.shutdown() 43 | 44 | 45 | if __name__ == "__main__": 46 | main() 47 | -------------------------------------------------------------------------------- /.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 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /chatgpt_ros/test/test_chatgpt.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import requests 3 | from unittest import mock 4 | from chatgpt_ros.chatgpt import ChatGPT 5 | 6 | 7 | @pytest.fixture 8 | def chat_gpt(): 9 | return ChatGPT(api_key="TEST_API_KEY") 10 | 11 | 12 | @mock.patch.object(requests, "post") 13 | def test_generate_text(mock_post, chat_gpt): 14 | mock_response_json = { 15 | "choices": [ 16 | { 17 | "message": {"content": "This is a test response."}, 18 | "index": 0, 19 | "logprobs": None, 20 | "finish_reason": "stop", 21 | } 22 | ], 23 | "created": "2022-03-14T01:23:45.678901Z", 24 | "model": "text-davinci-002", 25 | } 26 | mock_post.return_value.json.return_value = mock_response_json 27 | assert ( 28 | chat_gpt.generate_text("This is a test prompt.") == "This is a test response." 29 | ) 30 | mock_post.assert_called_once_with( 31 | "https://api.openai.com/v1/chat/completions", 32 | headers={ 33 | "Content-Type": "application/json", 34 | "Authorization": "Bearer TEST_API_KEY", 35 | }, 36 | json={ 37 | "model": "gpt-3.5-turbo", 38 | "messages": [{"role": "user", "content": "This is a test prompt."}], 39 | "max_tokens": 50, 40 | "temperature": 0.5, 41 | "n": 1, 42 | "stop": ".", 43 | }, 44 | ) 45 | 46 | 47 | def test_set_assitant_content(chat_gpt): 48 | chat_gpt.num_hold_pass_res = 2 49 | chat_gpt.set_assitant_content("This is a test assistant content.") 50 | assert chat_gpt.assistant_list == [ 51 | {"role": "assistant", "content": "This is a test assistant content."} 52 | ] 53 | chat_gpt.set_assitant_content("This is another test assistant content.") 54 | assert chat_gpt.assistant_list == [ 55 | {"role": "assistant", "content": "This is a test assistant content."}, 56 | {"role": "assistant", "content": "This is another test assistant content."}, 57 | ] 58 | chat_gpt.set_assitant_content("This is a third test assistant content.") 59 | assert chat_gpt.assistant_list == [ 60 | {"role": "assistant", "content": "This is another test assistant content."}, 61 | {"role": "assistant", "content": "This is a third test assistant content."}, 62 | ] 63 | 64 | 65 | def test_set_system_content(chat_gpt): 66 | chat_gpt.set_system_content("This is a test system message.") 67 | assert chat_gpt.role_system == { 68 | "role": "system", 69 | "content": "This is a test system message.", 70 | } 71 | 72 | 73 | def test_set_assitant(chat_gpt): 74 | chat_gpt.set_assitant = True 75 | assert chat_gpt.set_assitant is True 76 | -------------------------------------------------------------------------------- /chatgpt_ros/chatgpt_ros/chatgpt_ros_service_server.py: -------------------------------------------------------------------------------- 1 | import rclpy 2 | from rclpy.node import Node 3 | from chatgpt_ros import chatgpt 4 | from chatgpt_ros_interfaces.srv import ChatGptService 5 | 6 | import os 7 | 8 | 9 | class ChatGptServiceServer(Node): 10 | def __init__(self) -> None: 11 | """ 12 | constructer 13 | """ 14 | super().__init__("chatgpt_service_server") 15 | self.srv = self.create_service( 16 | ChatGptService, "chatgpt_service", self.gpt_service_callback 17 | ) 18 | self.gpt = chatgpt.ChatGPT(api_key=os.environ["ChatGPT_API"]) 19 | 20 | self.init_param() 21 | 22 | def init_param(self): 23 | self.declare_parameter("system_role.use_system_role", False) 24 | self.declare_parameter("system_role.content", "") 25 | self.declare_parameter("assistant_role.hold_passed_response", False) 26 | self.declare_parameter("assistant_role.num_passed_response", 0) 27 | 28 | use_system_role: bool = ( 29 | self.get_parameter("system_role.use_system_role") 30 | .get_parameter_value() 31 | .bool_value 32 | ) 33 | system_content: str = ( 34 | self.get_parameter("system_role.content").get_parameter_value().string_value 35 | ) 36 | 37 | hold_passed_response: bool = ( 38 | self.get_parameter("assistant_role.hold_passed_response") 39 | .get_parameter_value() 40 | .bool_value 41 | ) 42 | num_passed_response: int = ( 43 | self.get_parameter("assistant_role.num_passed_response") 44 | .get_parameter_value() 45 | .integer_value 46 | ) 47 | 48 | if use_system_role: 49 | self.gpt.set_system_content(system_content) 50 | 51 | if hold_passed_response: 52 | self.gpt.num_hold_pass_res = num_passed_response 53 | 54 | def gpt_service_callback( 55 | self, request: ChatGptService.Request, response: ChatGptService.Response 56 | ) -> ChatGptService.Response: 57 | """ 58 | Service callback function 59 | 60 | Parameters 61 | ---------- 62 | requests : ChatGptService.requests 63 | requests for ros service 64 | response : ChatGptService.response 65 | response for ros service 66 | """ 67 | text: str = request.text 68 | length: str = request.length 69 | response.response = self.gpt.generate_text(text, length) 70 | return response 71 | 72 | 73 | def main(args=None): 74 | """ 75 | main function 76 | """ 77 | rclpy.init(args=args) 78 | node = ChatGptServiceServer() 79 | rclpy.spin(node) 80 | rclpy.shutdown() 81 | -------------------------------------------------------------------------------- /chatgpt_ros/chatgpt_ros/chatgpt.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | 4 | class ChatGPT: 5 | def __init__(self, api_key: str) -> None: 6 | """ 7 | Constructer 8 | 9 | Parameters 10 | ---------- 11 | api_key : str 12 | API key for OpenAI 13 | """ 14 | self.api_key: str = api_key 15 | self.endpoint: str = "https://api.openai.com/v1/chat/completions" 16 | 17 | self.role_system: dict = {"role": "system", "content": None} 18 | self.past_content_list: list = [] 19 | self.num_hold_pass_res: int = 0 20 | self.set_past: bool = False 21 | self.set_system: bool = False 22 | 23 | def set_past_content(self, u_content: str, a_content: str) -> None: 24 | """ 25 | Set the assistant content of message for the ChatGPT API. 26 | Parameters 27 | ---------- 28 | u_content : str 29 | The prompt of the message to set for the past prompt. 30 | a_content : str 31 | The content of the message to set for the assistant. 32 | """ 33 | assistant: dict = {"role": "assistant", "content": a_content} 34 | prompt: dict = {"role": "user", "content": u_content} 35 | self.past_content_list.append(prompt) 36 | self.past_content_list.append(assistant) 37 | diff_num: int = len(self.past_content_list) / 2 - self.num_hold_pass_res 38 | if diff_num > 0: 39 | for _ in range(diff_num): 40 | self.past_content_list.pop(0) 41 | self.set_past = True 42 | 43 | def set_system_content(self, content): 44 | """ 45 | Set the system content of message for the ChatGPT API. 46 | 47 | Parameters 48 | ---------- 49 | content : str 50 | The content of the message to set for the system. 51 | """ 52 | self.role_system["content"] = content 53 | self.set_system = True 54 | 55 | def generate_text(self, prompt: str, length: int = 50) -> str: 56 | """ 57 | Generates text response from ChatGPT API given a prompt. 58 | 59 | Parameters 60 | ---------- 61 | prompt : str 62 | The prompt message to initiate the conversation with ChatGPT API. 63 | 64 | length : int, optional 65 | The maximum number of tokens to generate in the response message. 66 | Default is 50. 67 | 68 | Returns 69 | ------- 70 | str 71 | The generated response text from ChatGPT API. 72 | 73 | Raises 74 | ------ 75 | requests.exceptions.HTTPError 76 | If the request to ChatGPT API returns an error status code. 77 | """ 78 | messages: list[dict] = [] 79 | if self.set_system: 80 | messages.append(self.role_system) 81 | if self.set_past: 82 | for past in self.past_content_list: 83 | messages.append(past) 84 | messages.append({"role": "user", "content": prompt}) 85 | headers: dict = { 86 | "Content-Type": "application/json", 87 | "Authorization": f"Bearer {self.api_key}", 88 | } 89 | payload: dict = { 90 | "model": "gpt-3.5-turbo", 91 | "messages": messages, 92 | "max_tokens": length, 93 | "temperature": 0.5, 94 | "n": 1, 95 | "stop": ".", 96 | } 97 | print("message : ", messages) 98 | try: 99 | response = requests.post( 100 | self.endpoint, headers=headers, json=payload, timeout=(3.0, 7.5) 101 | ) 102 | response.raise_for_status() 103 | except requests.exceptions.HTTPError as e: 104 | print("HTTP Error!", e) 105 | result_content = str(e) 106 | else: 107 | result: dict = response.json() 108 | print("result : ", result) 109 | result_content: str = result["choices"][0]["message"]["content"] 110 | self.set_past_content(prompt, result_content) 111 | return result_content 112 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------