Skip to content
This repository has been archived by the owner on Nov 3, 2024. It is now read-only.

Commit

Permalink
[HN-19/HN-50] feat: add API version in client constructor (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
ToJen authored May 28, 2024
1 parent 9c10e04 commit 414f98a
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 49 deletions.
15 changes: 9 additions & 6 deletions hive_agent_client/chat/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import os
import sys


def get_log_level():
HIVE_AGENT_LOG_LEVEL = os.getenv('HIVE_AGENT_LOG_LEVEL', 'INFO').upper()
return getattr(logging, HIVE_AGENT_LOG_LEVEL, logging.INFO)
HIVE_AGENT_LOG_LEVEL = os.getenv('HIVE_AGENT_LOG_LEVEL', 'INFO').upper()
return getattr(logging, HIVE_AGENT_LOG_LEVEL, logging.INFO)


logging.basicConfig(stream=sys.stdout, level=get_log_level())
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
Expand All @@ -14,7 +16,6 @@ def get_log_level():
logger.setLevel(get_log_level())



async def send_chat_message(http_client: httpx.AsyncClient, base_url: str, content: str) -> str:
"""
Sends a chat message to the Hive Agent API and returns the response.
Expand All @@ -30,7 +31,7 @@ async def send_chat_message(http_client: httpx.AsyncClient, base_url: str, conte
if not content.strip():
raise ValueError("Content must not be empty")

endpoint = "/api/chat"
endpoint = "/chat"
url = f"{base_url}{endpoint}"
payload = {
"messages": [{
Expand All @@ -46,8 +47,10 @@ async def send_chat_message(http_client: httpx.AsyncClient, base_url: str, conte
logger.debug(f"Response from chat message {content}: {response.text}")
return response.text
except httpx.HTTPStatusError as e:
logging.error(f"HTTP error occurred when sending message to {url}: {e.response.status_code} - {e.response.text}")
raise Exception(f"HTTP error occurred when sending message to the chat API: {e.response.status_code} - {e.response.text}")
logging.error(
f"HTTP error occurred when sending message to {url}: {e.response.status_code} - {e.response.text}")
raise Exception(
f"HTTP error occurred when sending message to the chat API: {e.response.status_code} - {e.response.text}")
except httpx.RequestError as e:
logging.error(f"Request error occurred when sending message to {url}: {e}")
raise Exception(f"Request error occurred when sending message to the chat API: {e}")
Expand Down
10 changes: 7 additions & 3 deletions hive_agent_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,17 @@ class HiveAgentClient:
Client for interacting with a Hive Agent's API.
"""

def __init__(self, base_url: str):
def __init__(self, base_url: str, version: str = "v1"):
"""
Initializes the HiveAgentClient with the given base URL.
Initializes the HiveAgentClient with the given base URL and version.
:param base_url: The base URL of the Hive Agent API.
:param version: The version of the Hive Agent API.
"""
self.base_url = base_url
if base_url.endswith('/'):
base_url = base_url[:-1]

self.base_url = f"{base_url}/{version}"
self.http_client = httpx.AsyncClient()

async def chat(self, content: str) -> str:
Expand Down
4 changes: 2 additions & 2 deletions tests/chat/test_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ async def test_send_chat_message_success():
mock_response.text = "Hello, world!"
mock_client.post.return_value = mock_response

base_url = "http://example.com"
base_url = "http://example.com/api/v1"
content = "Hello, how are you?"

result = await send_chat_message(mock_client, base_url, content)

assert result == "Hello, world!"
mock_client.post.assert_called_once_with(
"http://example.com/api/chat",
"http://example.com/api/v1/chat",
json={"messages": [{"role": "user", "content": content}]}
)

Expand Down
73 changes: 37 additions & 36 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

from hive_agent_client.client import HiveAgentClient

base_url = "http://example.com"
base_url = "http://example.com/api"
version = "v1"


def check_response(response: int) -> int:
Expand All @@ -33,9 +34,9 @@ async def test_chat_success():
expected_response = "Response from chat"

with respx.mock() as mock:
mock.post(f"{base_url}/api/chat").mock(return_value=httpx.Response(200, text=expected_response))
mock.post(f"{base_url}/v1/chat").mock(return_value=httpx.Response(200, text=expected_response))

client = HiveAgentClient(base_url)
client = HiveAgentClient(base_url, version)
response = await client.chat(content)
assert response == expected_response

Expand All @@ -45,7 +46,7 @@ async def test_chat_failure():
content = "Hello"

with respx.mock() as mock:
mock.post(f"{base_url}/api/chat").mock(return_value=httpx.Response(400))
mock.post(f"{base_url}/v1/chat").mock(return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
with pytest.raises(Exception) as excinfo:
Expand All @@ -60,7 +61,7 @@ async def test_create_table_success():
expected_response = {"message": f"Table {table_name} created successfully."}

with respx.mock() as mock:
mock.post(f"{base_url}/database/create-table", json={"table_name": table_name, "columns": columns}).mock(
mock.post(f"{base_url}/v1/database/create-table", json={"table_name": table_name, "columns": columns}).mock(
return_value=httpx.Response(200, json=expected_response))

client = HiveAgentClient(base_url)
Expand All @@ -74,7 +75,7 @@ async def test_create_table_failure():
columns = {"id": "Integer", "name": "String"}

with respx.mock() as mock:
mock.post(f"{base_url}/database/create-table", json={"table_name": table_name, "columns": columns}).mock(
mock.post(f"{base_url}/v1/database/create-table", json={"table_name": table_name, "columns": columns}).mock(
return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
Expand All @@ -90,7 +91,7 @@ async def test_insert_data_success():
expected_response = {"message": "Data inserted successfully.", "id": 1}

with respx.mock() as mock:
mock.post(f"{base_url}/database/insert-data", json={"table_name": table_name, "data": data}).mock(
mock.post(f"{base_url}/v1/database/insert-data", json={"table_name": table_name, "data": data}).mock(
return_value=httpx.Response(200, json=expected_response))

client = HiveAgentClient(base_url)
Expand All @@ -104,7 +105,7 @@ async def test_insert_data_failure():
data = {"name": "Test"}

with respx.mock() as mock:
mock.post(f"{base_url}/database/insert-data", json={"table_name": table_name, "data": data}).mock(
mock.post(f"{base_url}/v1/database/insert-data", json={"table_name": table_name, "data": data}).mock(
return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
Expand All @@ -120,7 +121,7 @@ async def test_read_data_success():
expected_response = [{"id": 1, "name": "Test"}]

with respx.mock() as mock:
mock.post(f"{base_url}/database/read-data", json={"table_name": table_name, "filters": filters}).mock(
mock.post(f"{base_url}/v1/database/read-data", json={"table_name": table_name, "filters": filters}).mock(
return_value=httpx.Response(200, json=expected_response))

client = HiveAgentClient(base_url)
Expand All @@ -134,7 +135,7 @@ async def test_read_data_failure():
filters = {"id": [1]}

with respx.mock() as mock:
mock.post(f"{base_url}/database/read-data", json={"table_name": table_name, "filters": filters}).mock(
mock.post(f"{base_url}/v1/database/read-data", json={"table_name": table_name, "filters": filters}).mock(
return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
Expand All @@ -151,7 +152,7 @@ async def test_update_data_success():
expected_response = {"message": "Data updated successfully."}

with respx.mock() as mock:
mock.put(f"{base_url}/database/update-data", json={"table_name": table_name, "id": row_id, "data": data}).mock(
mock.put(f"{base_url}/v1/database/update-data", json={"table_name": table_name, "id": row_id, "data": data}).mock(
return_value=httpx.Response(200, json=expected_response))

client = HiveAgentClient(base_url)
Expand All @@ -166,7 +167,7 @@ async def test_update_data_failure():
data = {"name": "Updated Test"}

with respx.mock() as mock:
mock.put(f"{base_url}/database/update-data", json={"table_name": table_name, "id": row_id, "data": data}).mock(
mock.put(f"{base_url}/v1/database/update-data", json={"table_name": table_name, "id": row_id, "data": data}).mock(
return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
Expand All @@ -182,7 +183,7 @@ async def test_delete_data_success():
expected_response = {"message": "Data deleted successfully."}

with respx.mock() as mock:
mock.request("DELETE", f"{base_url}/database/delete-data",
mock.request("DELETE", f"{base_url}/v1/database/delete-data",
content=json.dumps({"table_name": table_name, "id": row_id})).mock(
return_value=httpx.Response(200, json=expected_response))

Expand All @@ -197,7 +198,7 @@ async def test_delete_data_failure():
row_id = 1

with respx.mock() as mock:
mock.request("DELETE", f"{base_url}/database/delete-data",
mock.request("DELETE", f"{base_url}/v1/database/delete-data",
content=json.dumps({"table_name": table_name, "id": row_id})).mock(
return_value=httpx.Response(400))

Expand All @@ -212,7 +213,7 @@ async def test_upload_files_success(temp_files):
expected_response = {"filenames": ["test1.txt", "test2.txt"]}

with respx.mock() as mock:
mock.post(f"{base_url}/uploadfiles/").mock(
mock.post(f"{base_url}/v1/uploadfiles/").mock(
return_value=httpx.Response(200, json=expected_response))

client = HiveAgentClient(base_url)
Expand All @@ -223,7 +224,7 @@ async def test_upload_files_success(temp_files):
@pytest.mark.asyncio
async def test_upload_files_failure(temp_files):
with respx.mock() as mock:
mock.post(f"{base_url}/uploadfiles/").mock(
mock.post(f"{base_url}/v1/uploadfiles/").mock(
return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
Expand All @@ -237,7 +238,7 @@ async def test_list_files_success():
expected_response = {"files": ["test1.txt", "test2.txt"]}

with respx.mock() as mock:
mock.get(f"{base_url}/files/").mock(
mock.get(f"{base_url}/v1/files/").mock(
return_value=httpx.Response(200, json=expected_response))

client = HiveAgentClient(base_url)
Expand All @@ -248,7 +249,7 @@ async def test_list_files_success():
@pytest.mark.asyncio
async def test_list_files_failure():
with respx.mock() as mock:
mock.get(f"{base_url}/files/").mock(
mock.get(f"{base_url}/v1/files/").mock(
return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
Expand All @@ -263,7 +264,7 @@ async def test_delete_file_success():
expected_response = {"message": f"File {filename} deleted successfully."}

with respx.mock() as mock:
mock.delete(f"{base_url}/files/{filename}").mock(
mock.delete(f"{base_url}/v1/files/{filename}").mock(
return_value=httpx.Response(200, json=expected_response))

client = HiveAgentClient(base_url)
Expand All @@ -276,7 +277,7 @@ async def test_delete_file_failure():
filename = "test_delete.txt"

with respx.mock() as mock:
mock.delete(f"{base_url}/files/{filename}").mock(
mock.delete(f"{base_url}/v1/files/{filename}").mock(
return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
Expand All @@ -292,7 +293,7 @@ async def test_rename_file_success():
expected_response = {"message": f"File {old_filename} renamed to {new_filename} successfully."}

with respx.mock() as mock:
mock.put(f"{base_url}/files/{old_filename}/{new_filename}").mock(
mock.put(f"{base_url}/v1/files/{old_filename}/{new_filename}").mock(
return_value=httpx.Response(200, json=expected_response))

client = HiveAgentClient(base_url)
Expand All @@ -306,7 +307,7 @@ async def test_rename_file_failure():
new_filename = "new_name.txt"

with respx.mock() as mock:
mock.put(f"{base_url}/files/{old_filename}/{new_filename}").mock(
mock.put(f"{base_url}/v1/files/{old_filename}/{new_filename}").mock(
return_value=httpx.Response(400))

client = HiveAgentClient(base_url)
Expand All @@ -326,9 +327,9 @@ async def test_close_http_client():
@pytest.mark.asyncio
async def test_network_failure_handling():
with respx.mock() as mock:
mock.get(f"{base_url}/database/read-data").mock(return_value=httpx.Response(504))
mock.get(f"{base_url}/v1/database/read-data").mock(return_value=httpx.Response(504))

response = await httpx.AsyncClient().get(f"{base_url}/database/read-data")
response = await httpx.AsyncClient().get(f"{base_url}/v1/database/read-data")

with pytest.raises(Exception) as excinfo:
check_response(response.status_code)
Expand All @@ -338,9 +339,9 @@ async def test_network_failure_handling():
@pytest.mark.asyncio
async def test_out_of_scope():
with respx.mock() as mock:
mock.get(f"{base_url}/database/read-data").mock(return_value=httpx.Response(404))
mock.get(f"{base_url}/v1/database/read-data").mock(return_value=httpx.Response(404))

response = await httpx.AsyncClient().get(f"{base_url}/database/read-data")
response = await httpx.AsyncClient().get(f"{base_url}/v1/database/read-data")

with pytest.raises(Exception) as excinfo:
check_response(response.status_code)
Expand All @@ -350,9 +351,9 @@ async def test_out_of_scope():
@pytest.mark.asyncio
async def test_heavy_load():
with respx.mock() as mock:
mock.get(f"{base_url}/database/read-data").mock(return_value=httpx.Response(429))
mock.get(f"{base_url}/v1/database/read-data").mock(return_value=httpx.Response(429))

response = await httpx.AsyncClient().get(f"{base_url}/database/read-data")
response = await httpx.AsyncClient().get(f"{base_url}/v1/database/read-data")

with pytest.raises(Exception) as excinfo:
check_response(response.status_code)
Expand All @@ -362,9 +363,9 @@ async def test_heavy_load():
@pytest.mark.asyncio
async def test_internal_server():
with respx.mock() as mock:
mock.get(f"{base_url}/database/read-data").mock(return_value=httpx.Response(500))
mock.get(f"{base_url}/v1/database/read-data").mock(return_value=httpx.Response(500))

response = await httpx.AsyncClient().get(f"{base_url}/database/read-data")
response = await httpx.AsyncClient().get(f"{base_url}/v1/database/read-data")

with pytest.raises(Exception) as excinfo:
check_response(response.status_code)
Expand All @@ -374,9 +375,9 @@ async def test_internal_server():
@pytest.mark.asyncio
async def test_large_data_entry():
with respx.mock() as mock:
mock.get(f"{base_url}/database/read-data").mock(return_value=httpx.Response(413))
mock.get(f"{base_url}/v1/database/read-data").mock(return_value=httpx.Response(413))

response = await httpx.AsyncClient().get(f"{base_url}/database/read-data")
response = await httpx.AsyncClient().get(f"{base_url}/v1/database/read-data")

with pytest.raises(Exception) as excinfo:
check_response(response.status_code)
Expand All @@ -386,9 +387,9 @@ async def test_large_data_entry():
@pytest.mark.asyncio
async def test_unprocessable_data_entry():
with respx.mock() as mock:
mock.get(f"{base_url}/database/read-data").mock(return_value=httpx.Response(422))
mock.get(f"{base_url}/v1/database/read-data").mock(return_value=httpx.Response(422))

response = await httpx.AsyncClient().get(f"{base_url}/database/read-data")
response = await httpx.AsyncClient().get(f"{base_url}/v1/database/read-data")

with pytest.raises(Exception) as excinfo:
check_response(response.status_code)
Expand All @@ -398,9 +399,9 @@ async def test_unprocessable_data_entry():
@pytest.mark.asyncio
async def test_response_success():
with respx.mock() as mock:
mock.get(f"{base_url}/database/read-data").mock(return_value=httpx.Response(200))
mock.get(f"{base_url}/v1/database/read-data").mock(return_value=httpx.Response(200))

response = await httpx.AsyncClient().get(f"{base_url}/database/read-data")
response = await httpx.AsyncClient().get(f"{base_url}/v1/database/read-data")

check_response(response.status_code)
assert response.status_code == 200
5 changes: 3 additions & 2 deletions tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ from hive_agent_client import HiveAgentClient
Instantiate the client with the base URL of your Hive Agent API:

```python
base_url = "https://api.example.com" # Replace with your actual API URL
client = HiveAgentClient(base_url)
base_url = "https://localhost:8000/api/" # replace with your actual API URL
version = "v1" # optional param
client = HiveAgentClient(base_url, version)
```

## Sending Chat Messages
Expand Down

0 comments on commit 414f98a

Please sign in to comment.