openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.86.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/parsing_tools.py

80lines · modeblame

bf1ca86cRobert Craigie1 years ago1from enum import Enum
2from typing import List, Union
3
4import rich
5from pydantic import BaseModel
6
7import openai
8from openai import OpenAI
9
10
11class Table(str, Enum):
12orders = "orders"
13customers = "customers"
14products = "products"
15
16
17class Column(str, Enum):
18id = "id"
19status = "status"
20expected_delivery_date = "expected_delivery_date"
21delivered_at = "delivered_at"
22shipped_at = "shipped_at"
23ordered_at = "ordered_at"
24canceled_at = "canceled_at"
25
26
27class Operator(str, Enum):
28eq = "="
29gt = ">"
30lt = "<"
31le = "<="
32ge = ">="
33ne = "!="
34
35
36class OrderBy(str, Enum):
37asc = "asc"
38desc = "desc"
39
40
41class DynamicValue(BaseModel):
42column_name: str
43
44
45class Condition(BaseModel):
46column: str
47operator: Operator
48value: Union[str, int, DynamicValue]
49
50
51class Query(BaseModel):
52table_name: Table
53columns: List[Column]
54conditions: List[Condition]
55order_by: OrderBy
56
57
58client = OpenAI()
59
60completion = client.beta.chat.completions.parse(
61model="gpt-4o-2024-08-06",
62messages=[
63{
64"role": "system",
65"content": "You are a helpful assistant. The current date is August 6, 2024. You help users query for the data they are looking for by calling the query function.",
66},
67{
68"role": "user",
69"content": "look up all my orders in november of last year that were fulfilled but not delivered on time",
70},
71],
72tools=[
73openai.pydantic_function_tool(Query),
74],
75)
76
77tool_call = (completion.choices[0].message.tool_calls or [])[0]
78rich.print(tool_call.function)
79assert isinstance(tool_call.function.parsed_arguments, Query)
80print(tool_call.function.parsed_arguments.table_name)