Spaces:
Sleeping
Sleeping
File size: 3,357 Bytes
611b67c 33c52e5 611b67c 33c52e5 611b67c f789516 611b67c |
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 |
import os
import json
from openai import OpenAI
class AgentResponse:
def __init__(self, response):
self.content = response
def __str__(self):
return self.content
def __repr__(self):
return self.content
def lower(self):
self.content = self.content.lower()
return self
def is_equal(self, condition):
return self.content == condition
def as_boolean(self):
try:
return bool(self.content)
except ValueError:
raise ValueError(f"Cannot convert {self.content} to boolean")
def as_json(self):
try:
return json.loads(self.content)
except json.JSONDecodeError:
raise ValueError(f"Cannot convert {self.content} to JSON")
class Agent:
def __init__(self, prompt_folder: str = "prompts"):
organization = os.getenv("OPENAI_ORGANIZATION")
project = os.getenv("OPENAI_PROJECT")
api_key = os.getenv("OPENAI_API_KEY")
if not organization or not project or not api_key:
raise ValueError(
"Please set the OPENAI_ORGANIZATION, OPENAI_PROJECT, and OPENAI_API_KEY environment variables"
)
self.client = OpenAI(
organization=organization,
project=project,
api_key=api_key,
)
self.prompt_folder = prompt_folder
def request(self, query, model="gpt-4o-mini", max_tokens=300) -> AgentResponse:
response = self.client.chat.completions.create(
model=model,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": query,
}
],
}
],
max_tokens=max_tokens,
)
return AgentResponse(response.choices[0].message.content)
def read_prompt(self, prompt_name: str):
prompt_file = f"{self.prompt_folder}/{prompt_name}.txt"
if not os.path.exists(prompt_file):
raise FileNotFoundError(f"Prompt file not found at {prompt_file}")
with open(prompt_file, "r") as file:
return file.read()
def image_request(
self, image: str, query: str, max_tokens: int = 300, force_json: bool = False
) -> AgentResponse:
try:
response = self.client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": query,
},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpg;base64,{image}"},
},
],
}
],
max_tokens=max_tokens,
response_format={"type": "json_object"} if force_json else None,
)
result = AgentResponse(response.choices[0].message.content)
return result
except Exception as e:
raise
|