Configure OpenAI GPT-5 series models including GPT-5, GPT-5 Pro, GPT-5 Mini, and GPT-5 Nano
Overview
OpenAI provides industry-leading language models with the GPT-5 series. This guide covers setup, configuration, and best practices for using OpenAI models with the MCP Server.
GPT-5 is OpenAI’s latest flagship model with enhanced reasoning, multimodal capabilities, and improved efficiency.
Available Models
Model
Context Window
Use Case
Pricing (per 1M tokens)
gpt-5.1
128K tokens
Best all-around, latest flagship
$2.50 input / $10.00 output
gpt-5.1-pro
128K tokens
Most capable, advanced reasoning
$10.00 input / $30.00 output
gpt-5-mini
128K tokens
Fast and cost-effective
$0.15 input / $0.60 output
gpt-5.1-nano
128K tokens
Smallest, fastest, ultra low-cost
$0.10 input / $0.40 output
Recommended: gpt-5.1 for production (best performance/cost ratio)
# Add to Infisical dashboardOPENAI_API_KEY=sk-...your-key# In .env, reference InfisicalINFISICAL_PROJECT_ID=your-project-idINFISICAL_CLIENT_ID=your-client-idINFISICAL_CLIENT_SECRET=your-client-secret
def select_openai_model(task_type: str, complexity: str) -> str: """Select appropriate OpenAI model based on task""" # Fast, simple tasks if task_type == "chat" and complexity == "simple": return "gpt-5.1-nano" # Smallest, fastest, ultra low-cost # Standard tasks elif complexity == "low": return "gpt-5-mini" # Fast and cost-effective # Multimodal or complex reasoning elif task_type in ["vision", "multimodal"] or complexity == "high": return "gpt-5.1" # Best all-around flagship # Maximum intelligence and advanced reasoning elif complexity == "expert": return "gpt-5.1-pro" # Most capable # Default return "gpt-5.1"## Use dynamicallyllm = LLMFactory( provider="openai", model_name=select_openai_model(task_type="chat", complexity="medium"))
Features
Function Calling (Tools)
from langchain_core.tools import toolfrom langgraph.prebuilt import create_react_agent@tooldef get_current_weather(location: str, unit: str = "fahrenheit") -> str: """Get the current weather in a given location. Args: location: The city and state, e.g. San Francisco, CA unit: The unit of temperature, either "celsius" or "fahrenheit" """ # Implementation return f"Weather in {location}: 72°{unit[0].upper()}, Sunny"@tooldef search_web(query: str) -> str: """Search the web for current information. Args: query: The search query """ # Implementation return f"Search results for: {query}"## Create agent with toolsllm_with_tools = llm.bind_tools([get_current_weather, search_web])agent = create_react_agent( llm_with_tools, tools=[get_current_weather, search_web])## Run agentresult = await agent.ainvoke({ "messages": [("user", "What's the weather in Tokyo and search for recent AI news")]})print(result["messages"][-1].content)
Vision (GPT-5, GPT-5 Pro)
import base64from langchain_core.messages import HumanMessage## Load imagewith open("chart.png", "rb") as f: image_data = base64.b64encode(f.read()).decode()## Create vision messagemessage = HumanMessage( content=[ { "type": "text", "text": "What's in this image? Provide a detailed description." }, { "type": "image_url", "image_url": { "url": f"data:image/png;base64,{image_data}", "detail": "high" # "low", "high", or "auto" } } ])response = await llm.ainvoke([message])print(response.content)
Structured Output (JSON Mode)
from pydantic import BaseModel, Fieldfrom typing import Listclass SentimentAnalysis(BaseModel): """Sentiment analysis result""" sentiment: str = Field(description="Overall sentiment: positive, negative, or neutral") confidence: float = Field(description="Confidence score 0-1") key_phrases: List[str] = Field(description="Key phrases that influenced the sentiment")## Force structured outputstructured_llm = llm.with_structured_output(SentimentAnalysis)text = "I absolutely love this product! It exceeded all my expectations."response = await structured_llm.ainvoke( f"Analyze the sentiment of this text:\n\n{text}")print(response.model_dump_json(indent=2))## Output:## {## "sentiment": "positive",## "confidence": 0.95,## "key_phrases": ["absolutely love", "exceeded expectations"]## }
Streaming
## Stream token-by-tokenasync def stream_response(query: str): async for chunk in llm.astream(query): print(chunk.content, end="", flush=True) yield chunk.content## Use in APIfrom fastapi.responses import StreamingResponse@app.post("/message/stream")async def stream_message(request: MessageRequest): return StreamingResponse( stream_response(request.query), media_type="text/event-stream" )
System Prompts
from langchain_core.prompts import ChatPromptTemplate## Define system promptprompt = ChatPromptTemplate.from_messages([ ("system", """You are a helpful AI assistant specializing in {domain}.Guidelines:- Provide accurate, well-researched information- Cite sources when applicable- Acknowledge uncertainty- Use {style} communication styleCurrent date: {current_date}"""), ("user", "{query}")])## Create chainfrom datetime import datetimechain = prompt | llm## Runresponse = await chain.ainvoke({ "domain": "software engineering", "style": "technical but accessible", "current_date": datetime.now().strftime("%Y-%m-%d"), "query": "Explain microservices architecture"})print(response.content)
Response Format (JSON Mode)
## Force JSON outputllm_json = ChatOpenAI( model="gpt-5.1", model_kwargs={"response_format": {"type": "json_object"}})response = await llm_json.ainvoke( "Extract person info as JSON: John Smith is a 35-year-old software engineer")import jsondata = json.loads(response.content)print(data)## Output: {"name": "John Smith", "age": 35, "occupation": "software engineer"}
# Verify API key formatecho $OPENAI_API_KEY | head -c 10# Should start with: sk-# Test keycurl https://api.openai.com/v1/models \ -H "Authorization: Bearer $OPENAI_API_KEY"# Regenerate key# 1. Go to https://platform.openai.com/api-keys# 2. Revoke old key# 3. Create new key# 4. Update in Infisical