langchain-straitly 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Straitly
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.
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-straitly
3
+ Version: 0.1.0
4
+ Summary: LangChain chat model for Straitly, an OpenAI-compatible AI gateway
5
+ Project-URL: Homepage, https://straitly.ai
6
+ Project-URL: Documentation, https://straitly.ai/docs/quickstart
7
+ Project-URL: Models, https://straitly.ai/models
8
+ Author: Straitly
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai-gateway,chat,langchain,llm,openai-compatible,straitly
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: <4.0,>=3.10
17
+ Requires-Dist: langchain-core<2.0.0,>=1.0.0
18
+ Requires-Dist: langchain-openai<2.0.0,>=1.0.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ # langchain-straitly
22
+
23
+ LangChain chat model for [Straitly](https://straitly.ai).
24
+
25
+ Straitly is an AI gateway for startups: one OpenAI-compatible API key for 150+ models including Claude, GPT, Gemini,
26
+ Grok and DeepSeek.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install -U langchain-straitly
32
+ export STRAITLY_API_KEY="your-api-key"
33
+ ```
34
+
35
+ ## Use
36
+
37
+ ```python
38
+ from langchain_straitly import ChatStraitly
39
+
40
+ model = ChatStraitly(model="deepseek/deepseek-v4-1-flash", temperature=0)
41
+ print(model.invoke("Say hello in one sentence.").content)
42
+
43
+ for chunk in model.stream("Write one line about rain."):
44
+ print(chunk.text, end="")
45
+ ```
46
+
47
+ Pick any model id from https://straitly.ai/models (JSON: https://straitly.ai/api/catalog). Tool calling and
48
+ structured output use the same methods as `ChatOpenAI` (`bind_tools`, `with_structured_output`); support depends on
49
+ the model.
50
+
51
+ | Setting | Env var | Default |
52
+ | :-- | :-- | :-- |
53
+ | API key | `STRAITLY_API_KEY` | none, required |
54
+ | Base URL | `STRAITLY_API_BASE` | `https://api.straitly.ai/v1` |
55
+
56
+ `OPENAI_API_KEY` is never read, so an OpenAI key is never sent to Straitly.
57
+
58
+ Docs: https://straitly.ai/docs/quickstart. Contact: https://straitly.ai/contact.
@@ -0,0 +1,38 @@
1
+ # langchain-straitly
2
+
3
+ LangChain chat model for [Straitly](https://straitly.ai).
4
+
5
+ Straitly is an AI gateway for startups: one OpenAI-compatible API key for 150+ models including Claude, GPT, Gemini,
6
+ Grok and DeepSeek.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install -U langchain-straitly
12
+ export STRAITLY_API_KEY="your-api-key"
13
+ ```
14
+
15
+ ## Use
16
+
17
+ ```python
18
+ from langchain_straitly import ChatStraitly
19
+
20
+ model = ChatStraitly(model="deepseek/deepseek-v4-1-flash", temperature=0)
21
+ print(model.invoke("Say hello in one sentence.").content)
22
+
23
+ for chunk in model.stream("Write one line about rain."):
24
+ print(chunk.text, end="")
25
+ ```
26
+
27
+ Pick any model id from https://straitly.ai/models (JSON: https://straitly.ai/api/catalog). Tool calling and
28
+ structured output use the same methods as `ChatOpenAI` (`bind_tools`, `with_structured_output`); support depends on
29
+ the model.
30
+
31
+ | Setting | Env var | Default |
32
+ | :-- | :-- | :-- |
33
+ | API key | `STRAITLY_API_KEY` | none, required |
34
+ | Base URL | `STRAITLY_API_BASE` | `https://api.straitly.ai/v1` |
35
+
36
+ `OPENAI_API_KEY` is never read, so an OpenAI key is never sent to Straitly.
37
+
38
+ Docs: https://straitly.ai/docs/quickstart. Contact: https://straitly.ai/contact.
@@ -0,0 +1,12 @@
1
+ """LangChain integration for Straitly."""
2
+
3
+ from importlib import metadata
4
+
5
+ try:
6
+ __version__ = metadata.version(__package__ or "langchain-straitly")
7
+ except metadata.PackageNotFoundError:
8
+ __version__ = ""
9
+
10
+ from langchain_straitly.chat_models import ChatStraitly # noqa: E402
11
+
12
+ __all__ = ["ChatStraitly", "__version__"]
@@ -0,0 +1,164 @@
1
+ """Straitly chat models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import openai
8
+ from langchain_core.language_models import LangSmithParams, LanguageModelInput
9
+ from langchain_core.utils import from_env, secret_from_env
10
+ from langchain_openai.chat_models.base import BaseChatOpenAI
11
+ from pydantic import ConfigDict, Field, SecretStr, model_validator
12
+ from typing_extensions import Self
13
+
14
+ DEFAULT_API_BASE = "https://api.straitly.ai/v1"
15
+
16
+
17
+ class ChatStraitly(BaseChatOpenAI):
18
+ """Chat models on Straitly, an OpenAI-compatible AI gateway.
19
+
20
+ One Straitly API key reaches more than 150 models, including Claude, GPT,
21
+ Gemini, Grok and DeepSeek. Model ids are listed at https://straitly.ai/models
22
+ (JSON: https://straitly.ai/api/catalog).
23
+
24
+ Setup:
25
+ ```bash
26
+ pip install -U langchain-straitly
27
+ export STRAITLY_API_KEY="your-api-key"
28
+ ```
29
+
30
+ Key init args (completion params):
31
+ model:
32
+ Straitly model id from https://straitly.ai/models. Required.
33
+ temperature:
34
+ Sampling temperature.
35
+ max_tokens:
36
+ Max number of tokens to generate.
37
+
38
+ Key init args (client params):
39
+ api_key:
40
+ Straitly API key. Read from `STRAITLY_API_KEY` if not passed.
41
+ base_url:
42
+ API base URL. Read from `STRAITLY_API_BASE`, defaults to
43
+ `https://api.straitly.ai/v1`.
44
+ timeout:
45
+ Timeout for requests.
46
+ max_retries:
47
+ Max number of retries.
48
+
49
+ Instantiate:
50
+ ```python
51
+ from langchain_straitly import ChatStraitly
52
+
53
+ model = ChatStraitly(model="deepseek/deepseek-v4-1-flash", temperature=0)
54
+ ```
55
+
56
+ Invoke:
57
+ ```python
58
+ model.invoke("Say hello in one sentence.")
59
+ ```
60
+
61
+ Stream:
62
+ ```python
63
+ for chunk in model.stream("Write one line about rain."):
64
+ print(chunk.text, end="")
65
+ ```
66
+
67
+ Tool calling and structured output use the same methods as `ChatOpenAI`
68
+ (`bind_tools`, `with_structured_output`). Support depends on the model.
69
+
70
+ Requests go to `/v1/chat/completions`. Pass `use_responses_api=True` to use
71
+ `/v1/responses` instead. `OPENAI_API_KEY` is never read, so an OpenAI key is
72
+ never sent to Straitly.
73
+ """
74
+
75
+ model_name: str = Field(alias="model")
76
+ """Straitly model id."""
77
+ api_key: SecretStr | None = Field(
78
+ default_factory=secret_from_env("STRAITLY_API_KEY", default=None),
79
+ )
80
+ """Straitly API key. Read from `STRAITLY_API_KEY` if not provided."""
81
+ api_base: str = Field(
82
+ alias="base_url",
83
+ default_factory=from_env("STRAITLY_API_BASE", default=DEFAULT_API_BASE),
84
+ )
85
+ """Straitly API base URL. Read from `STRAITLY_API_BASE` if not provided."""
86
+ stream_usage: bool | None = True
87
+ """Include token usage in streamed responses."""
88
+
89
+ model_config = ConfigDict(populate_by_name=True)
90
+
91
+ @property
92
+ def _llm_type(self) -> str:
93
+ """Return type of chat model."""
94
+ return "chat-straitly"
95
+
96
+ @property
97
+ def lc_secrets(self) -> dict[str, str]:
98
+ """A map of constructor argument names to secret ids."""
99
+ return {"api_key": "STRAITLY_API_KEY"}
100
+
101
+ def _get_ls_params(
102
+ self,
103
+ stop: list[str] | None = None,
104
+ **kwargs: Any,
105
+ ) -> LangSmithParams:
106
+ ls_params = super()._get_ls_params(stop=stop, **kwargs)
107
+ ls_params["ls_provider"] = "straitly"
108
+ return ls_params
109
+
110
+ @model_validator(mode="after")
111
+ def validate_environment(self) -> Self:
112
+ """Check the API key and build OpenAI clients pointed at Straitly."""
113
+ if self.n is not None and self.n < 1:
114
+ msg = "n must be at least 1."
115
+ raise ValueError(msg)
116
+ if self.n is not None and self.n > 1 and self.streaming:
117
+ msg = "n must be 1 when streaming."
118
+ raise ValueError(msg)
119
+ # With no key the OpenAI client would fall back to OPENAI_API_KEY and
120
+ # send it to this base URL, so a Straitly key is always required.
121
+ if not (self.api_key and self.api_key.get_secret_value()):
122
+ msg = "STRAITLY_API_KEY must be set, or pass api_key=..."
123
+ raise ValueError(msg)
124
+ client_params: dict = {
125
+ k: v
126
+ for k, v in {
127
+ "api_key": self.api_key.get_secret_value(),
128
+ "base_url": self.api_base,
129
+ "timeout": self.request_timeout,
130
+ "max_retries": self.max_retries,
131
+ "default_headers": self.default_headers,
132
+ "default_query": self.default_query,
133
+ }.items()
134
+ if v is not None
135
+ }
136
+ if not self.client:
137
+ sync_specific: dict = {"http_client": self.http_client}
138
+ self.root_client = openai.OpenAI(**client_params, **sync_specific)
139
+ self.client = self.root_client.chat.completions
140
+ if not self.async_client:
141
+ async_specific: dict = {"http_client": self.http_async_client}
142
+ self.root_async_client = openai.AsyncOpenAI(
143
+ **client_params, **async_specific
144
+ )
145
+ self.async_client = self.root_async_client.chat.completions
146
+ return self
147
+
148
+ def _use_responses_api(self, payload: dict) -> bool:
149
+ # Chat Completions works for every model; use /v1/responses only when asked.
150
+ return self.use_responses_api is True
151
+
152
+ def _get_request_payload(
153
+ self,
154
+ input_: LanguageModelInput,
155
+ *,
156
+ stop: list[str] | None = None,
157
+ **kwargs: Any,
158
+ ) -> dict:
159
+ payload = super()._get_request_payload(input_, stop=stop, **kwargs)
160
+ # Models from other labs may reject the OpenAI-only `developer` role.
161
+ for message in payload.get("messages", []):
162
+ if message.get("role") == "developer":
163
+ message["role"] = "system"
164
+ return payload
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "langchain-straitly"
7
+ version = "0.1.0"
8
+ description = "LangChain chat model for Straitly, an OpenAI-compatible AI gateway"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Straitly" }]
13
+ requires-python = ">=3.10,<4.0"
14
+ keywords = ["straitly", "langchain", "llm", "openai-compatible", "ai-gateway", "chat"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ ]
21
+ dependencies = [
22
+ "langchain-core>=1.0.0,<2.0.0",
23
+ "langchain-openai>=1.0.0,<2.0.0",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://straitly.ai"
28
+ Documentation = "https://straitly.ai/docs/quickstart"
29
+ Models = "https://straitly.ai/models"
30
+
31
+ [dependency-groups]
32
+ test = [
33
+ "pytest>=8",
34
+ "pytest-asyncio>=0.23",
35
+ "pytest-socket>=0.7",
36
+ "langchain-tests>=1.0.0,<2.0.0",
37
+ ]
38
+
39
+ [tool.hatch.build.targets.sdist]
40
+ include = ["langchain_straitly", "tests", "README.md", "LICENSE", "pyproject.toml"]
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["langchain_straitly"]
44
+
45
+ [tool.pytest.ini_options]
46
+ asyncio_mode = "auto"
47
+ asyncio_default_fixture_loop_scope = "function"
File without changes
File without changes
@@ -0,0 +1,40 @@
1
+ """Straitly-specific unit tests."""
2
+
3
+ import pytest
4
+ from langchain_core.messages import HumanMessage, SystemMessage
5
+
6
+ from langchain_straitly import ChatStraitly
7
+ from langchain_straitly.chat_models import DEFAULT_API_BASE
8
+
9
+
10
+ def test_default_base_url(monkeypatch: pytest.MonkeyPatch) -> None:
11
+ monkeypatch.delenv("STRAITLY_API_BASE", raising=False)
12
+ model = ChatStraitly(model="m", api_key="k")
13
+ assert model.api_base == DEFAULT_API_BASE == "https://api.straitly.ai/v1"
14
+ assert str(model.root_client.base_url).rstrip("/") == DEFAULT_API_BASE
15
+
16
+
17
+ def test_never_falls_back_to_openai_key(monkeypatch: pytest.MonkeyPatch) -> None:
18
+ monkeypatch.delenv("STRAITLY_API_KEY", raising=False)
19
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-openai")
20
+ with pytest.raises(ValueError, match="STRAITLY_API_KEY"):
21
+ ChatStraitly(model="m")
22
+
23
+
24
+ def test_developer_role_sent_as_system() -> None:
25
+ model = ChatStraitly(model="m", api_key="k")
26
+ payload = model._get_request_payload(
27
+ [SystemMessage("be brief"), HumanMessage("hi")]
28
+ )
29
+ assert all(m["role"] != "developer" for m in payload["messages"])
30
+
31
+
32
+ def test_responses_api_only_when_asked() -> None:
33
+ assert ChatStraitly(model="m", api_key="k")._use_responses_api({}) is False
34
+ model = ChatStraitly(model="m", api_key="k", use_responses_api=True)
35
+ assert model._use_responses_api({}) is True
36
+
37
+
38
+ def test_ls_provider() -> None:
39
+ params = ChatStraitly(model="m", api_key="k")._get_ls_params()
40
+ assert params["ls_provider"] == "straitly"
@@ -0,0 +1,32 @@
1
+ """Standard LangChain unit tests for ChatStraitly."""
2
+
3
+ from langchain_core.language_models import BaseChatModel
4
+ from langchain_tests.unit_tests import ChatModelUnitTests
5
+
6
+ from langchain_straitly import ChatStraitly
7
+
8
+ MODEL_NAME = "deepseek/deepseek-v4-1-flash"
9
+
10
+
11
+ class TestChatStraitlyUnit(ChatModelUnitTests):
12
+ @property
13
+ def chat_model_class(self) -> type[BaseChatModel]:
14
+ return ChatStraitly
15
+
16
+ @property
17
+ def chat_model_params(self) -> dict:
18
+ return {"model": MODEL_NAME, "api_key": "test-key"}
19
+
20
+ @property
21
+ def init_from_env_params(self) -> tuple[dict, dict, dict]:
22
+ return (
23
+ {
24
+ "STRAITLY_API_KEY": "api_key",
25
+ "STRAITLY_API_BASE": "https://base.example.com/v1",
26
+ },
27
+ {"model": MODEL_NAME},
28
+ {
29
+ "api_key": "api_key",
30
+ "api_base": "https://base.example.com/v1",
31
+ },
32
+ )