ag2 0.4b1__py3-none-any.whl → 0.4.1__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.

Potentially problematic release.


This version of ag2 might be problematic. Click here for more details.

Files changed (78) hide show
  1. {ag2-0.4b1.dist-info → ag2-0.4.1.dist-info}/METADATA +13 -9
  2. ag2-0.4.1.dist-info/RECORD +158 -0
  3. autogen/agentchat/contrib/agent_builder.py +1 -0
  4. autogen/agentchat/contrib/agent_eval/agent_eval.py +107 -0
  5. autogen/agentchat/contrib/agent_eval/criterion.py +47 -0
  6. autogen/agentchat/contrib/agent_eval/critic_agent.py +47 -0
  7. autogen/agentchat/contrib/agent_eval/quantifier_agent.py +42 -0
  8. autogen/agentchat/contrib/agent_eval/subcritic_agent.py +48 -0
  9. autogen/agentchat/contrib/agent_eval/task.py +43 -0
  10. autogen/agentchat/contrib/captainagent/tools/__init__.py +0 -0
  11. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_correlation.py +41 -0
  12. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_skewness_and_kurtosis.py +29 -0
  13. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_iqr.py +29 -0
  14. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_zscore.py +29 -0
  15. autogen/agentchat/contrib/captainagent/tools/data_analysis/explore_csv.py +22 -0
  16. autogen/agentchat/contrib/captainagent/tools/data_analysis/shapiro_wilk_test.py +31 -0
  17. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_download.py +26 -0
  18. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_search.py +55 -0
  19. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_image.py +54 -0
  20. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_text.py +39 -0
  21. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_wikipedia_text.py +22 -0
  22. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_youtube_caption.py +35 -0
  23. autogen/agentchat/contrib/captainagent/tools/information_retrieval/image_qa.py +61 -0
  24. autogen/agentchat/contrib/captainagent/tools/information_retrieval/optical_character_recognition.py +62 -0
  25. autogen/agentchat/contrib/captainagent/tools/information_retrieval/perform_web_search.py +48 -0
  26. autogen/agentchat/contrib/captainagent/tools/information_retrieval/scrape_wikipedia_tables.py +34 -0
  27. autogen/agentchat/contrib/captainagent/tools/information_retrieval/transcribe_audio_file.py +22 -0
  28. autogen/agentchat/contrib/captainagent/tools/information_retrieval/youtube_download.py +36 -0
  29. autogen/agentchat/contrib/captainagent/tools/math/calculate_circle_area_from_diameter.py +22 -0
  30. autogen/agentchat/contrib/captainagent/tools/math/calculate_day_of_the_week.py +19 -0
  31. autogen/agentchat/contrib/captainagent/tools/math/calculate_fraction_sum.py +29 -0
  32. autogen/agentchat/contrib/captainagent/tools/math/calculate_matrix_power.py +32 -0
  33. autogen/agentchat/contrib/captainagent/tools/math/calculate_reflected_point.py +17 -0
  34. autogen/agentchat/contrib/captainagent/tools/math/complex_numbers_product.py +26 -0
  35. autogen/agentchat/contrib/captainagent/tools/math/compute_currency_conversion.py +24 -0
  36. autogen/agentchat/contrib/captainagent/tools/math/count_distinct_permutations.py +28 -0
  37. autogen/agentchat/contrib/captainagent/tools/math/evaluate_expression.py +29 -0
  38. autogen/agentchat/contrib/captainagent/tools/math/find_continuity_point.py +35 -0
  39. autogen/agentchat/contrib/captainagent/tools/math/fraction_to_mixed_numbers.py +40 -0
  40. autogen/agentchat/contrib/captainagent/tools/math/modular_inverse_sum.py +23 -0
  41. autogen/agentchat/contrib/captainagent/tools/math/simplify_mixed_numbers.py +37 -0
  42. autogen/agentchat/contrib/captainagent/tools/math/sum_of_digit_factorials.py +16 -0
  43. autogen/agentchat/contrib/captainagent/tools/math/sum_of_primes_below.py +16 -0
  44. autogen/agentchat/contrib/captainagent/tools/requirements.txt +10 -0
  45. autogen/agentchat/contrib/captainagent/tools/tool_description.tsv +34 -0
  46. autogen/agentchat/contrib/captainagent.py +3 -0
  47. autogen/agentchat/contrib/graph_rag/document.py +6 -0
  48. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +55 -20
  49. autogen/agentchat/contrib/graph_rag/falkor_graph_rag_capability.py +81 -0
  50. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +7 -1
  51. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +12 -4
  52. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +7 -3
  53. autogen/agentchat/contrib/swarm_agent.py +69 -20
  54. autogen/agentchat/contrib/tool_retriever.py +6 -0
  55. autogen/coding/base.py +2 -2
  56. autogen/coding/docker_commandline_code_executor.py +2 -2
  57. autogen/coding/factory.py +2 -2
  58. autogen/coding/func_with_reqs.py +2 -2
  59. autogen/coding/jupyter/base.py +2 -2
  60. autogen/coding/jupyter/docker_jupyter_server.py +2 -2
  61. autogen/coding/jupyter/embedded_ipython_code_executor.py +2 -2
  62. autogen/coding/jupyter/jupyter_client.py +2 -2
  63. autogen/coding/jupyter/jupyter_code_executor.py +2 -2
  64. autogen/coding/jupyter/local_jupyter_server.py +2 -2
  65. autogen/coding/local_commandline_code_executor.py +2 -2
  66. autogen/coding/markdown_code_extractor.py +2 -2
  67. autogen/coding/utils.py +2 -2
  68. autogen/oai/bedrock.py +6 -0
  69. autogen/oai/cerebras.py +6 -0
  70. autogen/oai/ollama.py +6 -0
  71. autogen/oai/openai_utils.py +1 -0
  72. autogen/token_count_utils.py +2 -0
  73. autogen/version.py +1 -1
  74. ag2-0.4b1.dist-info/RECORD +0 -115
  75. {ag2-0.4b1.dist-info → ag2-0.4.1.dist-info}/LICENSE +0 -0
  76. {ag2-0.4b1.dist-info → ag2-0.4.1.dist-info}/NOTICE.md +0 -0
  77. {ag2-0.4b1.dist-info → ag2-0.4.1.dist-info}/WHEEL +0 -0
  78. {ag2-0.4b1.dist-info → ag2-0.4.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,19 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def calculate_day_of_the_week(total_days: int, starting_day: str):
5
+ """
6
+ Calculates the day of the week after a given number of days starting from a specified day.
7
+
8
+ Args:
9
+ total_days: The number of days to calculate.
10
+ starting_day: The starting day of the week, should be one of 'Monday', 'Tuesday', 'Wednesday', etc.
11
+
12
+ Returns:
13
+ str: The day of the week after the specified number of days.
14
+ """
15
+ days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
16
+
17
+ start_index = days_of_week.index(starting_day)
18
+ end_index = (start_index + total_days) % 7
19
+ return days_of_week[end_index]
@@ -0,0 +1,29 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def calculate_fraction_sum(
5
+ fraction1_numerator: int, fraction1_denominator: int, fraction2_numerator: int, fraction2_denominator: int
6
+ ):
7
+ """
8
+ Calculates the sum of two fractions and returns the result as a mixed number.
9
+
10
+ Args:
11
+ fraction1_numerator: The numerator of the first fraction.
12
+ fraction1_denominator: The denominator of the first fraction.
13
+ fraction2_numerator: The numerator of the second fraction.
14
+ fraction2_denominator: The denominator of the second fraction.
15
+
16
+ Returns:
17
+ str: The sum of the two fractions as a mixed number in the format 'a b/c'
18
+ """
19
+ from fractions import Fraction
20
+
21
+ fraction1 = Fraction(fraction1_numerator, fraction1_denominator)
22
+ fraction2 = Fraction(fraction2_numerator, fraction2_denominator)
23
+ result = fraction1 + fraction2
24
+ mixed_number = result.numerator // result.denominator
25
+ mixed_fraction_numerator = result.numerator % result.denominator
26
+ if mixed_fraction_numerator > 0:
27
+ return f"{mixed_number} {Fraction(mixed_fraction_numerator, result.denominator)}"
28
+ else:
29
+ return str(mixed_number)
@@ -0,0 +1,32 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from autogen.coding.func_with_reqs import with_requirements
5
+
6
+
7
+ @with_requirements(["sympy"])
8
+ def calculate_matrix_power(matrix, power):
9
+ """
10
+ Calculate the power of a given matrix.
11
+
12
+ Args:
13
+ matrix (list): An array of numbers that represents the matrix.
14
+ power (int): The power to which the matrix is raised.
15
+
16
+ Returns:
17
+ Matrix: The resulting matrix after raising to power.
18
+
19
+ Raises:
20
+ ValueError: If the power is negative and the matrix is not invertible.
21
+ """
22
+ from sympy import Matrix, eye
23
+
24
+ m = Matrix(matrix)
25
+ if power == 0:
26
+ return eye(m.shape[0])
27
+ elif power < 0:
28
+ if not m.is_invertible():
29
+ raise ValueError("Matrix is not invertible.")
30
+ return m.inverse() ** (-power)
31
+ elif power > 0:
32
+ return m**power
@@ -0,0 +1,17 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def calculate_reflected_point(point):
5
+ """
6
+ Calculates the reflection point of a given point about the line y=x.
7
+
8
+ Args:
9
+ point (dict): A dictionary representing the coordinates of the point.
10
+ The dictionary should have keys 'x' and 'y' representing the x and y coordinates respectively.
11
+
12
+ Returns:
13
+ dict: A dictionary representing the coordinates of the reflected point. Its keys are 'x' and 'y'.
14
+ """
15
+ # Swap x and y for reflection about y=x
16
+ reflected_point = {"x": point["y"], "y": point["x"]}
17
+ return reflected_point
@@ -0,0 +1,26 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from autogen.coding.func_with_reqs import with_requirements
5
+
6
+
7
+ @with_requirements(["sympy"])
8
+ def complex_numbers_product(complex_numbers):
9
+ """
10
+ Calculates the product of a list of complex numbers.
11
+
12
+ Args:
13
+ complex_numbers (list): A list of dictionaries representing complex numbers.
14
+ Each dictionary should have 'real' and 'imag' keys representing the real
15
+ and imaginary parts of the complex number.
16
+
17
+ Returns:
18
+ complex: The simplified product of the complex numbers.
19
+
20
+ """
21
+ from sympy import I, simplify
22
+
23
+ result = 1
24
+ for c in complex_numbers:
25
+ result *= c["real"] + I * c["imag"]
26
+ return simplify(result)
@@ -0,0 +1,24 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from autogen.coding.func_with_reqs import with_requirements
5
+
6
+
7
+ @with_requirements(["sympy"])
8
+ def compute_currency_conversion(amount, exchange_rate):
9
+ """
10
+ Compute the currency conversion of the given amount using the provided exchange rate.
11
+
12
+ Args:
13
+ amount (float): The amount to be converted.
14
+ exchange_rate (float): The exchange rate to use for the conversion, represented as the amount of second currency equivalent to one unit of the first currency.
15
+
16
+ Returns:
17
+ float: The converted amount.
18
+
19
+ """
20
+ from sympy import Rational
21
+
22
+ # Calculate the converted amount using the given exchange rate
23
+ converted_amount = Rational(amount, exchange_rate)
24
+ return float(converted_amount)
@@ -0,0 +1,28 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def count_distinct_permutations(sequence):
5
+ """
6
+ Counts the number of distinct permutations of a sequence where items may be indistinguishable.
7
+
8
+ Args:
9
+ sequence (iterable): The sequence for which to count the distinct permutations.
10
+
11
+ Returns:
12
+ int: The number of distinct permutations.
13
+
14
+ Example:
15
+ >>> count_distinct_permutations('aab')
16
+ 3
17
+ >>> count_distinct_permutations([1, 2, 2])
18
+ 3
19
+ """
20
+ from collections import Counter
21
+ from math import factorial
22
+
23
+ counts = Counter(sequence)
24
+ total_length = sum(counts.values())
25
+ permutations = factorial(total_length)
26
+ for count in counts.values():
27
+ permutations //= factorial(count)
28
+ return permutations
@@ -0,0 +1,29 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def evaluate_expression(expression):
5
+ """
6
+ Evaluates a mathematical expression with support for floor function notation and power notation.
7
+
8
+ Args:
9
+ expression (str): The mathematical expression to evaluate. It can only contain one symbol 'x'.
10
+
11
+ Returns:
12
+ Union[sympy.Expr, str]: The evaluated result as a sympy expression if successful,
13
+ otherwise an error message as a string.
14
+
15
+ """
16
+ from sympy import symbols, sympify
17
+
18
+ # Replace power with ** for sympy
19
+ expression = expression.replace("^", "**")
20
+ # Replace the floor function notation
21
+ expression = expression.replace("\\lfloor", "floor(").replace("\\rfloor", ")")
22
+ try:
23
+ # Create a symbol 'x' for use in case it is in the expression
24
+ symbols("x")
25
+ # Evaluate the expression
26
+ result = sympify(expression)
27
+ return result
28
+ except Exception as e:
29
+ return str(e)
@@ -0,0 +1,35 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def find_continuity_point(f_leq, f_gt, x_value):
5
+ """
6
+ Find the value 'a' that ensures the continuity of a piecewise function at a given point.
7
+
8
+ Args:
9
+ f_leq (str): The function expression for f(x) when x is less than or equal to the continuity point, in the form of a string.
10
+ f_gt (str): The function expression for f(x) when x is greater than the continuity point, in the form of a string.
11
+ x_value (float): The x-value at which continuity is to be ensured.
12
+
13
+ Returns:
14
+ float or None: The value of 'a' that satisfies the continuity condition,
15
+ or None if no such value exists.
16
+ """
17
+ from sympy import Eq, solve, symbols, sympify
18
+
19
+ x, a = symbols("x a")
20
+
21
+ # Convert string to sympy expression
22
+ f_leq_expr = sympify(f_leq)
23
+ f_gt_expr = sympify(f_gt)
24
+
25
+ # Evaluate the expressions at the given x_value
26
+ f_leq_value = f_leq_expr.subs(x, x_value)
27
+ f_gt_value = f_gt_expr.subs(x, x_value)
28
+
29
+ # Set up the equation for a
30
+ equation = Eq(f_leq_value, f_gt_value)
31
+
32
+ # Solve the equation
33
+ a_value = solve(equation, a)
34
+
35
+ return a_value[0] if a_value else None
@@ -0,0 +1,40 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def fraction_to_mixed_numbers(numerator, denominator):
5
+ """
6
+ Simplifies a fraction to its lowest terms and returns it as a mixed number.
7
+
8
+ Args:
9
+ numerator (int): The numerator of the fraction.
10
+ denominator (int): The denominator of the fraction.
11
+
12
+ Returns:
13
+ str: The simplified fraction as a string. If the fraction is already an integer, it returns the integer as a string.
14
+ If the fraction is a proper fraction, it returns the mixed number representation as a string.
15
+ If the numerator or denominator is not an integer, it returns an error message.
16
+ If the denominator is zero, it returns an error message.
17
+ """
18
+ from sympy import Rational
19
+
20
+ # Ensure that numerator and denominator are integers
21
+ if not isinstance(numerator, int) or not isinstance(denominator, int):
22
+ return "Error: Numerator and denominator must be integers."
23
+
24
+ # Handle the case where the denominator is zero
25
+ if denominator == 0:
26
+ return "Error: Denominator cannot be zero."
27
+
28
+ # Simplify the fraction to its lowest terms
29
+ result = Rational(numerator, denominator)
30
+ # Return the result as a mixed number if needed
31
+ if result.is_integer:
32
+ return str(int(result))
33
+ else:
34
+ # Result as a mixed number
35
+ integer_part = int(result)
36
+ fractional_part = result - integer_part
37
+ if fractional_part != 0:
38
+ return f"{integer_part} {fractional_part}"
39
+ else:
40
+ return str(integer_part)
@@ -0,0 +1,23 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def modular_inverse_sum(expressions, modulus):
5
+ """
6
+ Calculates the sum of modular inverses of the given expressions modulo the specified modulus.
7
+
8
+ Args:
9
+ expressions (list): A list of numbers for which the modular inverses need to be calculated.
10
+ modulus (int): The modulus value.
11
+
12
+ Returns:
13
+ int: The sum of modular inverses modulo the specified modulus.
14
+ """
15
+ from sympy import mod_inverse
16
+
17
+ mod_sum = 0
18
+ for number in expressions:
19
+ try:
20
+ mod_sum += mod_inverse(number, modulus)
21
+ except ValueError:
22
+ pass # If modular inverse does not exist, skip the term
23
+ return mod_sum % modulus
@@ -0,0 +1,37 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def simplify_mixed_numbers(numerator1, denominator1, numerator2, denominator2, whole_number1, whole_number2):
5
+ """
6
+ Simplifies the sum of two mixed numbers and returns the result as a string in the format 'a b/c'.
7
+
8
+ Args:
9
+ numerator1 (int): The numerator of the first fraction.
10
+ denominator1 (int): The denominator of the first fraction.
11
+ numerator2 (int): The numerator of the second fraction.
12
+ denominator2 (int): The denominator of the second fraction.
13
+ whole_number1 (int): The whole number part of the first mixed number.
14
+ whole_number2 (int): The whole number part of the second mixed number.
15
+
16
+ Returns:
17
+ str: The simplified sum of the two mixed numbers as a string in the format 'a b/c'.
18
+ """
19
+ from fractions import Fraction
20
+
21
+ # Convert mixed numbers to improper fractions
22
+ fraction1 = whole_number1 * denominator1 + numerator1
23
+ fraction2 = whole_number2 * denominator2 + numerator2
24
+ # Create Fraction objects
25
+ frac1 = Fraction(fraction1, denominator1)
26
+ frac2 = Fraction(fraction2, denominator2)
27
+ # Calculate the sum
28
+ result = frac1 + frac2
29
+ # Convert to mixed number
30
+ mixed_number = result.numerator // result.denominator
31
+ mixed_fraction_numerator = result.numerator % result.denominator
32
+ mixed_fraction = Fraction(mixed_fraction_numerator, result.denominator)
33
+ # Return as a string in the format 'a b/c'
34
+ if mixed_fraction_numerator > 0:
35
+ return f"{mixed_number} {mixed_fraction}"
36
+ else:
37
+ return str(mixed_number)
@@ -0,0 +1,16 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def sum_of_digit_factorials(number):
5
+ """
6
+ Calculates the sum of the factorial of each digit in a number, often used in problems involving curious numbers like 145.
7
+
8
+ Args:
9
+ number (int): The number for which to calculate the sum of digit factorials.
10
+
11
+ Returns:
12
+ int: The sum of the factorials of the digits in the given number.
13
+ """
14
+ from math import factorial
15
+
16
+ return sum(factorial(int(digit)) for digit in str(number))
@@ -0,0 +1,16 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ def sum_of_primes_below(threshold):
5
+ """
6
+ Calculates the sum of all prime numbers below a given threshold.
7
+
8
+ Args:
9
+ threshold (int): The maximum number (exclusive) up to which primes are summed.
10
+
11
+ Returns:
12
+ int: The sum of all prime numbers below the threshold.
13
+ """
14
+ from sympy import primerange
15
+
16
+ return sum(primerange(2, threshold))
@@ -0,0 +1,10 @@
1
+ markdownify
2
+ arxiv
3
+ pymupdf
4
+ wikipedia-api
5
+ easyocr
6
+ python-pptx
7
+ openai-whisper
8
+ pandas
9
+ scipy
10
+ sentence-transformers
@@ -0,0 +1,34 @@
1
+ docid document_content
2
+ 1 math complex_numbers_product Calculates the product of a list of complex numbers.
3
+ 2 math calculate_matrix_power Calculate the power of a given matrix.
4
+ 3 math calculate_day_of_the_week Calculates the day of the week after a given number of days starting from a specified day.
5
+ 4 math modular_inverse_sum Calculates the sum of modular inverses of the given expressions modulo the specified modulus.
6
+ 5 math sum_of_digit_factorials Calculates the sum of the factorial of each digit in a number, often used in problems involving curious numbers like 145.
7
+ 6 math sum_of_primes_below Calculates the sum of all prime numbers below a given threshold.
8
+ 7 math evaluate_expression Evaluates a mathematical expression with support for floor function notation and power notation.
9
+ 8 math compute_currency_conversion Compute the currency conversion of the given amount using the provided exchange rate.
10
+ 9 math find_continuity_point Find the value 'a' that ensures the continuity of a piecewise function at a given point.
11
+ 10 math simplify_mixed_numbers Simplifies the sum of two mixed numbers and returns the result as a string in the format 'a b/c'.
12
+ 11 math fraction_to_mixed_numbers Simplifies a fraction to its lowest terms and returns it as a mixed number.
13
+ 12 math calculate_fraction_sum Calculates the sum of two fractions and returns the result as a mixed number.
14
+ 13 math count_distinct_permutations Counts the number of distinct permutations of a sequence where items may be indistinguishable.
15
+ 14 math calculate_circle_area_from_diameter Calculate the area of a circle given its diameter.
16
+ 15 math calculate_reflected_point Calculates the reflection point of a given point about the line y=x.
17
+ 16 data_analysis explore_csv Reads a CSV file and prints the column names, shape, data types, and the first few lines of data.
18
+ 17 data_analysis calculate_correlation Calculate the correlation between two columns in a CSV file.
19
+ 18 data_analysis detect_outlier_zscore Detect outliers in a CSV file based on a specified column. The outliers are determined by calculating the z-score of the data points in the column.
20
+ 19 data_analysis detect_outlier_iqr Detect outliers in a specified column of a CSV file using the IQR method.
21
+ 20 data_analysis shapiro_wilk_test Perform the Shapiro-Wilk test on a specified column of a CSV file.
22
+ 21 data_analysis calculate_skewness_and_kurtosis Calculate the skewness and kurtosis of a specified column in a CSV file. The kurtosis is calculated using the Fisher definition. The two metrics are computed using scipy.stats functions.
23
+ 22 information_retrieval perform_web_search Perform a web search using Bing API.
24
+ 23 information_retrieval transcribe_audio_file Transcribes the audio file located at the given file path.
25
+ 24 information_retrieval arxiv_search Search for articles on arXiv based on the given query.
26
+ 25 information_retrieval arxiv_download Downloads PDF files from ArXiv based on a list of arxiv paper IDs.
27
+ 26 information_retrieval scrape_wikipedia_tables Scrapes Wikipedia tables based on a given URL and header keyword.
28
+ 27 information_retrieval extract_pdf_text Extracts text from a specified page or the entire PDF file.
29
+ 28 information_retrieval extract_pdf_image Extracts images from a PDF file and saves them to the specified output directory.
30
+ 29 information_retrieval image_qa Perform question answering on an image using a pre-trained VQA model.
31
+ 30 information_retrieval optical_character_recognition Perform optical character recognition (OCR) on the given image.
32
+ 31 information_retrieval get_youtube_caption Retrieves the captions for a YouTube video.
33
+ 32 information_retrieval youtube_download Downloads a YouTube video and returns the download link.
34
+ 33 information_retrieval get_wikipedia_text Retrieves the text content of a Wikipedia page. It does not support tables and other complex formatting.
@@ -1,3 +1,6 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
1
4
  import hashlib
2
5
  import json
3
6
  import os
@@ -1,3 +1,9 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
+ # SPDX-License-Identifier: MIT
1
7
  from dataclasses import dataclass
2
8
  from enum import Enum, auto
3
9
  from typing import Optional
@@ -1,21 +1,24 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
1
5
  import os
2
- from dataclasses import field
6
+ from dataclasses import dataclass, field
3
7
  from typing import List
4
8
 
5
9
  from graphrag_sdk import KnowledgeGraph, Source
6
- from graphrag_sdk.schema import Schema
10
+ from graphrag_sdk.model_config import KnowledgeGraphModelConfig
11
+ from graphrag_sdk.models import GenerativeModel
12
+ from graphrag_sdk.models.openai import OpenAiGenerativeModel
13
+ from graphrag_sdk.ontology import Ontology
7
14
 
8
15
  from .document import Document
9
16
  from .graph_query_engine import GraphStoreQueryResult
10
17
 
11
18
 
12
- class FalkorGraphQueryResult(GraphStoreQueryResult):
13
- messages: list = field(default_factory=list)
14
-
15
-
16
19
  class FalkorGraphQueryEngine:
17
20
  """
18
- This is a wrapper for Falkor DB KnowledgeGraph.
21
+ This is a wrapper for FalkorDB KnowledgeGraph.
19
22
  """
20
23
 
21
24
  def __init__(
@@ -25,11 +28,11 @@ class FalkorGraphQueryEngine:
25
28
  port: int = 6379,
26
29
  username: str | None = None,
27
30
  password: str | None = None,
28
- model: str = "gpt-4-1106-preview",
29
- schema: Schema | None = None,
31
+ model: GenerativeModel = OpenAiGenerativeModel("gpt-4o"),
32
+ ontology: Ontology | None = None,
30
33
  ):
31
34
  """
32
- Initialize a Falkor DB knowledge graph.
35
+ Initialize a FalkorDB knowledge graph.
33
36
  Please also refer to https://github.com/FalkorDB/GraphRAG-SDK/blob/main/graphrag_sdk/kg.py
34
37
 
35
38
  Args:
@@ -38,11 +41,18 @@ class FalkorGraphQueryEngine:
38
41
  port (int): FalkorDB port number.
39
42
  username (str|None): FalkorDB username.
40
43
  password (str|None): FalkorDB password.
41
- model (str): OpenAI model to use for Falkor DB to build and retrieve from the graph.
42
- schema: Falkor DB knowledge graph schema (ontology), https://github.com/FalkorDB/GraphRAG-SDK/blob/main/graphrag_sdk/schema/schema.py
43
- If None, Falkor DB will auto generate a schema from the input docs.
44
+ model (GenerativeModel): LLM model to use for FalkorDB to build and retrieve from the graph, default to use OAI gpt-4o.
45
+ ontology: FalkorDB knowledge graph schema/ontology, https://github.com/FalkorDB/GraphRAG-SDK/blob/main/graphrag_sdk/ontology.py
46
+ If None, FalkorDB will auto generate an ontology from the input docs.
44
47
  """
45
- self.knowledge_graph = KnowledgeGraph(name, host, port, username, password, model, schema)
48
+ self.name = name
49
+ self.host = host
50
+ self.port = port
51
+ self.username = username
52
+ self.password = password
53
+ self.model = model
54
+ self.model_config = KnowledgeGraphModelConfig.with_model(model)
55
+ self.ontology = ontology
46
56
 
47
57
  def init_db(self, input_doc: List[Document] | None):
48
58
  """
@@ -54,14 +64,33 @@ class FalkorGraphQueryEngine:
54
64
  sources.append(Source(doc.path_or_url))
55
65
 
56
66
  if sources:
67
+ # Auto generate graph ontology if not created by user.
68
+ if self.ontology is None:
69
+ self.ontology = Ontology.from_sources(
70
+ sources=sources,
71
+ model=self.model,
72
+ )
73
+
74
+ self.knowledge_graph = KnowledgeGraph(
75
+ name=self.name,
76
+ host=self.host,
77
+ port=self.port,
78
+ username=self.username,
79
+ password=self.password,
80
+ model_config=KnowledgeGraphModelConfig.with_model(self.model),
81
+ ontology=self.ontology,
82
+ )
83
+
84
+ # Establish a chat session, this will maintain the history
85
+ self._chat_session = self.knowledge_graph.chat_session()
57
86
  self.knowledge_graph.process_sources(sources)
58
87
 
59
88
  def add_records(self, new_records: List) -> bool:
60
- raise NotImplementedError("This method is not supported by Falkor DB SDK yet.")
89
+ raise NotImplementedError("This method is not supported by FalkorDB SDK yet.")
61
90
 
62
- def query(self, question: str, n_results: int = 1, **kwargs) -> FalkorGraphQueryResult:
91
+ def query(self, question: str, n_results: int = 1, **kwargs) -> GraphStoreQueryResult:
63
92
  """
64
- Query the knowledage graph with a question and optional message history.
93
+ Query the knowledge graph with a question and optional message history.
65
94
 
66
95
  Args:
67
96
  question: a human input question.
@@ -71,6 +100,12 @@ class FalkorGraphQueryEngine:
71
100
 
72
101
  Returns: FalkorGraphQueryResult
73
102
  """
74
- messages = kwargs.pop("messages", [])
75
- answer, messages = self.knowledge_graph.ask(question, messages)
76
- return FalkorGraphQueryResult(answer=answer, results=[], messages=messages)
103
+ if self.knowledge_graph is None:
104
+ raise ValueError("Knowledge graph is not created.")
105
+
106
+ response = self._chat_session.send_message(question)
107
+
108
+ # History will be considered when querying by setting the last_answer
109
+ self._chat_session.last_answer = response["response"]
110
+
111
+ return GraphStoreQueryResult(answer=response["response"], results=[])
@@ -0,0 +1,81 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any, Dict, List, Optional, Tuple, Union
6
+
7
+ from autogen import Agent, ConversableAgent, UserProxyAgent
8
+
9
+ from .falkor_graph_query_engine import FalkorGraphQueryEngine
10
+ from .graph_query_engine import GraphStoreQueryResult
11
+ from .graph_rag_capability import GraphRagCapability
12
+
13
+
14
+ class FalkorGraphRagCapability(GraphRagCapability):
15
+ """
16
+ The FalkorDB GraphRAG capability integrate FalkorDB with graphrag_sdk version: 0.1.3b0.
17
+ Ref: https://github.com/FalkorDB/GraphRAG-SDK/tree/2-move-away-from-sql-to-json-ontology-detection
18
+
19
+ For usage, please refer to example notebook/agentchat_graph_rag_falkordb.ipynb
20
+ """
21
+
22
+ def __init__(self, query_engine: FalkorGraphQueryEngine):
23
+ """
24
+ initialize GraphRAG capability with a graph query engine
25
+ """
26
+ self.query_engine = query_engine
27
+
28
+ def add_to_agent(self, agent: UserProxyAgent):
29
+ """
30
+ Add FalkorDB GraphRAG capability to a UserProxyAgent.
31
+ The restriction to a UserProxyAgent to make sure the returned message does not contain information retrieved from the graph DB instead of any LLMs.
32
+ """
33
+ self.graph_rag_agent = agent
34
+
35
+ # Validate the agent config
36
+ if agent.llm_config not in (None, False):
37
+ raise Exception(
38
+ "Agents with GraphRAG capabilities do not use an LLM configuration. Please set your llm_config to None or False."
39
+ )
40
+
41
+ # Register method to generate the reply using a FalkorDB query
42
+ # All other reply methods will be removed
43
+ agent.register_reply(
44
+ [ConversableAgent, None], self._reply_using_falkordb_query, position=0, remove_other_reply_funcs=True
45
+ )
46
+
47
+ def _reply_using_falkordb_query(
48
+ self,
49
+ recipient: ConversableAgent,
50
+ messages: Optional[List[Dict]] = None,
51
+ sender: Optional[Agent] = None,
52
+ config: Optional[Any] = None,
53
+ ) -> Tuple[bool, Union[str, Dict, None]]:
54
+ """
55
+ Query FalkorDB and return the message. Internally, it utilises OpenAI to generate a reply based on the given messages.
56
+ The history with FalkorDB is also logged and updated.
57
+
58
+ If no results are found, a default message is returned: "I'm sorry, I don't have an answer for that."
59
+
60
+ Args:
61
+ recipient: The agent instance that will receive the message.
62
+ messages: A list of messages in the conversation history with the sender.
63
+ sender: The agent instance that sent the message.
64
+ config: Optional configuration for message processing.
65
+
66
+ Returns:
67
+ A tuple containing a boolean indicating success and the assistant's reply.
68
+ """
69
+ question = self._get_last_question(messages[-1])
70
+ result: GraphStoreQueryResult = self.query_engine.query(question)
71
+
72
+ return True, result.answer if result.answer else "I'm sorry, I don't have an answer for that."
73
+
74
+ def _get_last_question(self, message: Union[Dict, str]):
75
+ """Retrieves the last message from the conversation history."""
76
+ if isinstance(message, str):
77
+ return message
78
+ if isinstance(message, Dict):
79
+ if "content" in message:
80
+ return message["content"]
81
+ return None