-
Notifications
You must be signed in to change notification settings - Fork 0
/
openrouter_client.py
65 lines (53 loc) · 2.2 KB
/
openrouter_client.py
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
import requests
import os
from typing import List, Dict, Any
from dotenv import load_dotenv
load_dotenv()
class OpenRouterClient:
def __init__(self):
self.api_key = os.getenv("OPENROUTER_API_KEY")
if not self.api_key:
raise ValueError("OpenRouter API key is required. Set it in the .env file as OPENROUTER_API_KEY.")
self.base_url = "https://openrouter.ai/api/v1"
def chat_completion(self, messages: List[Dict[str, str]], model: str = "anthropic/claude-3.5-sonnet") -> str:
"""
Send a chat completion request to OpenRouter.
:param messages: List of message dictionaries
:param model: The model to use for completion
:return: The generated response as a string
"""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
data = {
"model": model,
"messages": messages
}
response = requests.post(f"{self.base_url}/chat/completions", headers=headers, json=data)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
def generate_embedding(self, text: str, model: str = "openai/text-embedding-3-small", dimensions: int = 1536) -> List[float]:
"""
Generate an embedding for the given text using OpenRouter.
:param text: The input text to embed
:param model: The model to use for embedding
:param dimensions: The number of dimensions for the embedding (default: 1536)
:return: The embedding as a list of floats
"""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
if self.site_url:
headers["HTTP-Referer"] = self.site_url
if self.site_name:
headers["X-Title"] = self.site_name
data = {
"model": model,
"input": text,
"dimensions": dimensions
}
response = requests.post(f"{self.base_url}/embeddings", headers=headers, json=data)
response.raise_for_status()
return response.json()["data"][0]["embedding"]