As a workaround, you can move to an auxiliary tex file all the code needed to config SageTeX. Then you can input that file in the argument of \AtBeginDocument. For example, let the contents of examplepackage.sty be

\documentclass[12pt]{article}
\usepackage{examplepackage}
\begin{document}
% Do something with a and b
The value of $a$ is $\sage{a}$, while that of $b$
is $\sage{b}$. Their sum is $\sage{a+b}$.
% Do something with the function
\begin{sagesilent}
gp(x) = diff(g(x),x)
g_int(x) = integrate(g(x), x)
\end{sagesilent}
Let $g(x)=\sage{g(x)}$. It is easily seen that
\[
g'(x)=\sage{gp(x)},
\]
whereas
\[
\int g(x)\,dx=\sage{g_int(x)}.
\]
Observe also that $g'(2)\approx\sage{gp(2).n()}$.
\end{document}