|
| 1 | +"""SiliconFlow model integrations for ReAct agent.""" |
| 2 | + |
| 3 | +import os |
| 4 | +from typing import Any, Optional |
| 5 | + |
| 6 | +# NOTE: Using ChatOpenAI instead of ChatSiliconFlow because langchain-siliconflow v0.1.1 |
| 7 | +# does not support function calling (bind_tools raises NotImplementedError). |
| 8 | +# We'll switch back to ChatSiliconFlow once they add function calling support. |
| 9 | +from langchain_openai import ChatOpenAI |
| 10 | + |
| 11 | +from ..utils import normalize_region |
| 12 | + |
| 13 | + |
| 14 | +def create_siliconflow_model( |
| 15 | + model_name: str, |
| 16 | + api_key: Optional[str] = None, |
| 17 | + base_url: Optional[str] = None, |
| 18 | + region: Optional[str] = None, |
| 19 | + **kwargs: Any, |
| 20 | +) -> ChatOpenAI: |
| 21 | + """Create a SiliconFlow model using ChatOpenAI (OpenAI-compatible API). |
| 22 | +
|
| 23 | + NOTE: Using ChatOpenAI instead of ChatSiliconFlow because langchain-siliconflow v0.1.1 |
| 24 | + does not support function calling (bind_tools raises NotImplementedError). |
| 25 | + SiliconFlow provides OpenAI-compatible API endpoints, so we use ChatOpenAI directly. |
| 26 | +
|
| 27 | + Args: |
| 28 | + model_name: The model name (e.g., 'Qwen/Qwen3-8B', 'THUDM/GLM-4.1V-9B-Thinking') |
| 29 | + api_key: SiliconFlow API key (defaults to env var SILICONFLOW_API_KEY) |
| 30 | + base_url: Custom base URL for API (optional) |
| 31 | + region: Region setting ('prc'/'cn' for China, 'international'/'en' for global) |
| 32 | + Defaults to env var REGION |
| 33 | + **kwargs: Additional model parameters |
| 34 | +
|
| 35 | + Returns: |
| 36 | + Configured ChatOpenAI instance pointing to SiliconFlow API |
| 37 | + """ |
| 38 | + # Get API key from env if not provided |
| 39 | + if api_key is None: |
| 40 | + api_key = os.getenv("SILICONFLOW_API_KEY") |
| 41 | + |
| 42 | + # Get region from env if not provided |
| 43 | + if region is None: |
| 44 | + region = os.getenv("REGION") |
| 45 | + |
| 46 | + # Set base URL based on region if not explicitly provided |
| 47 | + if base_url is None and region: |
| 48 | + # Normalize region aliases |
| 49 | + normalized_region = normalize_region(region) |
| 50 | + if normalized_region == "prc": |
| 51 | + base_url = "https://api.siliconflow.cn/v1" |
| 52 | + elif normalized_region == "international": |
| 53 | + base_url = "https://api.siliconflow.com/v1" |
| 54 | + |
| 55 | + # Default to PRC endpoint if no region specified |
| 56 | + if base_url is None: |
| 57 | + base_url = "https://api.siliconflow.cn/v1" |
| 58 | + |
| 59 | + # Create ChatOpenAI configuration for SiliconFlow |
| 60 | + config = { |
| 61 | + "model": model_name, |
| 62 | + "api_key": api_key, |
| 63 | + "base_url": base_url, |
| 64 | + **kwargs |
| 65 | + } |
| 66 | + |
| 67 | + return ChatOpenAI(**config) |
0 commit comments