跳轉到

LLM 用戶端

Gemini 和 Azure OpenAI 需要安裝 llm extra。

Warning

generate_response 會呼叫遠端模型:輸出不固定,每次呼叫都會用掉 API 額度。

cjtrade.pkgs.llm._llm_base.LLMClientBase(model_name, api_key=None)

Base class for LLM clients.

Parameters:

Name Type Description Default
model_name str

Name of the model to use.

required
api_key str

API key for the provider.

None
Source code in src/cjtrade/pkgs/llm/_llm_base.py
11
12
13
14
def __init__(self, model_name: str, api_key: str = None):
    self.model_name = model_name
    self.api_key = api_key
    self.is_connected = False

generate_response(prompt)

Return a reply to prompt; subclasses must override this.

Parameters:

Name Type Description Default
prompt str

The full prompt.

required

Returns:

Type Description
str

A fixed message saying the method is not implemented.

Warnings

Placeholder: the base class does not call any model.

Source code in src/cjtrade/pkgs/llm/_llm_base.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def generate_response(self, prompt: str) -> str:
    """Return a reply to `prompt`; subclasses must override this.

    Parameters
    ----------
    prompt : str
        The full prompt.

    Returns
    -------
    str
        A fixed message saying the method is not implemented.

    Warnings
    --------
    Placeholder: the base class does not call any model.
    """
    return "Response from base LLM client class," \
    "you need to implement this method rather than calling me directly."

cjtrade.pkgs.llm.gemini

GeminiClient(model_name='gemini-3-flash-preview', api_key=None)

Bases: LLMClientBase

LLM client for Google Gemini (google-genai).

Parameters:

Name Type Description Default
model_name str

Gemini model name.

"gemini-3-flash-preview"
api_key str

Gemini API key.

None
Source code in src/cjtrade/pkgs/llm/gemini.py
20
21
22
def __init__(self, model_name: str = "gemini-3-flash-preview", api_key: str = None):
    self.client = None
    super().__init__(model_name=model_name, api_key=api_key)

generate_response(prompt)

Send prompt to Gemini and return its text reply.

Parameters:

Name Type Description Default
prompt str

The full prompt.

required

Returns:

Type Description
str

The model's reply.

Raises:

Type Description
ImportError

If the 'llm' extra (google-genai) is not installed.

Warnings

Calls a remote API over the network: output is non-deterministic and each call uses paid quota.

Source code in src/cjtrade/pkgs/llm/gemini.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def generate_response(self, prompt: str) -> str:
    """Send `prompt` to Gemini and return its text reply.

    Parameters
    ----------
    prompt : str
        The full prompt.

    Returns
    -------
    str
        The model's reply.

    Raises
    ------
    ImportError
        If the 'llm' extra (``google-genai``) is not installed.

    Warnings
    --------
    Calls a remote API over the network: output is non-deterministic
    and each call uses paid quota.
    """
    if genai is None:
        raise missing_extra("llm")
    self.client = genai.Client(api_key=self.api_key)
    response = self.client.models.generate_content(
        model=self.model_name,
        contents=prompt,
    )
    return response.text

cjtrade.pkgs.llm.azure_openai

AzureOpenAIClient(model_name='gpt-4o', api_key=None, deployment='gpt-4o', endpoint='')

Bases: LLMClientBase

LLM client for Azure OpenAI chat completions.

Parameters:

Name Type Description Default
model_name str

Name of the model.

"gpt-4o"
api_key str

Azure OpenAI API key.

None
deployment str

Azure deployment name sent as the request's model.

"gpt-4o"
endpoint str

Azure OpenAI endpoint URL.

""

Raises:

Type Description
ImportError

If the 'llm' extra (openai) is not installed.

Source code in src/cjtrade/pkgs/llm/azure_openai.py
28
29
30
31
32
33
34
35
36
37
def __init__(self, model_name: str = "gpt-4o", api_key: str = None, deployment: str = "gpt-4o", endpoint: str = ""):
    super().__init__(model_name=model_name, api_key=api_key)
    self.deployment = deployment
    if AzureOpenAI is None:
        raise missing_extra("llm")
    self.client = AzureOpenAI(
        api_version="2024-12-01-preview",
        azure_endpoint=endpoint,
        api_key=self.api_key,
    )

generate_response(prompt)

Send prompt to the Azure deployment and return its text reply.

A fixed system message ("You're a quant trading assistant.") is prepended.

Parameters:

Name Type Description Default
prompt str

The user prompt.

required

Returns:

Type Description
str

The model's reply.

Warnings

Calls a remote API over the network: output is non-deterministic (temperature 1.0) and each call uses paid quota.

Source code in src/cjtrade/pkgs/llm/azure_openai.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def generate_response(self, prompt: str) -> str:
    """Send `prompt` to the Azure deployment and return its text reply.

    A fixed system message ("You're a quant trading assistant.") is
    prepended.

    Parameters
    ----------
    prompt : str
        The user prompt.

    Returns
    -------
    str
        The model's reply.

    Warnings
    --------
    Calls a remote API over the network: output is non-deterministic
    (temperature 1.0) and each call uses paid quota.
    """
    response = self.client.chat.completions.create(
        messages=[
            {
                "role": "system",
                "content": "You're a quant trading assistant.",
            },
            {
                "role": "user",
                "content": prompt,
            }
        ],
        max_tokens=4096,
        temperature=1.0,
        top_p=1.0,
        model=self.deployment
    )
    return response.choices[0].message.content

cjtrade.pkgs.llm.chatpdf

ChatPDFClient(model_name='chatpdf', api_key=None, pdf_src=None)

Bases: LLMClientBase

LLM client that asks questions about a PDF via the ChatPDF API.

Parameters:

Name Type Description Default
model_name str

Name of the model.

"chatpdf"
api_key str

ChatPDF API key.

None
pdf_src str

ChatPDF source ID of the uploaded PDF.

None
Source code in src/cjtrade/pkgs/llm/chatpdf.py
19
20
21
22
def __init__(self, model_name: str = "chatpdf", api_key: str = None, pdf_src: str = None):
    self.client = None
    self.pdf_src = pdf_src
    super().__init__(model_name=model_name, api_key=api_key)

generate_response(prompt)

Send prompt about the PDF to ChatPDF and return its reply.

Parameters:

Name Type Description Default
prompt str

The user message.

required

Returns:

Type Description
str

The content field of the API response.

Raises:

Type Description
Exception

If the API returns a non-200 status; the message is the response body.

Warnings

Calls a remote API over the network: output is non-deterministic and each call uses API quota.

Source code in src/cjtrade/pkgs/llm/chatpdf.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def generate_response(self, prompt: str) -> str:
    """Send `prompt` about the PDF to ChatPDF and return its reply.

    Parameters
    ----------
    prompt : str
        The user message.

    Returns
    -------
    str
        The ``content`` field of the API response.

    Raises
    ------
    Exception
        If the API returns a non-200 status; the message is the response body.

    Warnings
    --------
    Calls a remote API over the network: output is non-deterministic
    and each call uses API quota.
    """
    headers = {
        "x-api-key": self.api_key,
        "Content-Type": "application/json"
    }

    data = {
        "sourceId": self.pdf_src,
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ]
    }

    # print("HEADERS:", headers)
    # print("DATA:", json.dumps(data, indent=2))

    response = requests.post(
        "https://api.chatpdf.com/v1/chats/message",
        headers=headers,
        data=json.dumps(data)
    )

    # print("STATUS:", response.status_code)
    # print("BODY:", response.text)

    if response.status_code != 200:
        raise Exception(response.text)

    return response.json()["content"]

cjtrade.pkgs.llm.mock_llm

MockLLMClient(model_name='', api_key=None)

Bases: LLMClientBase

Offline LLM client for tests that echoes the prompt.

Parameters:

Name Type Description Default
model_name str

Name of the model (unused).

""
api_key str

API key (unused).

None
Source code in src/cjtrade/pkgs/llm/mock_llm.py
15
16
17
def __init__(self, model_name: str = "", api_key: str = None):
    self.client = None
    super().__init__(model_name=model_name, api_key=api_key)

generate_response(prompt)

Wait one second and return "Hello from MockLLM: <prompt>".

Parameters:

Name Type Description Default
prompt str

The prompt to echo.

required

Returns:

Type Description
str

The canned reply.

Source code in src/cjtrade/pkgs/llm/mock_llm.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def generate_response(self, prompt: str) -> str:
    """Wait one second and return ``"Hello from MockLLM: <prompt>"``.

    Parameters
    ----------
    prompt : str
        The prompt to echo.

    Returns
    -------
    str
        The canned reply.
    """
    time.sleep(1)
    response = {"john": "doe", "foo": "bar", "text": f"Hello from MockLLM: {prompt}"}
    return response['text']

cjtrade.pkgs.llm.llm_pool

LLMPool(llms)

Bases: LLMClientBase

A list of LLM clients that fails over to the next one on error.

Parameters:

Name Type Description Default
llms list of LLMClientBase

Clients to try, in order.

required
Source code in src/cjtrade/pkgs/llm/llm_pool.py
15
16
17
def __init__(self, llms: list[LLMClientBase]):
    self.llms = llms
    self.current_index = 0

get_current_llm()

Return the client currently in use.

Raises:

Type Description
Exception

If the pool is empty.

Source code in src/cjtrade/pkgs/llm/llm_pool.py
19
20
21
22
23
24
25
26
27
28
29
def get_current_llm(self):
    """Return the client currently in use.

    Raises
    ------
    Exception
        If the pool is empty.
    """
    if not self.llms:
        raise Exception("No LLMs available in the pool.")
    return self.llms[self.current_index]

get_next_llm()

Return the client after the current one, without switching to it.

Raises:

Type Description
Exception

If the pool is empty.

Source code in src/cjtrade/pkgs/llm/llm_pool.py
31
32
33
34
35
36
37
38
39
40
41
42
def get_next_llm(self):
    """Return the client after the current one, without switching to it.

    Raises
    ------
    Exception
        If the pool is empty.
    """
    if not self.llms:
        raise Exception("No LLMs available in the pool.")
    next_index = (self.current_index + 1) % len(self.llms)
    return self.llms[next_index]

generate_response(prompt)

Return a reply from the current client, failing over on errors.

On an exception the pool logs the error, moves to the next client (wrapping around) and retries until some client returns a reply.

Parameters:

Name Type Description Default
prompt str

The full prompt.

required

Returns:

Type Description
str

The first successful reply.

Warnings

The member clients may call remote APIs (network, usage costs). If every client keeps failing, this loops forever.

Source code in src/cjtrade/pkgs/llm/llm_pool.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def generate_response(self, prompt):
    """Return a reply from the current client, failing over on errors.

    On an exception the pool logs the error, moves to the next client
    (wrapping around) and retries until some client returns a reply.

    Parameters
    ----------
    prompt : str
        The full prompt.

    Returns
    -------
    str
        The first successful reply.

    Warnings
    --------
    The member clients may call remote APIs (network, usage costs).
    If every client keeps failing, this loops forever.
    """
    current_llm = self.get_current_llm()
    response = None
    while response is None:
        try:
            response = current_llm.generate_response(prompt)
        except Exception as e:
            log.warning("LLM %s err: %s, falling back to next", current_llm, e)
            self._fallback()
            current_llm = self.get_current_llm()
    log.info("resp by LLM %s", current_llm)
    return response