Guide agli SDK
LangChain
Usa i modelli di api14 in LangChain per Python e JavaScript cambiando base URL e chiave, con streaming, strumenti, output strutturato ed embeddings.
L'integrazione OpenAI di LangChain funziona con api14 senza modifiche: imposta base URL e chiave e usa qualsiasi id di modello (ad esempio openai/gpt-5-mini). Gli esempi sono per Python (langchain-openai) e JavaScript (@langchain/openai).
Installazione
pip install langchain-openai
# or
npm install @langchain/openai @langchain/core
export API14_API_KEY="sk-api14-..."
Configurazione (Python)
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="anthropic/claude-sonnet-4.5",
base_url="https://api14.com/api/v1",
api_key=os.environ["API14_API_KEY"],
)
print(llm.invoke("Explain vector databases in two sentences.").content)
Configurazione (JavaScript)
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "openai/gpt-5-mini",
apiKey: process.env.API14_API_KEY,
configuration: { baseURL: "https://api14.com/api/v1" },
});
const res = await llm.invoke("Explain vector databases in two sentences.");
console.log(res.content);
Streaming
for chunk in llm.stream("Write a haiku about APIs."):
print(chunk.content, end="", flush=True)
for await (const chunk of await llm.stream("Write a haiku about APIs.")) {
process.stdout.write(String(chunk.content));
}
Strumenti e output strutturato
from pydantic import BaseModel
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"21°C in {city}"
msg = llm.bind_tools([get_weather]).invoke("What is the weather in Istanbul?")
print(msg.tool_calls)
class Place(BaseModel):
city: str
country: str
place = llm.with_structured_output(Place).invoke('I live in Lisbon, Portugal.')
print(place)
Embeddings
La maggior parte dei modelli di embeddings su api14 non sono modelli OpenAI, quindi disattiva il controllo della lunghezza con tiktoken lato client:
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(
model="openai/text-embedding-3-small",
base_url="https://api14.com/api/v1",
api_key=os.environ["API14_API_KEY"],
check_embedding_ctx_length=False,
)
vectors = embeddings.embed_documents(["The quick brown fox", "Lorem ipsum"])
Parametri del gateway
Passa i campi specifici del gateway tramite extra_body (Python) o modelKwargs (JS):
llm = ChatOpenAI(
model="openai/gpt-5-mini",
base_url="https://api14.com/api/v1",
api_key=os.environ["API14_API_KEY"],
extra_body={"models": ["anthropic/claude-sonnet-4.5"], "provider": {"sort": "price"}},
)
Errori
LangChain espone le eccezioni dell'SDK OpenAI. Un 402 insufficient_balance genera openai.APIStatusError; un 429 rate_limited genera openai.RateLimitError dopo i retry integrati (max_retries= su ChatOpenAI). Vedi Errori.