Skip to content

Commit bfae331

Browse files
Improve OpenAI integration with better error handling (#14)
- Use OpenAIProvider with configurable base_url via OPENAI_BASE_URL_OVERRIDE - Add comprehensive error handling for 401 Unauthorized errors - Provide helpful diagnostic messages for authentication failures - Default base_url changed to OpenAI's standard endpoint
1 parent 2d7421e commit bfae331

1 file changed

Lines changed: 41 additions & 11 deletions

File tree

src/openai.jl

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -54,18 +54,48 @@ function translate_with_openai(
5454
model::String = default_model(),
5555
system_promptfn = default_docstring_system_promptfn,
5656
)
57-
c = create_chat(
58-
ENV["OPENAI_API_KEY"],
59-
model,
60-
[
61-
Dict("role" => "system", "content" => system_promptfn(lang)),
62-
Dict("role" => "user", "content" => string(doc)),
63-
];
64-
temperature = 0,
57+
provider = OpenAI.OpenAIProvider(
58+
api_key=ENV["OPENAI_API_KEY"],
59+
base_url=get(ENV, "OPENAI_BASE_URL_OVERRIDE", "https://api.openai.com/v1")
6560
)
66-
content = c.response[:choices][begin][:message][:content]
67-
content = postprocess_content(content)
68-
return Markdown.parse(content)
61+
try
62+
c = create_chat(
63+
provider,
64+
model,
65+
[
66+
Dict("role" => "system", "content" => system_promptfn(lang)),
67+
Dict("role" => "user", "content" => string(doc)),
68+
];
69+
temperature = 0,
70+
)
71+
content = c.response[:choices][begin][:message][:content]
72+
content = postprocess_content(content)
73+
return Markdown.parse(content)
74+
catch e
75+
error_msg = string(e)
76+
# Check for 401 Unauthorized errors
77+
if occursin("401", error_msg) || occursin("Unauthorized", error_msg)
78+
error("""
79+
Authentication failed (401 Unauthorized).
80+
81+
Possible causes:
82+
1. The OPENAI_API_KEY is invalid or expired
83+
2. The API key is not valid for the endpoint: $(ENV["OPENAI_BASE_URL_OVERRIDE"])
84+
3. The API key format is incorrect
85+
4. The API key was not loaded from .env file
86+
87+
Please verify:
88+
- Your .env file contains: OPENAI_API_KEY=sk-<your-key>
89+
- You've run: using DotEnv; DotEnv.load!()
90+
- Check that the API key is set: @assert haskey(ENV, "OPENAI_API_KEY")
91+
- The API key is valid for the endpoint being used
92+
93+
Original error: $(error_msg)
94+
""")
95+
else
96+
rethrow(e)
97+
end
98+
end
6999
end
70100

71101
function _create_hex(l::Markdown.Link)

0 commit comments

Comments
 (0)