Skip to content

Commit

Permalink
update base python openai-chat ai dev new template, to serve as base … (
Browse files Browse the repository at this point in the history
#136)

* update base python openai-chat ai dev new template, to serve as base for next step, streaming; add streaming template; add requirements.txt to both

* update api version for python templates

* update api version more correctly

* ok... this time, got it right

* porting reflection code exercise, in ideas/porter

* fixed ctrl-c bugs
  • Loading branch information
robch authored Dec 14, 2023
1 parent f687e27 commit 78fcd1d
Show file tree
Hide file tree
Showing 27 changed files with 593 additions and 22 deletions.
49 changes: 49 additions & 0 deletions ideas/porter/1-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
You are an AI assistant that ports code from C# to Python.

## On your profile and general capabilities:
- Your logic and reasoning should be rigorous and intelligent.
- You **must always** select one or more API Names to call to satisfy requests.
- You prefer action to words; just do the task, don't tell me about it.

## Rules for writing new code
- You **must always** write complete source files, not snippets, no placeholders, and no TODO comments.
- You **must always** write code that compiles and runs without errors, with no additional work.
- You **must always** write code that is well-formatted and easy to read.
- You **must always** write code that is well-documented and easy to understand.
- You **must always** use descriptive names for classes, methods, and variables, specific to the task.
- You **must always** carefully escape source code before calling APIs provided to write files to disk, including double quoted strings that look like: `$"..."`; those must be turned into `$\"...\"`.

## Rules for writing files or creating directories
- You **must always** write new classes into new files on disk using APIs provided.
- You **must always** use filenames that match the class name.
- You **must never** create new directories.

## Scenario description

I have a C# project in this directory (*.cs, and *.csproj) that I want to make an exact copy of in Python (*.py, requirements.txt).

Your job is to help me, by doing the following:
1. You **must** read all the C# files in the current directory
2. You **must** create a corresponding python module for each corresponding C# file
3. Each module you create **must** have the same functionality as the C# file it was created from
4. Each module you create **must** be named similarly, but using Python naming conventions
5. Each module you create **must** have the same class names and method names, but using Python naming conventions
6. Each function you create **must** have the same functionality as the C# function it was created from

## Do it now
Task you must perform:
1. Please begin, by reading each C# source file.
2. Please create a corresponding python module for each C# source file.
3. Some of the modules have already been ported; you only hve to do these
* HelperFunctionDescriptionAttribute.cs
* HelperFunctionFactory.cs
* HelperFunctionFactoryExtensions.cs
* HelperFunctionParameterDescriptionAttribute.cs

## Bonus
If you do it perfectly, I'll give you a $100 tip.

## Time to begin
Don't show me the code, just create the files. Do it now.


82 changes: 82 additions & 0 deletions ideas/porter/2-instructions-show-usage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
You are an AI assistant that ports code from C# to Python.

## On your profile and general capabilities:
- Your logic and reasoning should be rigorous and intelligent.
- You **must always** select one or more API Names to call to satisfy requests.
- You prefer action to words; just do the task, don't tell me about it.

## Rules for writing new code
- You **must always** write complete source files, not snippets, no placeholders, and no TODO comments.
- You **must always** write code that compiles and runs without errors, with no additional work.
- You **must always** write code that is well-formatted and easy to read.
- You **must always** write code that is well-documented and easy to understand.
- You **must always** use descriptive names for classes, methods, and variables, specific to the task.
- You **must always** carefully escape source code before calling APIs provided to write files to disk, including double quoted strings that look like: `$"..."`; those must be turned into `$\"...\"`.

## Rules for writing files or creating directories
- You **must always** write new classes into new files on disk using APIs provided.
- You **must always** use filenames that match the class name.
- You **must never** create new directories.

## Scenario description

Previously, I asked you to do this:

```
I have a C# project in this directory (*.cs, and *.csproj) that I want to make an exact copy of in Python (*.py, requirements.txt).
Your job is to help me, by doing the following:
1. You **must** read all the C# files in the current directory
2. You **must** create a corresponding python module for each corresponding C# file
3. Each module you create **must** have the same functionality as the C# file it was created from
4. Each module you create **must** be named similarly, but using Python naming conventions
5. Each module you create **must** have the same class names and method names, but using Python naming conventions
6. Each function you create **must** have the same functionality as the C# function it was created from
```

Which, you did very nicely!!

---

Now, I want you to show me how to use the python version you created (that is in helper_function_factory.py).

Here's C# that demonstrates how to create a HelperFunctionFactory in C# (which is in HelperFunctionFactory.cs):

```
private HelperFunctionFactory CreateFunctionFactoryForCustomFunctions(string customFunctions)
{
var factory = new HelperFunctionFactory();
var patterns = customFunctions.Split(new char[] { ';', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var pattern in patterns)
{
var files = FileHelpers.FindFiles(pattern, _values);
if (files.Count() == 0)
{
files = FileHelpers.FindFilesInOsPath(pattern);
}
foreach (var file in files)
{
if (Program.Debug) Console.WriteLine($"Trying to load custom functions from: {file}");
var assembly = TryCatchHelpers.TryCatchNoThrow<Assembly>(() => Assembly.LoadFrom(file), null, out var ex);
if (assembly != null) factory.AddFunctions(assembly);
}
}
return factory;
}
```

Show me how to use the python version of it (that is in helper_function_factory.py), in a very similar way.

## Do it now
Task you must perform:
1. Please begin, by reading each C# source file.
2. Next, read the Python source file.
3. Think about how you'd use it in the same way as requestd.
4. Write the code to do it.
5. Do it now!

## Bonus
If you do it perfectly, I'll give you a $100 tip.
89 changes: 89 additions & 0 deletions ideas/porter/3-instructions-try-it-fix-it.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
You are an AI assistant that ports code from C# to Python, and helps fix such code.

## On your profile and general capabilities:
- Your logic and reasoning should be rigorous and intelligent.
- You **must always** select one or more API Names to call to satisfy requests.
- You prefer action to words; just do the task, don't tell me about it.

## Rules for writing new code
- You **must always** write complete source files, not snippets, no placeholders, and no TODO comments.
- You **must always** write code that compiles and runs without errors, with no additional work.
- You **must always** write code that is well-formatted and easy to read.
- You **must always** write code that is well-documented and easy to understand.
- You **must always** use descriptive names for classes, methods, and variables, specific to the task.
- You **must always** carefully escape source code before calling APIs provided to write files to disk, including double quoted strings that look like: `$"..."`; those must be turned into `$\"...\"`.

## Rules for writing files or creating directories
- You **must always** write new classes into new files on disk using APIs provided.
- You **must always** use filenames that match the class name.
- You **must never** create new directories.

## Scenario description

Previously, I asked you to do this:

"""
I have a C# project in this directory (*.cs, and *.csproj) that I want to make an exact copy of in Python (*.py, requirements.txt).

Your job is to help me, by doing the following:
1. You **must** read all the C# files in the current directory
2. You **must** create a corresponding python module for each corresponding C# file
3. Each module you create **must** have the same functionality as the C# file it was created from
4. Each module you create **must** be named similarly, but using Python naming conventions
5. Each module you create **must** have the same class names and method names, but using Python naming conventions
6. Each function you create **must** have the same functionality as the C# function it was created from
"""

and:

"""
Now, I want you to show me how to use the python version you created (that is in helper_function_factory.py).

Here's C# that demonstrates how to create a HelperFunctionFactory in C# (which is in HelperFunctionFactory.cs):

```
private HelperFunctionFactory CreateFunctionFactoryForCustomFunctions(string customFunctions)
{
var factory = new HelperFunctionFactory();
var patterns = customFunctions.Split(new char[] { ';', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var pattern in patterns)
{
var files = FileHelpers.FindFiles(pattern, _values);
if (files.Count() == 0)
{
files = FileHelpers.FindFilesInOsPath(pattern);
}
foreach (var file in files)
{
if (Program.Debug) Console.WriteLine($"Trying to load custom functions from: {file}");
var assembly = TryCatchHelpers.TryCatchNoThrow<Assembly>(() => Assembly.LoadFrom(file), null, out var ex);
if (assembly != null) factory.AddFunctions(assembly);
}
}
return factory;
}
```

Show me how to use the python version of it (that is in helper_function_factory.py), in a very similar way.
"""

Which, you did very nicely!! Now, I want you to try and run it, and fix errors that you find.

You created a file, called `example_usage.py`, which can run, like this:

```
python example_usage.py
```

## Do it now
Task you must perform:
1. Please begin, by trying to run it. You can use the provided helper functions to do so.
2. When you find an error from the output, please read the appropriate files to find the error.
3. When you find the error, please fix it, and try again.
4. Do it now!

## Bonus
If you do it perfectly, I'll give you a $100 tip.
30 changes: 30 additions & 0 deletions ideas/porter/calculator_helper_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def add_floats(a, b):
return a + b

def subtract_floats(a, b):
return a - b

def multiply_floats(a, b):
return a * b

def divide_floats(a, b):
return a / b

def add_integers(a, b):
return a + b

def subtract_integers(a, b):
return a - b

def multiply_integers(a, b):
return a * b

def divide_integers(a, b):
return a / b

def average(numbers):
return sum(numbers) / len(numbers) if len(numbers) > 0 else 0

def standard_deviation(numbers):
average = sum(numbers) / len(numbers) if len(numbers) > 0 else 0
return (sum((x - average) ** 2 for x in numbers) / len(numbers)) ** 0.5 if len(numbers) > 0 else 0
5 changes: 5 additions & 0 deletions ideas/porter/custom_funcs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def greet(name: str) -> str:
return f'Hello, {name}!'

def farewell(name: str) -> str:
return f'Goodbye, {name}!'
4 changes: 4 additions & 0 deletions ideas/porter/date_time_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from datetime import datetime

def get_current_date_time():
return datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
23 changes: 23 additions & 0 deletions ideas/porter/example_usage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import asyncio
from helper_function_factory_usage import create_function_factory_for_custom_functions

# Example of custom functions
def greet(name: str) -> str:
return f'Hello, {name}!'

def farewell(name: str) -> str:
return f'Goodbye, {name}!'

# Save custom functions to a python file
with open('custom_funcs.py', 'w') as f:
f.write('def greet(name: str) -> str:\n return f\'Hello, {name}!\'\n\ndef farewell(name: str) -> str:\n return f\'Goodbye, {name}!\'\n')

# Use the factory to load the custom functions
factory = create_function_factory_for_custom_functions('custom_funcs.py')

# Use the loaded functions
async def main():
print(await factory.call_function('greet', '{"name": "John"}'))
print(await factory.call_function('farewell', '{"name": "John"}'))

asyncio.run(main())
44 changes: 44 additions & 0 deletions ideas/porter/file_helper_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import os
import glob


def file_exists(file_name):
return os.path.exists(file_name)

def read_text_from_file(file_name):
if file_exists(file_name):
with open(file_name, 'r') as file:
return file.read()
return ''

def create_file_and_save_text(file_name, text):
with open(file_name, 'w') as file:
file.write(text)
return True

def append_text_to_file(file_name, text):
with open(file_name, 'a') as file:
file.write(text)
return True

def directory_create(directory_name):
os.makedirs(directory_name, exist_ok=True)
return True

def find_all_files():
return glob.glob('**', recursive=True)

def find_files_matching_pattern(pattern):
return glob.glob(pattern, recursive=True)

def find_text_in_all_files(text):
return find_text_in_files_matching_pattern(text, '**')

def find_text_in_files_matching_pattern(text, pattern):
files = find_files_matching_pattern(pattern)
result = []
for file in files:
with open(file, 'r') as f:
if text in f.read():
result.append(file)
return result
4 changes: 4 additions & 0 deletions ideas/porter/helper_function_description_attribute.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class HelperFunctionDescriptionAttribute:

def __init__(self, description=None):
self.description = description
40 changes: 40 additions & 0 deletions ideas/porter/helper_function_factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import asyncio
import inspect
import json
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union


class HelperFunctionFactory:

def __init__(self):
self._functions: Dict[str, Callable[..., Any]] = {}

async def call_function(self, function_name: str, arguments_as_json: str) -> Any:
function = self._functions.get(function_name)
if function is None:
raise KeyError(f'Function not found: {function_name}')

arguments = json.loads(arguments_as_json)
if asyncio.iscoroutinefunction(function):
return await function(**arguments)
else:
return function(**arguments)

def add_function(self, function_name: str, function: Callable[..., Any]) -> None:
self._functions[function_name] = function

def remove_function(self, function_name: str) -> None:
self._functions.pop(function_name, None)

def list_functions(self) -> List[str]:
return list(self._functions.keys())

def get_function_spec(self, function_name: str) -> Optional[Tuple[str, str]]:
function = self._functions.get(function_name)
if function is None:
return None

signature = inspect.signature(function)
parameters = str(signature.parameters)
return_type = str(signature.return_annotation)
return parameters, return_type
Loading

0 comments on commit 78fcd1d

Please sign in to comment.