forked from aws-samples/bedrock-access-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
Handle Anthropic messages as if they were chat/completions #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
nullfunc
merged 14 commits into
defang
from
eric-update-to-allow-non-chat-completion-apis
Jun 5, 2025
Merged
Changes from 6 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
30af3c6
update to target URL creation
nullfunc c6a61b5
clean up
nullfunc d8ff6f5
remove unintended add
nullfunc 7066bbf
in progress checkpoint: handles vertex ai message conversion
nullfunc c6362b7
in progress
nullfunc 4571d1d
update for tests and minor fixes
nullfunc 9c395b9
Apply suggestions from code review
nullfunc fac6d32
review updates
nullfunc 97b6ee8
update for handle mistral. added some more models
nullfunc dcf908e
log error message so shows in logs
nullfunc 6598200
Apply suggestions from code review
nullfunc ae64e16
update modelmap to include gcp models with overlap for aws and docker…
nullfunc cdb9474
fix, gemini needs 'google/' prefix in model name
nullfunc 9a4bed5
Apply suggestions from code review
nullfunc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,199 @@ | ||
import pytest | ||
import json | ||
from unittest.mock import patch, MagicMock | ||
from fastapi import Request | ||
from starlette.datastructures import Headers, QueryParams | ||
from fastapi import Response | ||
|
||
import api.routers.vertex as vertex | ||
|
||
@pytest.fixture | ||
def dummy_request(): | ||
class DummyRequest: | ||
def __init__(self, headers=None, body=None, method="POST", query_params=None): | ||
self.headers = Headers(headers or {}) | ||
self._body = body or b'{}' | ||
self.method = method | ||
self.query_params = QueryParams(query_params or {}) | ||
|
||
async def body(self): | ||
return self._body | ||
|
||
return DummyRequest | ||
|
||
def test_to_vertex_anthropic(): | ||
openai_messages = { | ||
"messages": [ | ||
{"role": "user", "content": "Hello!"}, | ||
{"role": "assistant", "content": "Hi there!"} | ||
] | ||
} | ||
result = vertex.to_vertex_anthropic(openai_messages) | ||
assert result["anthropic_version"] == "vertex-2023-10-16" | ||
assert result["max_tokens"] == 256 | ||
assert isinstance(result["messages"], list) | ||
assert result["messages"][0]["role"] == "user" | ||
assert result["messages"][0]["content"][0]["text"] == "Hello!" | ||
assert result["messages"][1]["role"] == "assistant" | ||
assert result["messages"][1]["content"][0]["text"] == "Hi there!" | ||
|
||
def test_from_anthropic_to_openai_response(): | ||
msg = json.dumps({ | ||
"id": "abc123", | ||
"role": "assistant", | ||
"content": [{"type": "text", "text": "Hello!"}, {"type": "text", "text": "Bye!"}], | ||
"stop_reason": "stop", | ||
"usage": {"prompt_tokens": 5, "completion_tokens": 2} | ||
}) | ||
result = json.loads(vertex.from_anthropic_to_openai_response(msg)) | ||
assert result["id"] == "abc123" | ||
assert result["object"] == "chat.completion" | ||
assert len(result["choices"]) == 1 | ||
assert result["choices"][0]["message"]["content"] == "Hello!Bye!" | ||
assert result["choices"][0]["finish_reason"] == "stop" | ||
assert result["usage"]["prompt_tokens"] == 5 | ||
|
||
def test_get_gcp_target_env(monkeypatch): | ||
monkeypatch.setenv("PROXY_TARGET", "https://custom-proxy") | ||
result = vertex.get_gcp_target("any-model", "/v1/chat/completions") | ||
assert result == "https://custom-proxy" | ||
|
||
def test_get_gcp_target_known_chat(monkeypatch): | ||
monkeypatch.delenv("PROXY_TARGET", raising=False) | ||
model = vertex.known_chat_models[0] | ||
path = "/v1/chat/completions" | ||
result = vertex.get_gcp_target(model, path) | ||
assert "endpoints/openapi/chat/completions" in result | ||
|
||
def test_get_gcp_target_raw_predict(monkeypatch): | ||
monkeypatch.delenv("PROXY_TARGET", raising=False) | ||
model = "unknown-model" | ||
path = "/v1/other" | ||
result = vertex.get_gcp_target(model, path) | ||
assert ":rawPredict" in result | ||
|
||
@patch("api.routers.vertex.get_access_token", return_value="dummy-token") | ||
def test_get_header_removes_hop_headers(mock_token, dummy_request): | ||
req = dummy_request(headers={ | ||
"Host": "example.com", | ||
"Content-Length": "123", | ||
"Accept-Encoding": "gzip", | ||
"Connection": "keep-alive", | ||
"Authorization": "Bearer old", | ||
"X-Custom": "foo" | ||
}) | ||
model = "test-model" | ||
path = "/v1/chat/completions" | ||
with patch("api.routers.vertex.get_gcp_target", return_value="http://target"): | ||
nullfunc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
target_url, headers = vertex.get_header(model, req, path) | ||
assert target_url == "http://target" | ||
assert "Host" not in headers | ||
assert "Content-Length" not in headers | ||
assert "Accept-Encoding" not in headers | ||
assert "Connection" not in headers | ||
assert "Authorization" in headers | ||
assert headers["Authorization"] == "Bearer dummy-token" | ||
assert headers["x-custom"] == "foo" | ||
|
||
@pytest.mark.asyncio | ||
@patch("api.routers.vertex.httpx.AsyncClient") | ||
@patch("api.routers.vertex.get_header") | ||
@patch("api.routers.vertex.get_model", return_value="test-model") | ||
async def test_handle_proxy_basic(mock_get_model, mock_get_header, mock_async_client, dummy_request): | ||
req = dummy_request(body=json.dumps({"model": "foo"}).encode()) | ||
mock_get_header.return_value = ("http://target", {"Authorization": "Bearer token"}) | ||
mock_response = MagicMock() | ||
mock_response.content = b'{"candidates":[{"content":{"parts":[{"text":"hi"}]}, "finishReason":"STOP"}]}' | ||
mock_response.status_code = 200 | ||
mock_response.headers = {"content-type": "application/json"} | ||
mock_async_client.return_value.__aenter__.return_value.request.return_value = mock_response | ||
|
||
vertex.USE_MODEL_MAPPING = True | ||
vertex.known_chat_models.append("test-model") | ||
result = await vertex.handle_proxy(req, "/v1/chat/completions") | ||
assert result.status_code == 200 | ||
assert b"hi" in result.body | ||
assert result.headers["content-type"] == "application/json" | ||
|
||
@pytest.mark.asyncio | ||
@patch("api.routers.vertex.httpx.AsyncClient") | ||
@patch("api.routers.vertex.get_header") | ||
@patch("api.routers.vertex.get_model", return_value="test-model") | ||
async def test_handle_proxy_known_chat_model( | ||
mock_get_model, mock_get_header, mock_async_client, dummy_request | ||
): | ||
req = dummy_request(body=json.dumps({"model": "foo"}).encode()) | ||
mock_get_header.return_value = ("http://target", {"Authorization": "Bearer token"}) | ||
mock_response = MagicMock() | ||
mock_response.content = b'{"candidates":[{"content":{"parts":[{"text":"hi"}]}, "finishReason":"STOP"}]}' | ||
mock_response.status_code = 200 | ||
mock_response.headers = {"content-type": "application/json"} | ||
mock_async_client.return_value.__aenter__.return_value.request.return_value = mock_response | ||
|
||
vertex.USE_MODEL_MAPPING = True | ||
if "test-model" not in vertex.known_chat_models: | ||
vertex.known_chat_models.append("test-model") | ||
|
||
result = await vertex.handle_proxy(req, "/v1/chat/completions") | ||
assert isinstance(result, Response) | ||
assert result.status_code == 200 | ||
assert b"hi" in result.body | ||
assert result.headers["content-type"] == "application/json" | ||
|
||
@pytest.mark.asyncio | ||
@patch("api.routers.vertex.httpx.AsyncClient") | ||
@patch("api.routers.vertex.get_header") | ||
@patch("api.routers.vertex.get_model", return_value="anthropic-model") | ||
async def test_handle_proxy_anthropic_conversion( | ||
mock_get_model, mock_get_header, mock_async_client, dummy_request | ||
): | ||
req = dummy_request(body=json.dumps({"model": "foo", "messages": [{"role": "user", "content": "hi"}]}).encode()) | ||
mock_get_header.return_value = ("http://target", {"Authorization": "Bearer token"}) | ||
mock_response = MagicMock() | ||
# Simulate anthropic response | ||
anthropic_resp = json.dumps({ | ||
"id": "abc123", | ||
"role": "assistant", | ||
"content": [{"type": "text", "text": "Hello!"}], | ||
"stop_reason": "stop", | ||
"usage": {"prompt_tokens": 5, "completion_tokens": 2} | ||
}).encode() | ||
mock_response.content = anthropic_resp | ||
mock_response.status_code = 200 | ||
mock_response.headers = {"content-type": "application/json"} | ||
mock_async_client.return_value.__aenter__.return_value.request.return_value = mock_response | ||
|
||
vertex.USE_MODEL_MAPPING = True | ||
# Ensure model is not in known_chat_models to trigger conversion | ||
if "anthropic-model" in vertex.known_chat_models: | ||
vertex.known_chat_models.remove("anthropic-model") | ||
result = await vertex.handle_proxy(req, "/v1/chat/completions") | ||
assert isinstance(result, Response) | ||
data = json.loads(result.body) | ||
assert data["object"] == "chat.completion" | ||
assert data["choices"][0]["message"]["content"] == "Hello!" | ||
|
||
@pytest.mark.asyncio | ||
@patch("api.routers.vertex.httpx.AsyncClient", side_effect=Exception("network error")) | ||
@patch("api.routers.vertex.get_header") | ||
@patch("api.routers.vertex.get_model", return_value="test-model") | ||
async def test_handle_proxy_httpx_exception( | ||
mock_get_model, mock_get_header, mock_async_client, dummy_request | ||
): | ||
req = dummy_request(body=json.dumps({"model": "foo"}).encode()) | ||
mock_get_header.return_value = ("http://target", {"Authorization": "Bearer token"}) | ||
vertex.USE_MODEL_MAPPING = True | ||
if "test-model" not in vertex.known_chat_models: | ||
vertex.known_chat_models.append("test-model") | ||
# Patch httpx.RequestError to be raised | ||
with patch("api.routers.vertex.httpx.RequestError", Exception): | ||
result = await vertex.handle_proxy(req, "/v1/chat/completions") | ||
assert isinstance(result, Response) | ||
assert result.status_code == 502 | ||
assert b"Upstream request failed" in result.body | ||
# Assert that the status code is 502 (Bad Gateway) due to upstream failure | ||
assert result.status_code == 502 | ||
|
||
# Assert that the response body contains the expected error message | ||
assert b"Upstream request failed" in result.body | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.