instructor
62 строки · 2.1 Кб
1import os2import instructor3from openai import OpenAI4from pydantic import BaseModel, Field5from typing import Optional6from instructor import Mode7
8# Extract API key from environment
9runpod_api_key = os.environ.get("RUNPOD_API_KEY")10assert runpod_api_key, "RUNPOD_API_KEY is not set in environment variables"11
12# Base URL for OpenAI client
13runpod_base_url = os.environ.get("RUNPOD_BASE_URL")14assert runpod_base_url, "RUNPOD_BASE_URL is not set in environment variables"15
16# Initialize OpenAI client
17client = instructor.from_openai(18OpenAI(api_key=runpod_api_key, base_url=runpod_base_url),19mode=Mode.JSON,20)
21
22
23data = [24"Brandon is 33 years old. He works as a solution architect.",25"Jason is 25 years old. He is the GOAT.",26"Dominic is 45 years old. He is retired.",27"Jenny is 72. She is a wife and a CEO.",28"Holly is 22. She is an explorer.",29"There onces was a prince, named Benny. He ruled for 10 years, which just ended. He started at 22.",30"Simon says, why are you 22 years old marvin?",31]
32
33
34if __name__ == "__main__":35
36class UserDetail(BaseModel):37name: str = Field(description="Name extracted from the text")38age: int = Field(description="Age extracted from the text")39occupation: Optional[str] = Field(40default=None, description="Occupation extracted from the text"41)42
43for content in data:44try:45user = client.chat.completions.create(46response_model=UserDetail,47model="TheBloke_OpenHermes-2.5-Mistral-7B-GPTQ",48messages=[49{50"role": "system",51"content": "You are an expert at outputting json. You output valid JSON.",52},53{54"role": "user",55"content": f"Extract the user details from the following text: {content}. Match your response to the following schema: {UserDetail.model_json_schema()}",56},57],58)59print(f"Result: {user}")60except Exception as e:61print(f"Error: {e}")62continue63