Skip to content

Instantly share code, notes, and snippets.

@HabermannR
Created November 12, 2024 12:56
Show Gist options
  • Save HabermannR/2b2d090d663e2ef941062f8453ec6bb7 to your computer and use it in GitHub Desktop.
Save HabermannR/2b2d090d663e2ef941062f8453ec6bb7 to your computer and use it in GitHub Desktop.
from pydantic import BaseModel
from typing import Dict, Any, TypeVar, Type, List, Optional, Union, Generic
import os
import json
from openai import OpenAI
client = OpenAI(
api_key=os.environ["GEMINI_KEY"],
base_url="https://generativelanguage.googleapis.com/v1beta/"
)
def create_json_schema(model: Type[BaseModel]) -> Dict[str, Any]:
schema = model.model_json_schema()
return {
"type": "json_schema",
"json_schema": {
"name": "test_schema",
"strict": True,
"schema": schema,
},
}
class Relationship(BaseModel):
target: str
type: str
opinion: int # -100 to 100
class StartCharacter(BaseModel):
name: str
title: str
class Character(BaseModel):
name: str
title: str
relationships: Optional[List[Relationship]]
tool_schema = create_json_schema(StartCharacter)
tools = [
{
"type": "function",
"function": {
"name": "Tribe_Game",
"description": "Create game structures",
"parameters": tool_schema['json_schema']['schema']
}
}
]
messages = [{"role": "user", "content": "Create a Character with name, title."}]
response = client.chat.completions.create(
model="models/gemini-1.5-pro",
messages=messages,
tools=tools,
tool_choice={"type": "tool", "name": "Tribe_Game"}
)
print(response)
result = StartCharacter.model_validate(json.loads(response.choices[0].message.tool_calls[0].function.arguments))
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment