hjxdl 0.2.34__py3-none-any.whl → 0.2.36__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hdl/_version.py CHANGED
@@ -12,5 +12,5 @@ __version__: str
12
12
  __version_tuple__: VERSION_TUPLE
13
13
  version_tuple: VERSION_TUPLE
14
14
 
15
- __version__ = version = '0.2.34'
16
- __version_tuple__ = version_tuple = (0, 2, 34)
15
+ __version__ = version = '0.2.36'
16
+ __version_tuple__ = version_tuple = (0, 2, 36)
@@ -51,4 +51,46 @@ def web_search_text(
51
51
  result_str += "\n"
52
52
  except Exception as e:
53
53
  print(f"{str(e)}: 从{result['href']}未搜索(获取)到相关内容。")
54
- return result_str
54
+ return result_str
55
+
56
+
57
+ def fetch_baidu_results(query, max_n_links=3):
58
+ """
59
+ 模拟百度搜索,提取前三个搜索结果的网页文字内容并拼接返回。
60
+
61
+ :param query: str 要搜索的文本
62
+ :return: str 提取的网页内容拼接字符串
63
+ """
64
+ headers = {
65
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
66
+ }
67
+ # 百度搜索 URL
68
+ search_url = 'https://www.baidu.com/s'
69
+ params = {'wd': query}
70
+
71
+ # 发送搜索请求
72
+ response = requests.get(search_url, headers=headers, params=params)
73
+ response.raise_for_status()
74
+ soup = BeautifulSoup(response.text, 'html.parser')
75
+
76
+ # 提取前三个搜索结果链接
77
+ links = []
78
+ for link_tag in soup.select('.t a')[:max_n_links]:
79
+ link = link_tag.get('href')
80
+ if link:
81
+ links.append(link)
82
+
83
+ # 抓取每个链接的网页内容
84
+ text_content = []
85
+ for link in links:
86
+ try:
87
+ page_response = requests.get(link, headers=headers, timeout=10)
88
+ page_response.raise_for_status()
89
+ page_soup = BeautifulSoup(page_response.text, 'html.parser')
90
+ text = page_soup.get_text(separator='\n', strip=True)
91
+ text_content.append(text)
92
+ except requests.RequestException as e:
93
+ print(f"Failed to fetch {link}: {e}")
94
+
95
+ # 返回拼接的文本内容
96
+ return '\n'.join(text_content)
@@ -1,4 +1,5 @@
1
1
  FN_DESC = {
2
+
2
3
  "get_weather": """
3
4
  ## 函数名:get_weather
4
5
  描述:只有在用户询问一个城市的天气时,调用此工具获得此城市的天气信息
@@ -16,6 +17,7 @@ FN_DESC = {
16
17
  }
17
18
 
18
19
  """,
20
+
19
21
  "get_datetime_by_cityname": """
20
22
  ## 函数名:get_datetime_by_cityname
21
23
  描述:只有在用户询问一个城市当前的日期或时间时,调用此工具可以获得此城市当前的日期和时间
@@ -33,40 +35,62 @@ FN_DESC = {
33
35
  }
34
36
 
35
37
  """,
36
- "web_search_text": """
37
- ## 函数名:web_search_text
38
- 描述:在用户明确说要“联网查询”回答他的问题时,调用此工具可以获得该问题联网搜索的相关内容
39
- 触发条件:用户的问题中有显式的“联网查询”字样,用户若没有提到“联网查询”,则不要调用此函数
38
+
39
+ "execute_code": """
40
+ ## 函数名:execute_code,
41
+ 描述:当用户明确要求执行一段代码时,调用此工具,执行这段代码,返回执行结果。
42
+ 触发条件:用户要求执行一段代码
40
43
  参数:
41
- # query_text (str): 从用户提的问题中获取,用于在网络中搜索信息
42
- # max_results (int, optional): 搜索条目的最大数目,若用户指定了数目,则使用用户指定的数目,若用户提问中没有指定,你需要在下面的json中"max_results"这一项指定为数值3。
43
- 返回值 (str): 联网搜索到的信息
44
+ # code (str): 用户要求执行的代码
45
+ 返回值 (str): 执行结果
44
46
  需要返回的json
45
47
  {
46
- "function_name": "web_search_text",
48
+ "function_name": "execute_code",
47
49
  "params":
48
50
  {
49
- "query_text": <query from user question>,
50
- "max_results": <num of max results, 如果用户没有要求,这一项则指定为3>
51
+ "code": <code>
51
52
  }
52
53
  }
53
54
 
54
55
  """,
55
- "execute_code(code)": """
56
- ## 函数名:execute_code,
57
- 描述:当用户明确要求执行一段代码时,调用此工具,执行这段代码,返回执行结果。
58
- 触发条件:用户要求执行一段代码
56
+
57
+ "calculate": """
58
+ ## 函数名:calculate,
59
+ 描述:当用户要求计算一个数学表达式时,调用此工具,计算这个表达式,返回计算结果。
60
+ 触发条件:用户要求计算一个数学表达式
59
61
  参数:
60
- # code (str): 用户要求执行的代码
61
- 返回值 (str): 执行结果
62
+ # expression (str): 用户要求的数学表达式
63
+ 返回值 (str): 计算结果
62
64
  需要返回的json
63
65
  {
64
- "function_name": "execute_code",
66
+ "function_name": "calculate",
65
67
  "params":
66
68
  {
67
- "code": <code>
69
+ "expression": <expression>
68
70
  }
69
71
  }
72
+
70
73
  """,
74
+
75
+ "fetch_baidu_results": """
76
+ ## 函数名:fetch_baidu_results,
77
+ 描述:在用户明确要求查询网络上相关信息时,调用此工具,返回查询结果。
78
+ 触发条件:用户明确要求查询网络上相关信息
79
+ 参数:
80
+ # query (str): 用户要求的查询内容
81
+ # max_n_links (int, optional): 搜索条目的最大数目,若用户指定了数目,则使用用户指定的数目,若用户提问中没有指定,你需要在下面的json中"max_n_links"这一项指定为数值3。
82
+ 返回值 (str): 联网搜索到的信息
83
+ 需要返回的json
84
+ {
85
+ "function_name": "fetch_baidu_results",
86
+ "params":
87
+ {
88
+ "query": <query from user question>,
89
+ "max_n_links": <num of max results, 如果用户没有要求,这一项则指定为3>
90
+ }
91
+ }
92
+
93
+ """,
94
+
71
95
  "default": None
72
96
  }
@@ -1,6 +1,7 @@
1
1
  import subprocess
2
2
  import sys
3
3
  import os
4
+ import math
4
5
 
5
6
  def execute_code(code):
6
7
  """
@@ -37,4 +38,27 @@ def execute_code(code):
37
38
  return "Error: Code execution timed out"
38
39
  except Exception as e:
39
40
  # Return the exception information for other exceptions
41
+ return f"Error: {str(e)}"
42
+
43
+
44
+ def calculate(expression):
45
+ """
46
+ Calculates the result of a mathematical expression.
47
+
48
+ This function evaluates a mathematical expression string passed as an argument and returns the result.
49
+ In order to prevent security risks, the use of built-in functions is restricted during evaluation,
50
+ allowing only the 'math' module to be accessed. If an exception occurs during evaluation,
51
+ it returns the corresponding error message.
52
+
53
+ Parameters:
54
+ expression (str): The mathematical expression to calculate.
55
+
56
+ Returns:
57
+ The result of the calculation or an error message if an exception occurs.
58
+ """
59
+ try:
60
+ # Evaluate the expression with restricted built-in functions and access to the math module
61
+ return eval(expression, {"__builtins__": None}, {"math": math})
62
+ except Exception as e:
63
+ # Return the error message if an exception occurs
40
64
  return f"Error: {str(e)}"
hdl/utils/llm/chat.py CHANGED
@@ -1,5 +1,6 @@
1
1
  import typing as t
2
2
  import asyncio
3
+ import os
3
4
  from concurrent.futures import ProcessPoolExecutor
4
5
  import subprocess
5
6
 
@@ -109,37 +110,31 @@ class OpenAI_M():
109
110
  server_ip: str = "172.28.1.2",
110
111
  server_port: int = 8000,
111
112
  api_key: str = "dummy_key",
113
+ use_groq: bool = False,
114
+ groq_api_key: str = None,
112
115
  tools: list = None,
113
116
  tool_desc: dict = None,
114
117
  *args,
115
118
  **kwargs
116
119
  ):
117
- """Initialize the OpenAI client with the specified parameters.
118
-
119
- Args:
120
- model_path (str): Path to the model (default is "default_model").
121
- device (str): Device to use (default is 'gpu').
122
- generation_kwargs (dict): Additional generation arguments (default is an empty dictionary).
123
- server_ip (str): IP address of the server (default is "172.28.1.2").
124
- server_port (int): Port of the server (default is 8000).
125
- api_key (str): API key for authentication (default is "dummy_key").
126
- tools (list): List of tools.
127
- tool_desc (dict): Description of tools.
128
-
129
- Raises:
130
- ValueError: If an invalid argument is provided.
131
- """
132
120
  # self.model_path = model_path
133
121
  self.server_ip = server_ip
134
122
  self.server_port = server_port
135
123
  self.base_url = f"http://{self.server_ip}:{str(self.server_port)}/v1"
136
124
  self.api_key = api_key
137
- self.client = OpenAI(
138
- base_url=self.base_url,
139
- api_key=self.api_key,
140
- *args,
141
- **kwargs
142
- )
125
+ self.use_groq = use_groq
126
+ if use_groq:
127
+ import groq
128
+ self.client = groq.Groq(
129
+ api_key=os.getenv("GROQ_API_KEY", groq_api_key)
130
+ )
131
+ else:
132
+ self.client = OpenAI(
133
+ base_url=self.base_url,
134
+ api_key=self.api_key,
135
+ *args,
136
+ **kwargs
137
+ )
143
138
  self.tools = tools
144
139
  self.tool_desc = FN_DESC
145
140
  if tool_desc is not None:
@@ -148,6 +143,7 @@ class OpenAI_M():
148
143
  def get_resp(
149
144
  self,
150
145
  prompt : str,
146
+ sys_info: str = None,
151
147
  images: list = None,
152
148
  image_keys: tuple = ("image_url", "url"),
153
149
  stop: list[str] | None = ["USER:", "ASSISTANT:"],
@@ -169,6 +165,7 @@ class OpenAI_M():
169
165
  Returns:
170
166
  dict: The response from the chatbot.
171
167
  """
168
+
172
169
  content = [
173
170
  {"type": "text", "text": prompt},
174
171
  ]
@@ -191,11 +188,19 @@ class OpenAI_M():
191
188
  else:
192
189
  content = prompt
193
190
 
191
+ messages = []
192
+ if sys_info:
193
+ messages.append({
194
+ "role": "system",
195
+ "content": sys_info
196
+ })
197
+ messages.append({
198
+ "role": "user",
199
+ "content": content
200
+ })
201
+
194
202
  response = self.client.chat.completions.create(
195
- messages=[{
196
- "role": "user",
197
- "content": content
198
- }],
203
+ messages=messages,
199
204
  stream=stream,
200
205
  model=model,
201
206
  **kwargs
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hjxdl
3
- Version: 0.2.34
3
+ Version: 0.2.36
4
4
  Summary: A collection of functions for Jupyter notebooks
5
5
  Home-page: https://github.com/huluxiaohuowa/hdl
6
6
  Author: Jianxing Hu
@@ -1,5 +1,5 @@
1
1
  hdl/__init__.py,sha256=GffnD0jLJdhkd-vo989v40N90sQbofkayRBwxc6TVhQ,72
2
- hdl/_version.py,sha256=p0KyMPbK4UjHdk55CM8u0WRgTg4ZEwuArtOrGaope7E,413
2
+ hdl/_version.py,sha256=lyCfIDEPFC5Me7JK9UYDQkfgyTpQxlULFu59ekOiSFA,413
3
3
  hdl/args/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  hdl/args/loss_args.py,sha256=s7YzSdd7IjD24rZvvOrxLLFqMZQb9YylxKeyelSdrTk,70
5
5
  hdl/controllers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -120,15 +120,15 @@ hdl/utils/chemical_tools/sdf.py,sha256=71PEqU0H885L6IeGHEa6n7ZLZThvMsZOVLuFG2wno
120
120
  hdl/utils/database_tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
121
121
  hdl/utils/database_tools/connect.py,sha256=xCacGucKxlQUXs6AsNddpeECvdqT1180V1ZWqHrUdNA,875
122
122
  hdl/utils/database_tools/datetime.py,sha256=xqE2xNiOpADzX-R8_bM0bioJRF3Ay9Jp1CAG6dy6uVI,1202
123
- hdl/utils/database_tools/web.py,sha256=vZJYWA02QbyUUMGLDX710cexn7RlfWeHa8YwK3UsDZ0,1934
123
+ hdl/utils/database_tools/web.py,sha256=HvU7BtODTRSgrO9Bho5Nj0ImtlAOJ9nrOfDPWPp7qE8,3386
124
124
  hdl/utils/desc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
125
- hdl/utils/desc/func_desc.py,sha256=ykqYBpGHQnXm6pJUFmrRMZBGIpbwrERfGrt3anyc5aU,2346
125
+ hdl/utils/desc/func_desc.py,sha256=tDGEuUuqg6LnBVpmWQIxYZPvrcb0N70A9i20PbujCks,2660
126
126
  hdl/utils/desc/template.py,sha256=a0UAkkKctt_EHY9UECsIIAwVkGPcM1Hr01HSkRMeIuw,1272
127
127
  hdl/utils/general/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
128
128
  hdl/utils/general/glob.py,sha256=8-RCnt6L297wMIfn34ZAMCsGCZUjHG3MGglGZI1cX0g,491
129
- hdl/utils/general/runners.py,sha256=-xGCkRKKqSEFUtDy0o8JkXpfFVrXPCU0C-ISfv-pNis,1413
129
+ hdl/utils/general/runners.py,sha256=w9kgR9UgGug0s6NR27hpfPQbbFvRtmtqz5IfwyMTC1E,2351
130
130
  hdl/utils/llm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
131
- hdl/utils/llm/chat.py,sha256=OzyY9xACOOocx9zZigtq9YAPvHtDUo8v2fvf1Tyjg_U,14891
131
+ hdl/utils/llm/chat.py,sha256=YEBr2-6mBMf5uaY9Rpcc8iWSBB6pJeefWcD0JuBTuTk,14668
132
132
  hdl/utils/llm/chatgr.py,sha256=lKaDeimYz-Bw32QXYtde51xjf7gbfS2CEYt5R0ODunM,4075
133
133
  hdl/utils/llm/embs.py,sha256=Tf0FOYrOFZp7qQpEPiSCXzlgyHH0X9HVTUtsup74a9E,7174
134
134
  hdl/utils/llm/extract.py,sha256=2sK_WJzmYIc8iuWaM9DA6Nw3_6q1O4lJ5pKpcZo-bBA,6512
@@ -139,7 +139,7 @@ hdl/utils/schedulers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hS
139
139
  hdl/utils/schedulers/norm_lr.py,sha256=bDwCmdEK-WkgxQMFBiMuchv8Mm7C0-GZJ6usm-PQk14,4461
140
140
  hdl/utils/weather/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
141
141
  hdl/utils/weather/weather.py,sha256=k11o6wM15kF8b9NMlEfrg68ak-SfSYLN3nOOflFUv-I,4381
142
- hjxdl-0.2.34.dist-info/METADATA,sha256=0pypdynugK_HBW9sYnKj3L-kywu8o2Zt7H36gI-dOwg,836
143
- hjxdl-0.2.34.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
144
- hjxdl-0.2.34.dist-info/top_level.txt,sha256=-kxwTM5JPhylp06z3zAVO3w6_h7wtBfBo2zgM6YZoTk,4
145
- hjxdl-0.2.34.dist-info/RECORD,,
142
+ hjxdl-0.2.36.dist-info/METADATA,sha256=YeGojS09qKg1ukjhX_RI0o7FBft1kaW_m0EutpopDsQ,836
143
+ hjxdl-0.2.36.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
144
+ hjxdl-0.2.36.dist-info/top_level.txt,sha256=-kxwTM5JPhylp06z3zAVO3w6_h7wtBfBo2zgM6YZoTk,4
145
+ hjxdl-0.2.36.dist-info/RECORD,,
File without changes