Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:51bitquant Ai hedge fund crypto get llm

From Leeroopedia
Knowledge Sources
Domains LLM_Integration, Provider_Abstraction
Last Updated 2026-10-28 14:00 GMT

Overview

Wrapper around six LangChain chat-model providers, dispatching by name and caching instances provided by the `get_llm` factory function.

Description

get_llm is an `@lru_cache(maxsize=None)`-decorated factory returning a cached LangChain chat model for one of six providers: `openai` (`ChatOpenAI`), `groq` (`ChatGroq`), `openrouter` (uses `ChatOpenAI` with the OpenRouter base URL), `gemini` (`ChatGoogleGenerativeAI`), `anthropic` (`ChatAnthropic`), and `ollama` (`ChatOllama`). Each branch reads the provider-specific API key from environment variables, applies a default `base_url` when none is supplied, and sets `timeout=120` and `max_retries=3` (Ollama only sets timeout). An unsupported provider raises `ValueError`. The module also exports `json_parser = SimpleJsonOutputParser()`.

Usage

Call this function (or import `json_parser`) when you need a LangChain chat model instance for the trading decision chain. Used by generate_trading_decision to obtain the LLM. Set the appropriate environment variable (`OPENAI_API_KEY`, `GROQ_API_KEY`, `OPENROUTER_API_KEY`, `GOOGLE_API_KEY`, `ANTHROPIC_API_KEY`) before calling.

Code Reference

Source Location

Signature

@lru_cache(maxsize=None)
def get_llm(provider: str, model: str, base_url: Optional[str] = None):
    """
    Return a cached LLM instance based on provider and model.
    Supported providers: openai, groq, openrouter, gemini, anthropic, ollama
    """
    timeout = 120
    max_retries = 3
    if provider == "openai":
        return ChatOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=base_url or "https://api.openai.com/v1", model=model, timeout=timeout, max_retries=max_retries)
    elif provider == "groq":
        return ChatGroq(api_key=os.getenv("GROQ_API_KEY"), base_url=base_url or "https://api.groq.com/v1", model=model, timeout=timeout, max_retries=max_retries)
    elif provider == "openrouter":
        return ChatOpenAI(api_key=os.getenv("OPENROUTER_API_KEY"), base_url=base_url or "https://openrouter.ai/api/v1", model=model, timeout=timeout, max_retries=max_retries)
    elif provider == "gemini":
        return ChatGoogleGenerativeAI(google_api_key=os.getenv("GOOGLE_API_KEY"), base_url=base_url or "https://generativelanguage.googleapis.com/v1beta", model=model, timeout=timeout, max_retries=max_retries)
    elif provider == "anthropic":
        return ChatAnthropic(api_key=os.getenv("ANTHROPIC_API_KEY"), base_url=base_url or "https://api.anthropic.com", model=model, timeout=timeout, max_retries=max_retries)
    elif provider == "ollama":
        return ChatOllama(model=model, base_url=base_url or "http://localhost:11434", timeout=timeout)
    else:
        raise ValueError(f"Unsupported provider: {provider}")

json_parser = SimpleJsonOutputParser()

Import

from src.llm import get_llm, json_parser

I/O Contract

Inputs

Name Type Required Description
provider str Yes One of `openai`, `groq`, `openrouter`, `gemini`, `anthropic`, `ollama`
model str Yes Model identifier (e.g. `"gpt-4o-mini"`, `"llama-3.1-70b"`)
base_url Optional[str] No Custom base URL; defaults to provider's official endpoint
env vars str API key from environment (`OPENAI_API_KEY`, `GROQ_API_KEY`, etc.)

Outputs

Name Type Description
return ChatModel A LangChain chat model instance (cached)
json_parser SimpleJsonOutputParser Module-level singleton for parsing LLM JSON output

Usage Examples

Get an OpenAI Chat Model

import os
os.environ["OPENAI_API_KEY"] = "sk-..."
from src.llm import get_llm, json_parser

llm = get_llm(provider="openai", model="gpt-4o-mini")
response = llm.invoke("What is the capital of France?")
print(response.content)

Use in the Decision Chain

from src.llm import get_llm, json_parser
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([("system", "You are a trader."), ("human", "{input}")])
llm = get_llm(provider="openai", model="gpt-4o-mini")
chain = prompt | llm | json_parser
result = chain.invoke({"input": "Decide: buy or hold?"})
print(result)  # parsed dict

Ollama (local)

# Ensure Ollama is running on localhost:11434
llm = get_llm(provider="ollama", model="llama3.1")

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment