Visit: https://platform.openai.com/api-keys
Create a new API key (starts with sk-...)
# Set for current session
export OPENAI_API_KEY="sk-your-actual-key-here"
# Verify it's set
echo $OPENAI_API_KEYmvn exec:java -Dexec.mainClass="org.agentic.flink.example.OpenAIFlinkAgentsDemo"Temporary (current session only):
export OPENAI_API_KEY="sk-your-key-here"Permanent (add to shell profile):
For bash (~/.bashrc or ~/.bash_profile):
echo 'export OPENAI_API_KEY="sk-your-key-here"' >> ~/.bashrc
source ~/.bashrcFor zsh (~/.zshrc):
echo 'export OPENAI_API_KEY="sk-your-key-here"' >> ~/.zshrc
source ~/.zshrcFor fish (~/.config/fish/config.fish):
echo 'set -x OPENAI_API_KEY "sk-your-key-here"' >> ~/.config/fish/config.fish
source ~/.config/fish/config.fishmvn exec:java \
-Dexec.mainClass="org.agentic.flink.example.OpenAIFlinkAgentsDemo" \
-Dopenai.api.key="sk-your-key-here"Create .env file:
echo 'OPENAI_API_KEY=sk-your-key-here' > .envIMPORTANT: Add to .gitignore:
echo '.env' >> .gitignoreLoad in your code:
// You'd need a library like dotenv-java for this
// Or manually read the file- ✅ Use environment variables
- ✅ Add
.envto.gitignore - ✅ Rotate keys regularly
- ✅ Use different keys for dev/prod
- ✅ Set usage limits on OpenAI dashboard
- ✅ Monitor usage on OpenAI dashboard
- ❌ Hardcode API keys in source code
- ❌ Commit API keys to git
- ❌ Share keys in Slack/email
- ❌ Use production keys in development
- ❌ Store keys in plain text files (that get committed)
# Set your key first
export OPENAI_API_KEY="sk-..."
# Run the OpenAI-specific demo
mvn exec:java -Dexec.mainClass="org.agentic.flink.example.OpenAIFlinkAgentsDemo"What it demonstrates:
- Simple OpenAI chat
- Tool integration with OpenAI
- OpenAI + Flink Agents integration
The interactive demo can also use OpenAI if you add it. See the section below.
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.chat.ChatLanguageModel;
// Get API key from environment
String apiKey = System.getenv("OPENAI_API_KEY");
// Create model
ChatLanguageModel model = OpenAiChatModel.builder()
.apiKey(apiKey)
.modelName("gpt-5.4-nano") // or "gpt-5.5"
.temperature(0.7)
.maxTokens(500)
.build();
// Use it
String response = model.generate("Explain Apache Flink");import org.agentic.flink.langchain.model.language.OpenAiLanguageModel;
// Create OpenAI model
OpenAiLanguageModel openAiModel = new OpenAiLanguageModel();
ChatLanguageModel model = openAiModel.getModel(Map.of(
"apiKey", System.getenv("OPENAI_API_KEY"),
"modelName", "gpt-5.4-nano"
));
// Use with your agents
// (See examples in OpenAIFlinkAgentsDemo.java).modelName("gpt-5.4-nano")
.maxTokens(500)
.temperature(0.7) // 0.0 = deterministic, 1.0 = creativeBest for:
- Quick responses
- High volume
- Cost-sensitive applications
- Testing/development
Cost: ~$0.001 per 1K tokens
.modelName("gpt-5.5")
.maxTokens(1000)
.temperature(0.5)Best for:
- Complex reasoning
- High-quality responses
- Production use
- Critical applications
Cost: ~$0.03 per 1K tokens
.modelName("gpt-5.4")
.maxTokens(2000)
.temperature(0.7)Best for:
- Balance of speed and quality
- Longer context windows
- Most production use cases
Solution:
# Verify environment variable is set
echo $OPENAI_API_KEY
# If empty, set it
export OPENAI_API_KEY="sk-your-key-here"
# Try again
mvn exec:java -Dexec.mainClass="..."Causes:
- Key is wrong/typo
- Key was revoked
- Key has expired
Solution:
- Go to https://platform.openai.com/api-keys
- Create a new key
- Replace the old one:
export OPENAI_API_KEY="sk-new-key-here"
Solution:
- Wait 20-60 seconds
- Reduce request frequency
- Upgrade your OpenAI plan
- Check usage: https://platform.openai.com/usage
Solution:
- Add credits to your OpenAI account
- Check billing: https://platform.openai.com/account/billing
- Set up billing if needed
Solution:
- Check model name spelling
- Verify you have access to that model
- Try "gpt-5.4-nano" as fallback
- Go to https://platform.openai.com/account/limits
- Set hard limit (e.g., $10/month)
- Set soft limit for alerts
# Check your usage regularly
curl https://api.openai.com/v1/usage \
-H "Authorization: Bearer $OPENAI_API_KEY"Or visit: https://platform.openai.com/usage
Strategies:
- Use GPT-5.4 nano for most tasks
- Set
maxTokensto reasonable limits - Cache responses when possible
- Use streaming for long responses
- Implement request throttling
ChatLanguageModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5.4-nano")
.build();
String answer = model.generate("Question here");String context = "User is asking about Apache Flink...";
String question = "What are checkpoints?";
String prompt = context + "\n\nQuestion: " + question;
String answer = model.generate(prompt);// Create your tools
ToolExecutor calculator = new CalculatorTool();
ToolDefinition toolDef = new ToolDefinition(...);
// Wrap for Flink Agents
Agent toolAgent = FlinkAgentsToolAdapter.wrapSingleTool(
"calculator", calculator, toolDef
);
// Use with OpenAI
// (OpenAI can decide when to call tools)// Get AI response
String response = model.generate(question);
// Validate with your framework
ValidationResult result = validator.validate(response);
if (!result.isValid()) {
// Retry with feedback
String feedback = result.getFeedback();
String improved = model.generate(question + "\nFeedback: " + feedback);
}public class CustomerSupportAgent {
private ChatLanguageModel model;
public CustomerSupportAgent() {
model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5.4-nano")
.temperature(0.5) // More consistent responses
.build();
}
public String handleInquiry(String customerMessage) {
String systemPrompt = "You are a helpful customer support agent. " +
"Be concise, friendly, and professional.";
String response = model.generate(systemPrompt + "\n\n" + customerMessage);
return response;
}
}public String analyzeDocument(String documentText) {
String prompt = "Analyze this document and provide key insights:\n\n" +
documentText;
ChatLanguageModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5.5") // Better for analysis
.maxTokens(1000)
.build();
return model.generate(prompt);
}- Get API key: https://platform.openai.com/api-keys
- Set environment variable:
export OPENAI_API_KEY="sk-..." - Run demo:
mvn exec:java -Dexec.mainClass="org.agentic.flink.example.OpenAIFlinkAgentsDemo" - Read examples: See
OpenAIFlinkAgentsDemo.java - Build your agent: Use patterns above
- OpenAI Docs: https://platform.openai.com/docs
- LangChain4J Docs: https://docs.langchain4j.dev/
- Our Examples: See
src/main/java/org/agentic/flink/example/ - Troubleshooting: See this document or DEMO_GUIDE.md
🚀 Ready to use OpenAI with Flink Agents!