Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
guybinya committed Sep 21, 2024
0 parents commit 380581e
Show file tree
Hide file tree
Showing 13 changed files with 994 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

401 changes: 401 additions & 0 deletions .idea/dbnavigator.xml

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions .idea/give-me-answers.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Guy Binyamin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
88 changes: 88 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# give-me-answers

This lightweight utility is designed to help you quickly get AI-generated answers from OpenAI with minimal setup. It includes Zod schema validation, making it easy to ensure responses are structured the way you need.

## Installation

You can install this package using npm:

```bash
npm install give-me-answers
```

## Usage

### Importing the Package

```typescript
import { openAiRequestWithSchema, giveMeAiMessages, craftJsonSchemaPrompt } from 'give-me-answers';
```

### Example Usage

```typescript
import { z } from 'zod';
import { openAiRequestWithSchema, giveMeAiMessages } from 'give-me-answers';

// Define your schema using Zod
const responseSchema = z.object({
name: z.string(),
age: z.number()
});

// Create messages for the AI
const messages = giveMeAiMessages({
system: "You are a helpful assistant.",
user: "Tell me a bit about yourself."
});

// Make an OpenAI request and get the validated response
(async () => {
const response = await openAiRequestWithSchema('gpt-4o', messages, responseSchema);
console.log('Validated Response:', response);
})();
```

### Available Functions

#### `openAiRequestWithSchema<T>(model: string, messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[], schema: z.ZodType<T>): Promise<T | null>`

Sends a request to OpenAI and validates the response against a Zod schema.

- `model`: The OpenAI model to use (e.g., `'gpt-4o'`).
- `messages`: An array of system and user messages.
- `schema`: A Zod schema for validating the response.

#### `giveMeAiMessages({ system: string, user: string }): OpenAI.Chat.Completions.ChatCompletionMessageParam[]`

Generates an array of OpenAI chat messages from a system and user prompt.

- `system`: The system message for the assistant.
- `user`: The user message or prompt for the assistant.

#### `craftJsonSchemaPrompt({ instructions: string[], fieldDescriptions: string[], exampleJson: string }): string`

Crafts a detailed JSON schema prompt from provided instructions, field descriptions, and an example JSON string.

- `instructions`: Instructions for the AI.
- `fieldDescriptions`: Descriptions of the fields in the expected output.
- `exampleJson`: An example JSON string.

### Example Use Cases

### Get AI Answers with Validated Responses
Use this package to send prompts and get structured responses that match your Zod schema, making sure the returned data is in the format you expect.

### Automated Prompt Generation
With `craftJsonSchemaPrompt`, you can easily generate detailed prompts with field descriptions and example JSON, useful for generating structured outputs from AI models.

### Quick Chat Setup
Quickly create chat interactions with OpenAI using `giveMeAiMessages`, perfect for conversational agents or simple AI interactions.

## License

This package is licensed under the MIT License. See the [LICENSE](./LICENSE) file for more details.

## Contributing

Feel free to open issues or submit pull requests to improve this package. Contributions are welcome!
13 changes: 13 additions & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import OpenAI from 'openai';
import { z } from 'zod';
import * as ChatAPI from 'openai/src/resources/chat/chat';
export declare const openAiRequestWithSchema: <T>(model: string | ChatAPI.ChatModel, messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[], schema: z.ZodType<T>) => Promise<T | null>;
export declare const giveMeAiMessages: ({ system, user }: {
system: string;
user: string;
}) => OpenAI.Chat.Completions.ChatCompletionMessageParam[];
export declare const craftJsonSchemaPrompt: ({ instructions, fieldDescriptions, exampleJson }: {
instructions: string[];
fieldDescriptions: string[];
exampleJson: string;
}) => string;
54 changes: 54 additions & 0 deletions dist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.craftJsonSchemaPrompt = exports.giveMeAiMessages = exports.openAiRequestWithSchema = void 0;
const openai_1 = require("openai");
const zod_1 = require("openai/helpers/zod");
const openAiRequestWithSchema = async (model, messages, schema) => {
const client = new openai_1.default();
const responseFormat = (0, zod_1.zodResponseFormat)(schema, 'schema');
console.log('responseFormat', responseFormat);
try {
const completion = await client.beta.chat.completions.parse({
model,
messages,
response_format: responseFormat
});
console.log('completion.choices[0].message.content', completion.choices[0].message.content);
if (completion.choices[0].message.content === null) {
return null;
}
const parsedArguments = schema.parse(JSON.parse(completion.choices[0].message.content));
return parsedArguments;
}
catch (error) {
console.error('Error calling OpenAI:', error);
return null;
}
};
exports.openAiRequestWithSchema = openAiRequestWithSchema;
const giveMeAiMessages = ({ system, user }) => {
return [
{
role: 'system',
content: system
},
{
role: 'user',
content: user
}
];
};
exports.giveMeAiMessages = giveMeAiMessages;
const craftJsonSchemaPrompt = ({ instructions, fieldDescriptions, exampleJson }) => {
return `
## INSTRUCTIONS:
${instructions.join('\n')}
## FIELDS DESCRIPTION:
${fieldDescriptions.join('\n')}
## EXAMPLE JSON:
${exampleJson}
`;
};
exports.craftJsonSchemaPrompt = craftJsonSchemaPrompt;
Loading

0 comments on commit 380581e

Please sign in to comment.