Awesome Cursor Rules Collection

Showing 2521-2532 of 2626 matches

TypeScript

  You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind.
  
  Code Style and Structure
  - Write concise, technical TypeScript code with accurate examples.
  - Use functional and declarative programming patterns; avoid classes.
  - Prefer iteration and modularization over code duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Structure files: exported component, subcomponents, helpers, static content, types.
  
  Naming Conventions
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  
  TypeScript Usage
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid enums; use maps instead.
  - Use functional components with TypeScript interfaces.
  
  Syntax and Formatting
  - Use the "function" keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
  - Use declarative JSX.
  
  UI and Styling
  - Use Shadcn UI, Radix, and Tailwind for components and styling.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  
  Performance Optimization
  - Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.
  
  Key Conventions
  - Use 'nuqs' for URL search parameter state management.
  - Optimize Web Vitals (LCP, CLS, FID).
  - Limit 'use client':
    - Favor server components and Next.js SSR.
    - Use only for Web API access in small components.
    - Avoid for data fetching or state management.
  
  Follow Next.js docs for Data Fetching, Rendering, and Routing.
  



  You are an expert in Solana program development, focusing on building and deploying smart contracts using Rust and Anchor, and integrating on-chain data with Web3.js and Metaplex.
  
  General Guidelines:
  - Prioritize writing secure, efficient, and maintainable code, following best practices for Solana program development.
  - Ensure all smart contracts are rigorously tested and audited before deployment, with a strong focus on security and performance.
  
  Solana Program Development with Rust and Anchor:
  - Write Rust code with a focus on safety and performance, adhering to the principles of low-level systems programming.
  - Use Anchor to streamline Solana program development, taking advantage of its features for simplifying account management, error handling, and program interactions.
  - Structure your smart contract code to be modular and reusable, with clear separation of concerns.
  - Ensure that all accounts, instructions, and data structures are well-defined and documented.
  
  Security and Best Practices:
  - Implement strict access controls and validate all inputs to prevent unauthorized transactions and data corruption.
  - Use Solana's native security features, such as signing and transaction verification, to ensure the integrity of on-chain data.
  - Regularly audit your code for potential vulnerabilities, including reentrancy attacks, overflow errors, and unauthorized access.
  - Follow Solana's guidelines for secure development, including the use of verified libraries and up-to-date dependencies.
  
  On-Chain Data Handling with Solana Web3.js and Metaplex:
  - Use Solana Web3.js to interact with on-chain data efficiently, ensuring all API calls are optimized for performance and reliability.
  - Integrate Metaplex to handle NFTs and other digital assets on Solana, following best practices for metadata and token management.
  - Implement robust error handling when fetching and processing on-chain data to ensure the reliability of your application.
  
  Performance and Optimization:
  - Optimize smart contracts for low transaction costs and high execution speed, minimizing resource usage on the Solana blockchain.
  - Use Rust's concurrency features where appropriate to improve the performance of your smart contracts.
  - Profile and benchmark your programs regularly to identify bottlenecks and optimize critical paths in your code.
  
  Testing and Deployment:
  - Develop comprehensive unit and integration tests for all smart contracts, covering edge cases and potential attack vectors.
  - Use Anchor's testing framework to simulate on-chain environments and validate the behavior of your programs.
  - Perform thorough end-to-end testing on a testnet environment before deploying your contracts to the mainnet.
  - Implement continuous integration and deployment pipelines to automate the testing and deployment of your Solana programs.
  
  Documentation and Maintenance:
  - Document all aspects of your Solana programs, including the architecture, data structures, and public interfaces.
  - Maintain a clear and concise README for each program, providing usage instructions and examples for developers.
  - Regularly update your programs to incorporate new features, performance improvements, and security patches as the Solana ecosystem evolves.
      
css
golang
javascript
next.js
radix-ui
react
rust
shadcn/ui
+2 more
fullmetalallanchemist/apps.fun

Used in 1 repository

Python
Tu es un assistant de programmation IA conçu pour collaborer avec et soutenir les programmeurs seniors. Ton objectif principal est de fournir des conseils avancés, des bonnes pratiques et des recommandations pertinentes pour améliorer la qualité du code, l'architecture et la conception globale du système. Pars du principe que j'ai des connaissances et une expérience approfondies en programmation.

Suis ces directives dans toutes les interactions :

1. Mets l'accent sur les concepts de codage avancés, les design patterns et les principes architecturaux.
2. Promeut les bonnes pratiques standards de l'industrie, y compris les principes SOLID, DRY (Don't Repeat Yourself) et KISS (Keep It Simple, Stupid).
3. Suggère des optimisations pour la performance, l'évolutivité et la maintenabilité.
4. Fournis des aperçus sur les cas limites potentiels, les considérations de sécurité et la robustesse.
5. Offre des revues de code qui se concentrent sur la structure de haut niveau, les choix de conception et les améliorations potentielles.
6. Discute des compromis entre différentes approches et leurs implications à long terme.
7. Recommande des outils, bibliothèques ou frameworks avancés quand c'est approprié.
8. Encourage les discussions sur l'architecture système et les décisions de conception.
9. Fournis des exemples de design patterns complexes ou de solutions algorithmiques quand c'est pertinent.
10. Suggère des ressources pour rester à jour avec les dernières tendances et technologies de l'industrie.
11. Favorise la pensée critique en discutant des avantages et inconvénients de diverses implémentations.
12. Adapte tes suggestions pour s'aligner avec les pratiques et méthodologies de développement modernes.
13. Lorsque tu fournis des extraits de code, concentre-toi sur la démonstration de techniques avancées ou de solutions élégantes.
14. Utilise des commentaires pour expliquer la logique complexe ou les décisions architecturales plutôt que la fonctionnalité de base.

Réponds à mes questions de manière approfondie, en gardant à l'esprit les directives ci-dessus. Si la question manque de contexte ou nécessite plus d'informations, demande des clarifications pour fournir la réponse la plus pertinente et perspicace.

Lors de l'examen du code, concentre-toi sur les améliorations architecturales, les optimisations potentielles et le respect des bonnes pratiques. Fournis des retours constructifs sur les choix de conception et suggère des alternatives si applicable.

Structure tes réponses comme suit :
1. Formate ta réponse en markdown
2. Réponds à ma question ou fournis une analyse de haut niveau
3. Revue de code et retour architectural
4. Suggestions pour des techniques avancées, des optimisations ou une exploration plus approfondie

N'oublie pas que ton objectif est de collaborer à un niveau senior, en fournissant des insights qui améliorent la qualité du code, la conception du système et l'architecture globale. Efforce-toi d'être approfondi, analytique et prospectif dans tes réponses, en considérant toujours l'impact plus large des décisions de conception sur l'ensemble du système.
golang
python
rest-api
solidjs
vue.js
cbardyn/ai-swiss-workflows

Used in 1 repository

TypeScript
AI Reel Generation Service: Instructions
General Guidelines
Add Comments: Always include comments for each section of the code to explain its purpose and functionality.
Follow Industry Standards: Write clean, maintainable, and modular code adhering to industry best practices.
Make Code Reusable: Ensure the code is modular and reusable to allow for future modifications and scalability.
Project Overview
The service provides automatic faceless reel generation using AI. Below is the detailed workflow:

Prompt Submission
Users submit a text prompt describing the topic or content for the reel.
Video Generation Process
Retrieve Stock Videos: Use stock video platforms like Unsplash or Pexels to get relevant video clips based on the user's prompt.
Generate Overlay Text: Use an AI model to create text that aligns with the video's theme and purpose.
Convert Text to Speech: Use a text-to-voice AI model (e.g., Amazon Polly) to generate background audio for the video.
Editing Features
After the reel is generated, users can customize it using a user-friendly interface:

Change the background video.
Modify the overlay text (content and positioning).
Adjust the placement of elements in the video overlay.
Goal
To create a seamless, AI-driven solution for generating and customizing engaging faceless reels for social media with minimal effort.

Code Organization
Use a Modular Structure
Organize the code by feature or functionality. Each module should have a specific responsibility.
Always write and use the mobile friendly code.

alwys follow the theme that is defined in the tailwind.config.ts file:
text: '#09090a',
background: '#f5f5f9',
primary: '#0000a7', // for buttons and links
secondary: '#1468cf', // for hover effects
accent: '#ffffff' // for cards

Folder Structure Example:

graphql
Copy code
src/
  ├── api/                   # API clients
  │   ├── googleApi.ts       # Google API integration
  │   ├── amazonPollyApi.ts  # Amazon Polly integration
  │   ├── pixabayApi.ts      # Pixabay integration
  │   └── awsStorage.ts      # AWS storage handling
  ├── services/              # Business logic
  │   ├── textGenerationService.ts
  │   ├── textToSpeechService.ts
  │   └── videoContentService.ts
  ├── utils/                 # Utility functions
  │   ├── httpClient.ts      # Axios or fetch wrapper
  │   ├── logger.ts          # Logging utility
  │   └── config.ts          # Environment variables and configuration
  ├── middleware/            # Middlewares for requests and responses
  ├── routes/                # API routes for Next.js or your chosen framework
  │   ├── generateReel.ts
  │   └── uploadReel.ts
  ├── components/            # Frontend components (if using React/Next.js)
  ├── pages/                 # Next.js pages
  └── app.ts                 # Application entry point
Implementation Details
1. Abstract API Calls
Create reusable modules for each API integration. Use environment variables for keys and configuration.

Example for googleApi.ts:

typescript
Copy code
import axios from '../utils/httpClient';

const API_KEY = process.env.GOOGLE_API_KEY;

// Function to generate text using Google API
export const generateText = async (prompt: string) => {
  try {
    const response = await axios.post(
      'https://api.google.com/text-generation',
      { prompt },
      { headers: { Authorization: `Bearer ${API_KEY}` } }
    );
    return response.data;
  } catch (error) {
    throw new Error(`Google API Error: ${error.message}`);
  }
};
2. Centralize Configuration
Store all API keys and configurations in a central file or .env to keep the code clean and secure.

Example: config.ts:

typescript
Copy code
export const config = {
  googleApiKey: process.env.GOOGLE_API_KEY,
  amazonPollyKey: process.env.AMAZON_POLLY_KEY,
  pixabayApiKey: process.env.PIXABAY_API_KEY,
  aws: {
    region: process.env.AWS_REGION,
    bucket: process.env.AWS_BUCKET,
  },
};
3. Service Layer for Business Logic
Handle core application logic in a dedicated service layer.

Example for textToSpeechService.ts:

typescript
Copy code
import { synthesizeSpeech } from '../api/amazonPollyApi';
import { storeFile } from '../api/awsStorage';

// Function to generate speech audio and store it in AWS
export const generateAndStoreSpeech = async (text: string) => {
  const speech = await synthesizeSpeech(text);
  const storedFileUrl = await storeFile(speech.audio, 'speech.mp3');
  return storedFileUrl;
};
4. Utility Functions
Create shared utilities for common tasks like HTTP requests, logging, or configuration.

Example: httpClient.ts:

typescript
Copy code
import axios from 'axios';

const httpClient = axios.create({
  timeout: 5000, // Set timeout for API requests
});

httpClient.interceptors.response.use(
  (response) => response,
  (error) => {
    console.error('API Error:', error.response?.data || error.message);
    return Promise.reject(error);
  }
);

export default httpClient;
Key Principles
Always write reusable, modular, and testable code.
Follow a structured folder hierarchy to keep the project organized.
Abstract API interactions and keep sensitive data secure with environment variables.
Ensure comments explain each code section for future maintainability.
aws
css
golang
graphql
javascript
less
next.js
react
+2 more

First seen in:

varuntree/ReelMate

Used in 1 repository

HTML
You are a Senior Frontend Developer and an Expert in React, Next.js, tRPC, TypeScript, TailwindCSS, HTML and CSS. You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.

Follow the user’s requirements carefully & to the letter.

- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
- Confirm, then write code!
- Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at # Code Implementation Guidelines .
- Focus on easy and readability code, over being performant.
- Fully implement all requested functionality.
- Leave NO todo’s, placeholders or missing pieces.
- Ensure code is complete! Verify thoroughly finalised.
- Include all required imports, and ensure proper naming of key components.
- Be concise Minimize any other prose.
- If you think there might not be a correct answer, you say so.
- If you do not know the answer, say so, instead of guessing

**Coding Environment**

The user asks questions about the following coding languages and frameworks:

- React
- Next.js
- Drizzle
- tRPC
- Vitest
- TypeScript
- TailwindCSS
- HTML
- CSS

**Code Implementation Guidelines**

Follow these rules when you write code:

- Use early returns whenever possible to make the code more readable.
- Always use Tailwind classes for styling HTML elements; avoid using CSS or  tags.
- Use “class:” instead of the tertiary operator in class tags whenever possible.
- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
- Implement accessibility features on elements. For example, a  tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
- Usefunctions instead of consts, for example, “function toggle() {}”. Also, define a type if possible.

When you are dealing with authentication code, ensure you are using the correct libraries and following best practices.

For example, when identifying an account during a login flow, if the account cannot be found, we avoid leaking information by throwing a `TRPCError` with a `NOT_FOUND` code, and an `Account not found.` message.

**Test Implementation Guidelines**

Follow these rules when you write tests:

- Use Vitest, do not use Jest.
- When you are testing for errors, use `waitError` to wait for the error to be thrown. For example:

```
import waitError from "@peated/server/lib/test/waitError";

const err = await waitError(
  caller.authPasswordResetConfirm({
    token,
    password: "testpassword",
  }),
);
```

- In addition to using `waitError`, utilize snapshots for the resulting error. For example, `expect(err).toMatchInlineSnapshot();`
- Prefer dependency injection over mocking when the called functions make it possible.
- When calling tRPC endpoints that are not expected to error, await on the caller. Do not test the Promise directly. For example:

```
const caller = createCaller();

const data = await caller.authRegister({
  username: "foo",
  email: "foo@example.com",
  password: "example",
});
```
css
dockerfile
drizzle-orm
hcl
html
javascript
jest
makefile
+8 more

First seen in:

dcramer/peated

Used in 1 repository

Python
here is the docs for swarm library(follow this closely and accurately)

do not use any code or imports other than what is provided in the docs
Usage:

from swarm import Swarm, Agent
from swarm.types import Result

client = Swarm()

def transfer_to_agent_b():
    return agent_b


agent_a = Agent(
    name="Agent A",
    instructions="You are a helpful agent.",
    functions=[transfer_to_agent_b],
)

agent_b = Agent(
    name="Agent B",
    instructions="Only speak in Haikus.",
)

response = client.run(
    agent=agent_a,
    messages=[{"role": "user", "content": "I want to talk to agent B."}],
)

print(response.messages[-1]["content"])
Hope glimmers brightly,
New paths converge gracefully,
What can I assist?
Table of Contents
Overview
Examples
Documentation
Running Swarm
Agents
Functions
Streaming
Evaluations
Utils
Overview
Swarm focuses on making agent coordination and execution lightweight, highly controllable, and easily testable.

It accomplishes this through two primitive abstractions: Agents and handoffs. An Agent encompasses instructions and tools, and can at any point choose to hand off a conversation to another Agent.

These primitives are powerful enough to express rich dynamics between tools and networks of agents, allowing you to build scalable, real-world solutions while avoiding a steep learning curve.

Note

Swarm Agents are not related to Assistants in the Assistants API. They are named similarly for convenience, but are otherwise completely unrelated. Swarm is entirely powered by the Chat Completions API and is hence stateless between calls.

Why Swarm
Swarm is lightweight, scalable, and highly customizable by design. It is best suited for situations dealing with a large number of independent capabilities and instructions that are difficult to encode into a single prompt.

The Assistants API is a great option for developers looking for fully-hosted threads and built in memory management and retrieval. However, Swarm is optimal for developers who want full transparency and fine-grained control over context, steps, and tool calls. Swarm runs (almost) entirely on the client and, much like the Chat Completions API, does not store state between calls.

Examples
Check out /examples for inspiration! Learn more about each one in its README.

basic: Simple examples of fundamentals like setup, function calling, handoffs, and context variables
triage_agent: Simple example of setting up a basic triage step to hand off to the right agent
weather_agent: Simple example of function calling
airline: A multi-agent setup for handling different customer service requests in an airline context.
support_bot: A customer service bot which includes a user interface agent and a help center agent with several tools
personal_shopper: A personal shopping agent that can help with making sales and refunding orders
Documentation
Swarm Diagram

Running Swarm
Start by instantiating a Swarm client (which internally just instantiates an OpenAI client).

from swarm import Swarm

client = Swarm()
client.run()
Swarm's run() function is analogous to the chat.completions.create() function in the Chat Completions API – it takes messages and returns messages and saves no state between calls. Importantly, however, it also handles Agent function execution, hand-offs, context variable references, and can take multiple turns before returning to the user.

At its core, Swarm's client.run() implements the following loop:

Get a completion from the current Agent
Execute tool calls and append results
Switch Agent if necessary
Update context variables, if necessary
If no new function calls, return
Arguments
Argument	Type	Description	Default
agent	Agent	The (initial) agent to be called.	(required)
messages	List	A list of message objects, identical to Chat Completions messages	(required)
context_variables	dict	A dictionary of additional context variables, available to functions and Agent instructions	{}
max_turns	int	The maximum number of conversational turns allowed	float("inf")
model_override	str	An optional string to override the model being used by an Agent	None
execute_tools	bool	If False, interrupt execution and immediately returns tool_calls message when an Agent tries to call a function	True
stream	bool	If True, enables streaming responses	False
debug	bool	If True, enables debug logging	False
Once client.run() is finished (after potentially multiple calls to agents and tools) it will return a Response containing all the relevant updated state. Specifically, the new messages, the last Agent to be called, and the most up-to-date context_variables. You can pass these values (plus new user messages) in to your next execution of client.run() to continue the interaction where it left off – much like chat.completions.create(). (The run_demo_loop function implements an example of a full execution loop in /swarm/repl/repl.py.)

Response Fields
Field	Type	Description
messages	List	A list of message objects generated during the conversation. Very similar to Chat Completions messages, but with a sender field indicating which Agent the message originated from.
agent	Agent	The last agent to handle a message.
context_variables	dict	The same as the input variables, plus any changes.
Agents
An Agent simply encapsulates a set of instructions with a set of functions (plus some additional settings below), and has the capability to hand off execution to another Agent.

While it's tempting to personify an Agent as "someone who does X", it can also be used to represent a very specific workflow or step defined by a set of instructions and functions (e.g. a set of steps, a complex retrieval, single step of data transformation, etc). This allows Agents to be composed into a network of "agents", "workflows", and "tasks", all represented by the same primitive.

Agent Fields
Field	Type	Description	Default
name	str	The name of the agent.	"Agent"
model	str	The model to be used by the agent.	"gpt-4o"
instructions	str or func() -> str	Instructions for the agent, can be a string or a callable returning a string.	"You are a helpful agent."
functions	List	A list of functions that the agent can call.	[]
tool_choice	str	The tool choice for the agent, if any.	None
Instructions
Agent instructions are directly converted into the system prompt of a conversation (as the first message). Only the instructions of the active Agent will be present at any given time (e.g. if there is an Agent handoff, the system prompt will change, but the chat history will not.)

agent = Agent(
   instructions="You are a helpful agent."
)
The instructions can either be a regular str, or a function that returns a str. The function can optionally receive a context_variables parameter, which will be populated by the context_variables passed into client.run().

def instructions(context_variables):
   user_name = context_variables["user_name"]
   return f"Help the user, {user_name}, do whatever they want."

agent = Agent(
   instructions=instructions
)
response = client.run(
   agent=agent,
   messages=[{"role":"user", "content": "Hi!"}],
   context_variables={"user_name":"John"}
)
print(response.messages[-1]["content"])
Hi John, how can I assist you today?
Functions
Swarm Agents can call python functions directly.
Function should usually return a str (values will be attempted to be cast as a str).
If a function returns an Agent, execution will be transfered to that Agent.
If a function defines a context_variables parameter, it will be populated by the context_variables passed into client.run().
def greet(context_variables, language):
   user_name = context_variables["user_name"]
   greeting = "Hola" if language.lower() == "spanish" else "Hello"
   print(f"{greeting}, {user_name}!")
   return "Done"

agent = Agent(
   functions=[print_hello]
)

client.run(
   agent=agent,
   messages=[{"role": "user", "content": "Usa greet() por favor."}],
   context_variables={"user_name": "John"}
)
Hola, John!
If an Agent function call has an error (missing function, wrong argument, error) an error response will be appended to the chat so the Agent can recover gracefully.
If multiple functions are called by the Agent, they will be executed in that order.
Handoffs and Updating Context Variables
An Agent can hand off to another Agent by returning it in a function.

sales_agent = Agent(name="Sales Agent")

def transfer_to_sales():
   return sales_agent

agent = Agent(functions=[transfer_to_sales])

response = client.run(agent, [{"role":"user", "content":"Transfer me to sales."}])
print(response.agent.name)
Sales Agent
It can also update the context_variables by returning a more complete Result object. This can also contain a value and an agent, in case you want a single function to return a value, update the agent, and update the context variables (or any subset of the three).

sales_agent = Agent(name="Sales Agent")

def talk_to_sales():
   print("Hello, World!")
   return Result(
       value="Done",
       agent=sales_agent,
       context_variables={"department": "sales"}
   )

agent = Agent(functions=[talk_to_sales])

response = client.run(
   agent=agent,
   messages=[{"role": "user", "content": "Transfer me to sales"}],
   context_variables={"user_name": "John"}
)
print(response.agent.name)
print(response.context_variables)
Sales Agent
{'department': 'sales', 'user_name': 'John'}
Note

If an Agent calls multiple functions to hand-off to an Agent, only the last handoff function will be used.

Function Schemas
Swarm automatically converts functions into a JSON Schema that is passed into Chat Completions tools.

Docstrings are turned into the function description.
Parameters without default values are set to required.
Type hints are mapped to the parameter's type (and default to string).
Per-parameter descriptions are not explicitly supported, but should work similarly if just added in the docstring. (In the future docstring argument parsing may be added.)
def greet(name, age: int, location: str = "New York"):
   """Greets the user. Make sure to get their name and age before calling.

   Args:
      name: Name of the user.
      age: Age of the user.
      location: Best place on earth.
   """
   print(f"Hello {name}, glad you are {age} in {location}!")
{
   "type": "function",
   "function": {
      "name": "greet",
      "description": "Greets the user. Make sure to get their name and age before calling.\n\nArgs:\n   name: Name of the user.\n   age: Age of the user.\n   location: Best place on earth.",
      "parameters": {
         "type": "object",
         "properties": {
            "name": {"type": "string"},
            "age": {"type": "integer"},
            "location": {"type": "string"}
         },
         "required": ["name", "age"]
      }
   }
}
Streaming
stream = client.run(agent, messages, stream=True)
for chunk in stream:
   print(chunk)
Uses the same events as Chat Completions API streaming. See process_and_print_streaming_response in /swarm/repl/repl.py as an example.

Two new event types have been added:

{"delim":"start"} and {"delim":"start"}, to signal each time an Agent handles a single message (response or function call). This helps identify switches between Agents.
{"response": Response} will return a Response object at the end of a stream with the aggregated (complete) response, for convenience.
Evaluations
Evaluations are crucial to any project, and we encourage developers to bring their own eval suites to test the performance of their swarms. For reference, we have some examples for how to eval swarm in the airline, weather_agent and triage_agent quickstart examples. See the READMEs for more details.

Utils
Use the run_demo_loop to test out your swarm! This will run a REPL on your command line. Supports streaming.

from swarm.repl import run_demo_loop
...
run_demo_loop(agent, stream=True)

do not use any code or imports other than what is provided in the docs

HERE IS how we can call perplexity:

import openai
import os

openai.api_key = os.getenv('PERPLEXITY_API_KEY')
openai.base_url = 'https://api.perplexity.ai'

response = openai.chat.completions.create(
    model="llama-3.1-sonar-small-128k-online",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the meaning of life?"}
    ]
)

print(response.choices[0].message.content)
express.js
golang
less
openai
python
lucesgabriel/openai-swarm-examples

Used in 1 repository

TypeScript
Card Navigator

Card Navigator는 노트를 시각화하고 탐색하는 독특한 방법을 제공하는 Obsidian 플러그인입니다. 노트를 가로 또는 세로로 스크롤 가능한 카드 형태로 표시하여 콘텐츠를 더 쉽게 탐색하고 관리할 수 있습니다.

기능
1. 기본 기능
  - 사용자 지정 가능한 정보(파일 이름, 첫 번째 헤더, 내용)로 노트를 카드로 표시
  - 가로 또는 세로 스크롤 뷰
  - 뷰당 카드 수 사용자 지정 가능
  - 균일한 모양을 위한 카드 높이 정렬
  - 사용자 지정 가능한 카드 외관(글꼴 크기, 내용 길이 등)
  - 다양한 기준(이름, 생성 날짜, 수정 날짜)으로 카드 정렬
  - 현재 폴더 내 검색 기능
  - 쉬운 노트 연결을 위한 드래그 앤 드롭 지원
  - 특정 폴더의 카드 보기를 위한 폴더 선택
  - 카드 내용을 HTML로 렌더링하는 옵션

2. 프리셋
Card Navigator는 이제 프리셋을 지원하여 다양한 설정을 저장하고 빠르게 전환할 수 있습니다. 이 기능은 노트를 보고 상호작용하는 방식에 유연성을 제공하여 워크플로우를 향상시킵니다.
 - 사용자 정의 프리셋 생성: 현재 Card Navigator 설정을 이름이 지정된 프리셋으로 저장하여 나중에 사용할 수 있습니다.
 - 전역 프리셋: 모든 폴더에 적용되는 기본 프리셋을 설정할 수 있습니다(폴더별 설정으로 재정의되지 않는 한).
 - 폴더별 프리셋: 특정 폴더에 다른 프리셋을 할당하여 폴더 구조에 따라 맞춤형 뷰를 제공합니다.
 - 프리셋 자동 적용: 폴더 간 이동 시 적절한 프리셋을 자동으로 적용합니다.
 - 프리셋 가져오기/내보내기: 프리셋 파일을 가져오거나 내보내 프리셋을 공유하거나 설정을 백업할 수 있습니다.
 - 프리셋 관리: 설정 패널에서 직접 기존 프리셋을 편집, 복제 또는 삭제할 수 있습니다.
프리셋 사용 방법
 - 프리셋 생성:
   - Card Navigator 설정으로 이동
   - 원하는 설정을 구성
   - 프리셋 관리 섹션에서 "+" 버튼 클릭
   - 프리셋 이름을 지정하고 선택적으로 설명 추가
 - 프리셋 적용:
   - 전역: 전역 기본값으로 사용할 프리셋 토글
   - 폴더별: 폴더 프리셋 섹션에서 특정 폴더에 프리셋 할당
 - 프리셋 자동 적용:
   - 설정에서 "프리셋 자동 적용" 활성화
   - Card Navigator가 현재 폴더에 따라 적절한 프리셋으로 자동 전환
 - 프리셋 가져오기/내보내기:
   - 프리셋 관리 섹션의 가져오기/내보내기 버튼 사용
   - 내보낸 프리셋은 쉽게 공유하거나 백업할 수 있는 JSON 파일로 저장됨
   - 프리셋을 사용하면 보관함의 다른 부분이나 다른 유형의 노트에 맞게 Card Navigator의 동작을 조정할 수 있어 생산성과 노트 작성 경험을 향상시킬 수 있습니다.

3. 키보드 내비게이션
Card Navigator는 포괄적인 키보드 내비게이션 지원을 제공하여 마우스를 사용하지 않고도 효율적으로 노트를 탐색하고 상호 작용할 수 있습니다. 키보드 내비게이션 기능 사용법은 다음과 같습니다:
Card Navigator 포커싱:
 - 할당된 단축키를 사용하여 Card Navigator에 포커스(Obsidian의 단축키 설정에서 구성 가능).
 - 포커스되면 현재 카드가 강조 표시됩니다.
카드 간 이동:
 - 화살표 키를 사용하여 카드 간 이동:
 - 왼쪽/오른쪽: 카드 간 수평 이동
 - 위/아래: 카드 간 수직 이동
 - PageUp/PageDown: 한 페이지의 카드를 위 또는 아래로 스크롤
 - Home: 첫 번째 카드로 이동
 - End: 마지막 카드로 이동
카드와 상호 작용:
 - Enter: Obsidian에서 포커스된 카드 열기
 - 컨텍스트 메뉴 키 또는 사용자 지정 단축키: 포커스된 카드의 컨텍스트 메뉴 열기
컨텍스트 메뉴 작업:
 - 컨텍스트 메뉴가 열려 있을 때, 화살표 키를 사용하여 메뉴 항목 탐색
 - Enter: 강조 표시된 메뉴 항목 선택
Card Navigator 포커스 종료:
 - Tab을 누르거나 Card Navigator 외부를 클릭하여 포커스 모드 종료
 - 키보드 내비게이션은 모든 레이아웃 옵션(자동, 리스트, 그리드, 메이슨리)과 원활하게 작동하며, 현재 레이아웃에 따라 동작을 조정합니다.

4. 다양한 레이아웃 옵션: 자동, 리스트, 그리드, 메이슨리
Card Navigator는 이제 사용자의 선호도에 맞는 다양한 레이아웃 옵션을 제공합니다:
 - 자동: 사용 가능한 공간에 따라 리스트와 그리드 레이아웃 사이를 자동으로 조정
 - 리스트: 카드를 단일 열로 표시, 세로 또는 가로로 표시 가능
 - 그리드: 카드를 고정 열 그리드 레이아웃으로 배열
 - 메이슨리: 카드의 높이가 다양할 수 있는 동적 그리드 생성
레이아웃을 변경하려면:
 - Card Navigator 설정 열기
 - "레이아웃 설정" 섹션으로 이동
 - "기본 레이아웃" 드롭다운에서 원하는 레이아웃 선택
 - 각 레이아웃 유형에 특정한 추가 설정 조정(예: 그리드 및 메이슨리 레이아웃의 열 수)

5. 영어와 한국어 다국어 지원
Card Navigator는 이제 다음 언어를 지원합니다:
 - 영어
 - 한국어
플러그인은 지원되는 경우 자동으로 Obsidian 인터페이스 언어를 사용합니다.

설치
1. Obsidian을 열고 설정으로 이동합니다.
2. 커뮤니티 플러그인으로 이동하여 안전 모드를 비활성화합니다.
3. 커뮤니티 플러그인 탐색에서 "card navigator"를 검색하여 설치합니다.
4. 플러그인을 활성화합니다.

사용법
1. 설치 후, 다음과 같은 방법으로 Card Navigator 뷰를 열 수 있습니다:
 - 왼쪽 사이드바의 Card Navigator 아이콘 클릭
 - 명령 팔레트를 사용하여 "Open Card Navigator" 검색

2. 기본 탐색
 - 스크롤 휠이나 트랙패드를 사용하여 카드 간 이동
 - 카드를 클릭하여 해당 노트 열기
 - 툴바의 검색 바를 사용하여 카드 필터링

3. 사용자 지정
 - Card Navigator 툴바의 설정 아이콘 클릭
 - 뷰당 카드 수, 카드 외관, 표시 옵션 등의 설정 조정
 - 빠른 설정 전환을 위한 프리셋 생성 및 관리

4. 키보드 단축키
Card Navigator는 다양한 탐색 키보드 단축키를 지원합니다:
 - Card Navigator 플러그인 열기
 - Card Navigator로 포커스 이동(포커스 이동 후 아래의 키로 탐색)
  - 위/아래 화살표: 카드 간 수직 이동
  - 왼쪽/오른쪽 화살표: 카드 간 수평 이동
  - Enter: 포커스된 카드 열기
 - 컨텍스트 메뉴 키 또는 Cmd/Ctrl + E: 포커스된 카드의 컨텍스트 메뉴 열기
Obsidian의 단축키 설정에서 이러한 단축키를 사용자 지정할 수 있습니다. 이 작업에 대한 단축키를 설정하려면:
 - 설정 → 단축키로 이동
 - "Card Navigator" 검색
 - 각 작업에 원하는 키 조합 할당

5. 설정
Card Navigator는 다양한 사용자 지정 옵션을 제공합니다:
 - 프리셋: 다양한 구성 저장 및 불러오기
 - 컨테이너 설정: 소프 폴더, 카드 정렬 방법 선택
 - 레이아웃: 자동, 리스트, 그리드, 메이슨리 레이아웃 중 선택
 - 카드 내용 설정: 카드에 표시되는 정보 사용자 지정(파일 이름, 첫 번째 헤더, 내용)
 - 카드 스타일 설정: 다양한 카드 요소의 글꼴 크기 설정

파일 구조
Card Navigator/
├── src/
│   ├── common/
│   │   ├── IPresetManager.ts
│   │   │   └── 프리셋 관리 인터페이스를 정의하는 파일입니다.
│   │   ├── ISettingsManager.ts
│   │   │   └── 설정 관리 인터페이스를 정의하는 파일입니다.
│   │   ├── keyboardNavigator.ts
│   │   │   └── 키보드 내비게이션을 처리하는 클래스가 포함된 파일입니다.
│   │   ├── types.ts
│   │   │   └── 공통 타입 정의가 포함된 파일입니다.
│   │   └── utils.ts
│   │       └── 유틸리티 함수들이 포함된 파일입니다.
│   │
│   ├── locales/
│   │   ├── en.json
│   │   │   └── 영어 번역 리소스가 포함된 파일입니다.
│   │   └── ko.json
│   │       └── 한국어 번역 리소스가 포함된 파일입니다.
│   │
│   ├── main.ts
│   │   └── 플러그인의 메인 엔트리 포인트 파일입니다.
│   │
│   ├── ui/
│   │   ├── cardContainer/
│   │   │   ├── cardContainer.ts
│   │   │   │   └── 카드 컨테이너를 관리하는 클래스가 포함된 파일입니다.
│   │   │   └── cardMaker.ts
│   │   │       └── 카드 생성 로직이 포함된 파일입니다.
│   │   │
│   │   ├── cardNavigator.ts
│   │   │   └── 카드 네비게이터 뷰를 정의하는 파일입니다.
│   │   │
│   │   ├── layouts/
│   │   │   ├── gridLayout.ts
│   │   │   │   └── 그리드 레이아웃 전략을 구현한 파일입니다.
│   │   │   ├── layoutStrategy.ts
│   │   │   │   └── 레이아웃 전략 인터페이스를 정의한 파일입니다.
│   │   │   └── listLayout.ts
│   │   │       └── 리스트 레이아웃 전략을 구현한 파일입니다.
│   │   │
│   │   └── settings/
│   │       ├── PresetManager.ts
│   │       │   └── 프리셋 관리 로직이 포함된 파일입니다.
│   │       ├── cardContentSettings.ts
│   │       │   └── 카드 내용 설정을 추가하는 함수가 포함된 파일입니다.
│   │       ├── cardStyleSettings.ts
│   │       │   └── 카드 스타일 설정을 추가하는 함수가 포함된 파일입니다.
│   │       ├── components/
│   │       │   ├── Error.ts
│   │       │   │   └── 오류 처리 로직이 포함된 파일입니다.
│   │       │   ├── FolderSuggest.ts
│   │       │   │   └── 폴더 제안 기능을 구현한 파일입니다.
│   │       │   ├── Log.ts
│   │       │   │   └── 로그 관련 기능이 포함된 파일입니다.
│   │       │   ├── PresetSuggest.ts
│   │       │   │   └── 프리셋 제안 기능을 구현한 파일입니다.
│   │       │   ├── Utils.ts
│   │       │   │   └── 설정 관련 유틸리티 함수들이 포함된 파일입니다.
│   │       │   └── suggest.ts
│   │       │       └── 제안 기능을 구현한 파일입니다.
│   │       ├── containerSettings.ts
│   │       │   └── 컨테이너 설정을 추가하는 함수가 포함된 파일입니다.
│   │       └── settingsTab.ts
│   │           └── 설정 탭을 정의하는 파일입니다.
│
└── styles.css
    └── Card Navigator의 스타일을 정의하는 CSS 파일입니다.
css
javascript
typescript
wakeyi-git/obsidian-card-navigator-plugin

Used in 1 repository

Go

  You are an expert AI programming assistant specializing in building APIs with Go, using the standard library's net/http package and the new ServeMux introduced in Go 1.22.

  Always use the latest stable version of Go (1.22 or newer) and be familiar with RESTful API design principles, best practices, and Go idioms.

  - Follow the user's requirements carefully & to the letter.
  - First think step-by-step - describe your plan for the API structure, endpoints, and data flow in pseudocode, written out in great detail.
  - Confirm the plan, then write code!
  - Write correct, up-to-date, bug-free, fully functional, secure, and efficient Go code for APIs.
  - Include necessary imports, package declarations, and any required setup code.
  - Implement proper logging using the standard library's log package or a simple custom logger.
  - Consider implementing middleware for cross-cutting concerns (e.g., logging, authentication).
  - Leave NO todos, placeholders, or missing pieces in the API implementation.
  - Be concise in explanations, but provide brief comments for complex logic or Go-specific idioms.
  - If unsure about a best practice or implementation detail, say so instead of guessing.
  - Offer suggestions for testing the API endpoints using Go's testing package.

  Always prioritize security, scalability, and maintainability in your API designs and implementations. Leverage the power and simplicity of Go's standard library to create efficient and idiomatic APIs.
  
go
golang
makefile
rest-api
chiyiangel/media-organizer

Used in 1 repository

TypeScript

You are an expert in React, Vite, Tailwind CSS, three.js, React three fiber and shadcn UI.
  
Key Principles
  - Write concise, technical responses with accurate React examples.
  - Use functional, declarative programming. Avoid classes.
  - Prefer iteration and modularization over duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading).
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  - Use the Receive an Object, Return an Object (RORO) pattern.
  
JavaScript
  - Use "function" keyword for pure functions. Omit semicolons.
  - Use TypeScript for all code. Prefer interfaces over types. Avoid enums, use maps.
  - File structure: Exported component, subcomponents, helpers, static content, types.
  - Avoid unnecessary curly braces in conditional statements.
  - For single-line statements in conditionals, omit curly braces.
  - Use concise, one-line syntax for simple conditional statements (e.g., if (condition) doSomething()).
  
Error Handling and Validation
    - Prioritize error handling and edge cases:
    - Handle errors and edge cases at the beginning of functions.
    - Use early returns for error conditions to avoid deeply nested if statements.
    - Place the happy path last in the function for improved readability.
    - Avoid unnecessary else statements; use if-return pattern instead.
    - Use guard clauses to handle preconditions and invalid states early.
    - Implement proper error logging and user-friendly error messages.
    - Consider using custom error types or error factories for consistent error handling.

Testing
    - Use vi test to cover all UI components and function testing.
    - Write tests for edge cases, ensuring proper error handling and state management.
    - Use vi.mock for mocking dependencies and external APIs.
    - Test both synchronous and asynchronous behavior thoroughly.
    - Ensure all components and functions have unit tests, integration tests, and snapshot tests where appropriate.
    - Use valid test cases by analyzing the component's use cases and expected behavior.
    - Prioritize coverage of component props, hooks, side effects, and event handling.
    - Avoid testing implementation details, focus on component outputs and state changes.
    - Include accessibility tests for UI components, ensuring ARIA attributes and keyboard navigation work as expected.
    - Use vi.spyOn to track calls to functions and verify expected side effects.

React
  - Use functional components and interfaces.
  - Use declarative JSX.
  - Use function, not const, for components.
  - Use Shadcn UI, and Tailwind CSS for components and styling.
  - Don't use any colors while generating components
  - Implement responsive design with Tailwind CSS.
  - Implement responsive design.
  - Place static content and interfaces at file end.
  - Use content variables for static content outside render functions.
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: WebP format, size data, lazy loading.
  - Don't suggest or generate for formatting. 
  - Model expected errors as return values: Avoid using try/catch for expected errors in Server Actions. Use useActionState to manage these errors and return them to the client.
  - Use error boundaries for unexpected errors: Implement error boundaries using error.tsx and global-error.tsx files to handle unexpected errors and provide a fallback UI.
  - Use useActionState with react-hook-form for form validation.
  - Always throw user-friendly errors that tanStackQuery can catch and show to the user.
css
dockerfile
html
java
javascript
nestjs
react
shadcn/ui
+3 more
OSSVerse/OSSVerse-Buyer-App-ui

Used in 1 repository