ChenyuRabbitLove commited on
Commit
203f861
1 Parent(s): 006b3a2

feature: add api calling demo

Browse files
__pycache__/app.cpython-311.pyc ADDED
Binary file (5.2 kB). View file
 
__pycache__/functions_definition.cpython-311.pyc ADDED
Binary file (707 Bytes). View file
 
app.py CHANGED
@@ -3,25 +3,20 @@ import json
3
 
4
  import gradio as gr
5
  from openai import OpenAI
6
- from huggingface_hub import InferenceClient
7
  from tenacity import retry, wait_random_exponential, stop_after_attempt
8
 
 
 
9
  OPENAI_KEY = os.getenv("OPENAI_KEY")
10
  client = OpenAI(api_key=OPENAI_KEY)
11
 
12
- def get_current_weather(location, unit="celsius"):
13
- """Get the current weather in a given location"""
14
- if "taipei" in location.lower():
15
- return json.dumps({"location": "Taipei", "temperature": "10", "unit": unit})
16
- else:
17
- return json.dumps({"location": location, "temperature": "unknown"})
18
 
19
  @retry(wait=wait_random_exponential(multiplier=1, max=40), stop=stop_after_attempt(3))
20
  def chat_completion_request(messages, tools=None, tool_choice=None):
21
- print(f'query message {messages}')
22
  try:
23
  response = client.chat.completions.create(
24
- model='gpt-4o',
25
  messages=messages,
26
  tools=tools,
27
  tool_choice=tool_choice,
@@ -32,62 +27,45 @@ def chat_completion_request(messages, tools=None, tool_choice=None):
32
  print("Unable to generate ChatCompletion response")
33
  print(f"Exception: {e}")
34
  return e
35
-
36
- tools = [
37
- {
38
- "type": "function",
39
- "function": {
40
- "name": "get_current_weather",
41
- "description": "Get the current weather",
42
- "parameters": {
43
- "type": "object",
44
- "properties": {
45
- "location": {
46
- "type": "string",
47
- "description": "The city and state, e.g. San Francisco, CA",
48
- },
49
- "unit": {
50
- "type": "string",
51
- "enum": ["celsius", "fahrenheit"],
52
- "description": "The temperature unit to use. Infer this from the users location.",
53
- },
54
- },
55
- "required": ["location", "unit"],
56
- },
57
- }
58
- }
59
- ]
60
 
61
 
62
  def respond(
63
  message,
64
  history: list[tuple[str, str]],
65
  ):
66
- messages = [{"role": "system", "content": [{'type': 'text', 'text': 'You are a helpful agent'}]}]
 
 
 
 
 
67
  for val in history:
68
  if val[0]:
69
- messages.append({"role": "user", "content": [{'type': 'text', 'text': val[0]}]})
 
 
70
  if val[1]:
71
- messages.append({"role": "assistant", "content": [{'type': 'text', 'text': val[1]}]})
 
 
72
 
73
- messages.append({"role": "user", "content": [{'type': 'text', 'text': message}]})
74
 
75
- response = chat_completion_request(messages, tools=tools, tool_choice='auto')
 
 
76
 
77
  response_message = response.choices[0].message
78
  tool_calls = response_message.tool_calls
79
  if tool_calls:
80
- available_functions = {
81
- "get_current_weather": get_current_weather,
82
- }
83
  messages.append(response_message)
84
  for tool_call in tool_calls:
85
  function_name = tool_call.function.name
86
  function_to_call = available_functions[function_name]
87
  function_args = json.loads(tool_call.function.arguments)
88
  function_response = function_to_call(
89
- location=function_args.get("location"),
90
- unit=function_args.get("unit"),
91
  )
92
  messages.append(
93
  {
@@ -96,21 +74,31 @@ def respond(
96
  "name": function_name,
97
  "content": function_response,
98
  }
99
- )
100
  second_response = chat_completion_request(messages)
101
- messages.append({"role": "assistant", "content": [{'type': 'text', 'text': second_response.choices[0].message.content}]})
 
 
 
 
 
 
 
102
  return second_response.choices[0].message.content
103
- messages.append({"role": "assistant", "content": [{'type': 'text', 'text': response.choices[0].message.content}]})
 
 
 
 
 
104
  return response.choices[0].message.content
105
 
 
106
  """
107
  For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
108
  """
109
- demo = gr.ChatInterface(
110
- respond,
111
- title='Function Calling Demo'
112
- )
113
 
114
 
115
  if __name__ == "__main__":
116
- demo.launch()
 
3
 
4
  import gradio as gr
5
  from openai import OpenAI
 
6
  from tenacity import retry, wait_random_exponential, stop_after_attempt
7
 
8
+ from functions_definition import get_functions, get_openai_function_tools
9
+
10
  OPENAI_KEY = os.getenv("OPENAI_KEY")
11
  client = OpenAI(api_key=OPENAI_KEY)
12
 
 
 
 
 
 
 
13
 
14
  @retry(wait=wait_random_exponential(multiplier=1, max=40), stop=stop_after_attempt(3))
15
  def chat_completion_request(messages, tools=None, tool_choice=None):
16
+ print(f"query message {messages}")
17
  try:
18
  response = client.chat.completions.create(
19
+ model="gpt-4o",
20
  messages=messages,
21
  tools=tools,
22
  tool_choice=tool_choice,
 
27
  print("Unable to generate ChatCompletion response")
28
  print(f"Exception: {e}")
29
  return e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  def respond(
33
  message,
34
  history: list[tuple[str, str]],
35
  ):
36
+ messages = [
37
+ {
38
+ "role": "system",
39
+ "content": [{"type": "text", "text": "You are a helpful agent"}],
40
+ }
41
+ ]
42
  for val in history:
43
  if val[0]:
44
+ messages.append(
45
+ {"role": "user", "content": [{"type": "text", "text": val[0]}]}
46
+ )
47
  if val[1]:
48
+ messages.append(
49
+ {"role": "assistant", "content": [{"type": "text", "text": val[1]}]}
50
+ )
51
 
52
+ messages.append({"role": "user", "content": [{"type": "text", "text": message}]})
53
 
54
+ response = chat_completion_request(
55
+ messages, tools=get_openai_function_tools(), tool_choice="auto"
56
+ )
57
 
58
  response_message = response.choices[0].message
59
  tool_calls = response_message.tool_calls
60
  if tool_calls:
61
+ available_functions = get_functions()
 
 
62
  messages.append(response_message)
63
  for tool_call in tool_calls:
64
  function_name = tool_call.function.name
65
  function_to_call = available_functions[function_name]
66
  function_args = json.loads(tool_call.function.arguments)
67
  function_response = function_to_call(
68
+ type=function_args.get("type"),
 
69
  )
70
  messages.append(
71
  {
 
74
  "name": function_name,
75
  "content": function_response,
76
  }
77
+ )
78
  second_response = chat_completion_request(messages)
79
+ messages.append(
80
+ {
81
+ "role": "assistant",
82
+ "content": [
83
+ {"type": "text", "text": second_response.choices[0].message.content}
84
+ ],
85
+ }
86
+ )
87
  return second_response.choices[0].message.content
88
+ messages.append(
89
+ {
90
+ "role": "assistant",
91
+ "content": [{"type": "text", "text": response.choices[0].message.content}],
92
+ }
93
+ )
94
  return response.choices[0].message.content
95
 
96
+
97
  """
98
  For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
99
  """
100
+ demo = gr.ChatInterface(respond, title="Function Calling Demo")
 
 
 
101
 
102
 
103
  if __name__ == "__main__":
104
+ demo.launch()
functions_definition.py CHANGED
@@ -1,24 +1,86 @@
1
- tools = [
2
- {
3
- "type": "function",
4
- "function": {
5
- "name": "get_current_weather",
6
- "description": "Get the current weather",
7
- "parameters": {
8
- "type": "object",
9
- "properties": {
10
- "location": {
11
- "type": "string",
12
- "description": "The city and state, e.g. San Francisco, CA",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  },
14
- "unit": {
15
- "type": "string",
16
- "enum": ["celsius", "fahrenheit"],
17
- "description": "The temperature unit to use. Infer this from the users location.",
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  },
 
19
  },
20
- "required": ["location", "unit"],
21
  },
22
- }
 
 
 
 
 
 
 
 
23
  }
24
- ]
 
1
+ import json
2
+
3
+ import requests
4
+
5
+
6
+ def get_current_weather(location, unit="celsius"):
7
+ """Get the current weather in a given location"""
8
+ if "taipei" in location.lower():
9
+ return json.dumps({"location": "Taipei", "temperature": "10", "unit": unit})
10
+ else:
11
+ return json.dumps({"location": location, "temperature": "unknown"})
12
+
13
+
14
+ def get_junyi_content(type):
15
+ print(f"Fetching Junyi content of type {type}")
16
+ base_url = "https://www.junyiacademy.org/api/v2/open/content/topicpage/"
17
+ topic_id = "knsh-7a"
18
+
19
+ url = f"{base_url}{topic_id}"
20
+
21
+ response = requests.get(url)
22
+ if response.status_code == 200:
23
+ data = response.json()
24
+ print(data)
25
+ else:
26
+ print(f"Request failed with status code {response.status_code}")
27
+ if type == "english":
28
+ return json.dumps(
29
+ {
30
+ "content": "英文",
31
+ "url": "https://www.junyiacademy.org/junyi-english/eng-junior/eng-junior07/eng-junior07-knsh/knsh-7a",
32
+ }
33
+ )
34
+
35
+
36
+ def get_openai_function_tools():
37
+ tools = [
38
+ {
39
+ "type": "function",
40
+ "function": {
41
+ "name": "get_current_weather",
42
+ "description": "Get the current weather",
43
+ "parameters": {
44
+ "type": "object",
45
+ "properties": {
46
+ "location": {
47
+ "type": "string",
48
+ "description": "The city and state, e.g. San Francisco, CA",
49
+ },
50
+ "unit": {
51
+ "type": "string",
52
+ "enum": ["celsius", "fahrenheit"],
53
+ "description": "The temperature unit to use. Infer this from the users location.",
54
+ },
55
  },
56
+ "required": ["location", "unit"],
57
+ },
58
+ },
59
+ },
60
+ {
61
+ "type": "function",
62
+ "function": {
63
+ "name": "get_junyi_content",
64
+ "description": "Get the content from Junyi Academy",
65
+ "parameters": {
66
+ "type": "object",
67
+ "properties": {
68
+ "type": {
69
+ "type": "string",
70
+ "enum": ["english", "math"],
71
+ "description": "The type of content to fetch",
72
+ },
73
  },
74
+ "required": ["type"],
75
  },
 
76
  },
77
+ },
78
+ ]
79
+ return tools
80
+
81
+
82
+ def get_functions():
83
+ return {
84
+ "get_current_weather": get_current_weather,
85
+ "get_junyi_content": get_junyi_content,
86
  }