File size: 4,745 Bytes
9f50319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import os
from openai import OpenAI
from anthropic import Anthropic
import google.generativeai as genai
import requests
from dotenv import load_dotenv

load_dotenv()

class LLMCaller:
    def __init__(self, model_name: str = "gpt-4.1-mini-2025-04-14"):
        """
        Initialize LLM model with unified interface
        
        Parameters:
        - model_name: Model name to use, defaults to "gpt-4.1-mini-2025-04-14"
        """
        self.model_name = model_name
        self._setup_model()
        
    def _setup_model(self):
        """Setup model configuration based on model name"""
        if self.model_name.startswith("gpt"):
            self.client = OpenAI(
                api_key=os.getenv("OPENAI_API_KEY"),
                base_url="https://api.openai.com/v1"
            )
            self.api_type = "openai"
        elif self.model_name.startswith("claude"):
            self.client = Anthropic(
                api_key=os.getenv("ANTHROPIC_API_KEY")
            )
            self.api_type = "anthropic"
        elif self.model_name.startswith("deepseek"):
            self.api_key = os.getenv("DEEPSEEK_API_KEY")
            self.api_url = "https://api.deepseek.com/v1/chat/completions"
            self.api_type = "deepseek"
        elif self.model_name.startswith("gemini"):
            genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
            self.model = genai.GenerativeModel(self.model_name)
            self.api_type = "gemini"
        elif self.model_name in ["llama-3-70b", "mixtral-8x7b", "qwen-72b"]:
            self.api_url = "http://localhost:8000/v1"
            self.api_type = "local"
        else:
            raise ValueError(f"Unsupported model: {self.model_name}")

    def call(self, prompt: str) -> str:
        """
        Call LLM API with a single prompt
        
        Parameters:
        - prompt: Input prompt string
        
        Returns:
        - response: Model's response
        """
        try:
            if self.api_type == "openai":
                response = self.client.chat.completions.create(
                    model=self.model_name,
                    messages=[
                        {"role": "system", "content": "You are a mathematical expert specializing in graph theory and persistent homology."},
                        {"role": "user", "content": prompt}
                    ]
                )
                return response.choices[0].message.content
                
            elif self.api_type == "anthropic":
                response = self.client.messages.create(
                    model=self.model_name,
                    system="You are a helpful assistant.",
                    messages=[{"role": "user", "content": prompt}]
                )
                return response.content[0].text
                
            elif self.api_type == "deepseek":
                headers = {
                    "Authorization": f"Bearer {self.api_key}",
                    "Content-Type": "application/json"
                }
                data = {
                    "model": self.model_name,
                    "messages": [
                        {"role": "user", "content": "/no_think" + prompt}
                    ]
                }
                response = requests.post(self.api_url, headers=headers, json=data)
                response.raise_for_status()
                return response.json()["choices"][0]["message"]["content"]
                
            elif self.api_type == "gemini":
                response = self.model.generate_content(prompt)
                return response.text
                
            elif self.api_type == "local":
                data = {
                    "model": self.model_name,
                    "messages": [
                        {"role": "user", "content": prompt}
                    ]
                }
                response = requests.post(self.api_url, json=data)
                response.raise_for_status()
                return response.json()["choices"][0]["message"]["content"]
                
        except Exception as e:
            print(f"Error calling {self.model_name} API: {e}")
            return f"API call error: {str(e)}"

    def batch_call(self, prompts: list[str]) -> list[str]:
        """
        Batch call LLM API with multiple prompts
        
        Parameters:
        - prompts: List of input prompts
        
        Returns:
        - responses: List of model responses
        """
        responses = []
        for idx, prompt in enumerate(prompts, start=1):
            print(f"Processing prompt {idx}/{len(prompts)}")
            response = self.call(prompt)
            responses.append(response)
        return responses